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

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++ 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++ Functions

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

C++ Classes

C++ OOP C++ Classes/Objects C++ Class Methods C++ Constructors C++ Access Specifiers C++ Encapsulation C++ Inheritance C++ Polymorphism C++ Files C++ Exceptions C++ Date

C++ Data Structures

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

C++ How To

C++ Add Two Numbers C++ Random Numbers

C++ Reference

C++ Reference C++ Keywords C++ <iostream> C++ <fstream> C++ <cmath> C++ <string> C++ <cstring> C++ <ctime> C++ <vector> C++ <algorithm>

C++ Examples

C++ Examples C++ Real-Life Examples C++ Compiler C++ Exercises C++ Quiz C++ Certificate


C++ Real-Life Examples


Practical Examples

This page contains a list of practical examples used in real world projects.


Variables and Data Types

Example

Use variables to store different data of a college student:

// Student data
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25;
char studentGrade = 'B';

// Print variables
cout << "Student ID: " << studentID << "\n";
cout << "Student Age: " << studentAge << "\n";
cout << "Student Fee: " << studentFee << "\n";
cout << "Student Grade: " << studentGrade << "\n";
Try it Yourself »

Example

Calculate the area of a rectangle (by multiplying the length and width):

// Create integer variables
int length = 4;
int width = 6;
int area;

// Calculate the area of a rectangle
area = length * width;

// Print the variables
cout << "Length is: " << length << "\n";
cout << "Width is: " << width << "\n";
cout << "Area of the rectangle is: " << area << "\n";
Try it Yourself »

Example

Use different data types to calculate and output the total cost of a number of items:

// Create variables of different data types
int items = 50;
double cost_per_item = 9.99;
double total_cost = items * cost_per_item;
char currency = '$';

// Print variables
cout << "Number of items: " << items << "\n";
cout << "Cost per item: " << cost_per_item << "" << currency << "\n";
cout << "Total cost = " << total_cost << "" << currency << "\n";
Try it Yourself »

For a tutorial about variables and data types in C++, visit our Variables Chapter and Data Types Chapter.


Strings

Example

Use strings to create a simple welcome message:

string message = "Good to see you, ";
string fname = "John";

cout << greeting + fname;
Try it Yourself »

For a tutorial about strings in C++, visit our Strings Chapter.


Booleans

Example

Find out if a person is old enough to vote:

int myAge = 25;
int votingAge = 18;

cout << (myAge >= votingAge); // returns 1 (true), meaning 25 year olds are allowed to vote!
Try it Yourself »

For a tutorial about booleans in C++, visit our Booleans Chapter.


Conditions (If..Else)

Example

Check whether the user enters the correct code:

int doorCode = 1337;

if (doorCode == 1337) {
  cout << "Correct code.\nThe door is now open.\n";
} else {
  cout << "Wrong code.\nThe door remains closed.\n";
}
Try it Yourself »

Example

Find out if a number is positive or negative:

int myNum = 10; // Is this a positive or negative number?

if (myNum > 0) {
  cout << "The value is a positive number.\n";
} else if (myNum < 0) {
  cout << "The value is a negative number.\n";
} else {
  cout << "The value is 0.\n";
}
Try it Yourself »

Example

Find out if a person is old enough to vote:

int myNum = 10; // Is this a positive or negative number?

if (myNum > 0) {
  cout << "The value is a positive number.\n";
} else if (myNum < 0) {
  cout << "The value is a negative number.\n";
} else {
  cout << "The value is 0.\n";
}
Try it Yourself »

Example

Find out if a number is even or odd:

int myNum = 5;

if (myNum % 2 == 0) {
  cout << myNum << " is even.\n";
} else {
  cout << myNum << " is odd.\n";
}
Try it Yourself »

For a tutorial about conditions in C++, visit our If..Else Chapter.


Switch

Example

Use the weekday number to calculate and output the weekday name:

int day = 4;
switch (day) {
  case 1:
    cout << "Monday";
    break;
  case 2:
    cout << "Tuesday";
    break;
  case 3:
    cout << "Wednesday";
    break;
  case 4:
    cout << "Thursday";
    break;
  case 5:
    cout << "Friday";
    break;
  case 6:
    cout << "Saturday";
    break;
  case 7:
    cout << "Sunday";
    break;
}
// Outputs "Thursday" (day 4)
Try it Yourself »

For a tutorial about switch in C++, visit our Switch Chapter.


While Loops

Example

Create a simple "countdown" program:

int countdown = 3;

while (countdown > 0) {
  cout << countdown << "\n";
  countdown--;
}

cout << "Happy New Year!!\n";
Try it Yourself »

Example

