Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

C++ Tutorial

C++ HOME C++ Intro C++ Get Started C++ Syntax C++ Output C++ Comments C++ Variables C++ User Input C++ Data Types C++ Operators C++ Type Conversion C++ Strings C++ Math C++ Booleans C++ If...Else C++ Switch C++ While Loop C++ For Loop C++ Break/Continue C++ Arrays C++ Structures C++ Enums C++ References C++ Pointers C++ Memory Mgmt

C++ Functions

C++ Functions C++ Function Parameters C++ Function Overloading C++ Scope C++ Recursion C++ Lambda

C++ Classes

C++ OOP C++ Classes/Objects C++ Class Methods C++ Constructors C++ Destructors C++ The this Pointer C++ Access Specifiers C++ Encapsulation C++ Friend Functions C++ Inheritance C++ Polymorphism C++ Operator Overload C++ Templates

C++ Files

C++ Files

C++ Date

C++ Date

C++ Errors

C++ Errors C++ Debugging C++ Exceptions C++ Input Validation

C++ Problem Solving

C++ Problem Solving C++ Build the Logic C++ Test Cases

C++ Data Structures

C++ Data Structures & STL C++ Vectors C++ List C++ Stacks C++ Queues C++ Deque C++ Sets C++ Maps C++ Unordered Map C++ Unordered Set C++ Iterators C++ Algorithms

C++ Namespaces

C++ Namespaces

C++ Projects

C++ Projects

C++ Cert

C++ Certificate

C++ How To

C++ How Tos

C++ Examples

C++ Examples C++ Real-Life Examples C++ Compiler C++ Exercises C++ Quiz C++ Code Challenges C++ Practice Problems C++ Syllabus C++ Study Plan

C++ Reference

C++ Reference C++ Keywords C++ <algorithm> C++ <cctype> C++ <cmath> C++ <cstdlib> C++ <cstring> C++ <ctime> C++ <deque> C++ <fstream> C++ <iomanip> C++ <iostream> C++ <list> C++ <map> C++ <memory> C++ <queue> C++ <random> C++ <set> C++ <sstream> C++ <stack> C++ <stdexcept> C++ <string> C++ <unordered_map> C++ <unordered_set> C++ <vector>


C++ Problem Solving


Share

What is Problem Solving?

You now know a lot of C++: variables, operators, conditions, loops, arrays and functions. The next step is to use them to solve problems.

A problem tells you what a program must do, but not how. So where do you start? Most programmers use four steps:

  1. Understand the problem
  2. Plan the solution
  3. Write the code
  4. Test the code

In this chapter, we use the four steps to solve one of our C++ Practice Problems, from start to finish. Then it is your turn to solve it in our practice editor.


The Problem

This problem is called Celsius to Fahrenheit. Celsius and Fahrenheit are two ways to measure temperature. Here is the problem:

Read a temperature in Celsius from input.

Use this formula: fahrenheit = celsius * 9/5 + 32

Print the result like this: 25 Celsius = 77.0 Fahrenheit

You do not need to know how to convert temperatures. The problem gives you the formula, and your job is to turn it into code. Many problems work like this.


Step 1: Understand the Problem

Before you write any code, find out what goes in, and what must come out:

  • Input: a whole number, the temperature in Celsius. For example 25.
  • Output: one line of text, exactly like 25 Celsius = 77.0 Fahrenheit.

Then solve the example by hand. Put 25 into the formula, and calculate from left to right: 25 * 9 is 225, 225 / 5 is 45, and 45 + 32 is 77. That matches the 77.0 in the example output.

If you can solve the problem by hand, you know what the program must do.


Step 2: Plan the Solution

Write the steps in plain words, before you write any C++ code. This is called pseudocode (code written in plain words, that no computer can run):

read celsius
fahrenheit = celsius * 9 / 5 + 32
print the text: celsius Celsius = fahrenheit Fahrenheit

Each line is one small job. Now you only need to turn each line into C++ code.


Step 3: Write the Code

Turn each line of the plan into C++. To keep it simple, we put the temperature directly in the code, instead of reading it from input:

Example

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
  int celsius = 25;
  double fahrenheit = celsius * 9 / 5 + 32;
  cout << fixed << setprecision(1);
  cout << celsius << " Celsius = " << fahrenheit << " Fahrenheit\n";
  return 0;
}

Result:

25 Celsius = 77.0 Fahrenheit
Try it Yourself »

fixed and setprecision(1) make cout print fahrenheit with one decimal: 77.0. Without them, cout prints 77 (see Decimal Precision). The output is exactly what the problem asks for. Are we done? Not yet!


Step 4: Test the Code

One correct answer does not mean that the program always works. Test it with more temperatures, where you know the right answer.

Choose a temperature below, and follow it through the program:

Code


Inside the program

Output

Expected

Explanation

The program passes four tests, but fails with 37. In C++, an int divided by an int gives an int, and the decimals are cut off (see Arithmetic Operators).

Why did the other tests not find the bug? Because 225, 0, 900 and -360 can all be divided by 5 with nothing left over. That is why you should test many different values.


Fix and Test Again

To fix the bug, write 9.0 instead of 9. Now C++ uses decimal division, and keeps the decimals.

It is also a good idea to put the code in a function. Then you can test all the temperatures in one run:

Example

#include <iostream>
#include <iomanip>
using namespace std;

void convert(int celsius) {
  double fahrenheit = celsius * 9.0 / 5 + 32;
  cout << celsius << " Celsius = " << fahrenheit << " Fahrenheit\n";
}

int main() {
  cout << fixed << setprecision(1);
  convert(25);
  convert(0);
  convert(100);
  convert(-40);
  convert(37);
  return 0;
}

Result:

25 Celsius = 77.0 Fahrenheit
0 Celsius = 32.0 Fahrenheit
100 Celsius = 212.0 Fahrenheit
-40 Celsius = -40.0 Fahrenheit
37 Celsius = 98.6 Fahrenheit
Try it Yourself »

All five tests pass now, also 37.



Your Turn

Now solve Celsius to Fahrenheit yourself, in our practice editor. The starter code already reads the temperature from input, with cin (see User Input). It also includes <iomanip>, so you can print one decimal with fixed and setprecision(). You write the rest.

When you press Submit, your program is checked with several temperatures. You will learn how this works in the Test Cases chapter.


Tips for Solving Problems

  • Read the problem twice, and find the input and the output.
  • Solve one example by hand, before you write any code.
  • Test more than the example. Also try 0, negative numbers, and values that give decimals.
  • If the output is wrong, print your variables to see what they contain (see Debugging).



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.