Create a program that only print even numbers between 0 and 10 (inclusive):

int i = 0;

while (i <= 10) {
  cout << i << "\n";
  i += 2;
}
Try it Yourself »

Example

Use a while loop to reverse some numbers:

// A variable with some specific numbers
int numbers = 12345;

// A variable to store the reversed number
int revNumbers = 0;

// Reverse and reorder the numbers
while (numbers) {
  // Get the last number of 'numbers' and add it to 'revNumbers'
  revNumbers = revNumbers * 10 + numbers % 10;
  // Remove the last number of 'numbers'
  numbers /= 10;
}

cout << "Reversed numbers: " << revNumbers << "\n";
Try it Yourself »

Example

Use a while loop together with an if else statement to play a game of Yatzy:

int dice = 1;

while (dice <= 6) {
  if (dice < 6) {
    cout << "No Yatzy\n";
  } else {
    cout << "Yatzy!\n";
  }
  dice = dice + 1;
}
Try it Yourself »

For a tutorial about while loops in C++, visit our While Loops Chapter.


For Loops

Example

Use a for loop to create a program that counts to 100 by tens:

for (int i = 0; i <= 100; i += 10) {
  cout << i << "\n";
}
Try it Yourself »

Example

Use a for loop to create a program that only print even values between 0 and 10:

for (int i = 0; i <= 10; i = i + 2) {
  cout << i << "\n";
}
Try it Yourself »

Example

Use a for loop to create a program that only prints odd numbers:

for (int i = 1; i <= 10; i = i + 2) {
  cout << i << "\n";
}
Try it Yourself »

Example

Use a for loop to print the powers of 2 up to 512:

for (int i = 2; i <= 512; i *= 2) {
  cout << i << "\n";
}
Try it Yourself »

Example

Use a for loop to create a program that prints the multiplication table of a specified number (2 in this example):

int number = 2;
int i;

// Print the multiplication table for the number 2
for (i = 1; i <= 10; i++) {
  cout << number << " x " << i << " = " << number * i << "\n";
}
Try it Yourself »

For a tutorial about for loops in C++, visit our For Loops Chapter.


Arrays

Example

Create a program that calculates the average of different ages:

// An array storing different ages
int ages[8] = {20, 22, 18, 35, 48, 26, 87, 70};

float avg, sum = 0;
int i;

// Get the length of the array
int length = sizeof(ages) / sizeof(ages[0]);

// Loop through the elements of the array
for (int age : ages) {
  sum += age;
}

// Calculate the average by dividing the sum by the length
avg = sum / length;

// Print the average
cout << "The average age is: " << avg << "\n";
Try it Yourself »

Example

Create a program that finds the lowest age among different ages:

// An array storing different ages
int ages[8] = {20, 22, 18, 35, 48, 26, 87, 70};

int i;

// Get the length of the array
int length = sizeof(ages) / sizeof(ages[0]);

// Create a variable and assign the first array element of ages to it
int lowestAge = ages[0];

// Loop through the elements of the ages array to find the lowest age
for (int age : ages) {
  if (lowestAge > age) {
    lowestAge = age;
  }
}

// Print the lowest age
cout << "The lowest age is: " << lowestAge << "\n";
Try it Yourself »

For a tutorial about arrays in C++, visit our Arrays Chapter.


Structs

Example

Use a structure to store and output different information about Cars:

// Declare a structure named "car"
struct car {
  string brand;
  string model;
  int year;
};

int main() {
  // Create a car structure and store it in myCar1;
  car myCar1;
  myCar1.brand = "BMW";
  myCar1.model = "X5";
  myCar1.year = 1999;

  // Create another car structure and store it in myCar2;
  car myCar2;
  myCar2.brand = "Ford";
  myCar2.model = "Mustang";
  myCar2.year = 1969;
 
  // Print the structure members
  cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
  cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
 
  return 0;
}
Try it Yourself »

For a tutorial about structs in C++, visit our Structures Chapter.


Functions

Example

Create a program that converts a value from fahrenheit to celsius:

// Function to convert Fahrenheit to Celsius
float toCelsius(float fahrenheit) {
  return (5.0 / 9.0) * (fahrenheit - 32.0);
}

int main() {
  // Set a fahrenheit value
  float f_value = 98.8;

  // Call the function with the fahrenheit value
  float result = toCelsius(f_value);

  // Print the fahrenheit value
  cout << "Fahrenheit: " << f_value << "\n";

  // Print the result
  cout << "Convert Fahrenheit to Celsius: " << result << "\n";

  return 0;
}
Try it Yourself »

For a tutorial about functions in C++, visit our Functions Chapter.



×

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, cookie and privacy policy.

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