C++ stands out as a robust and advanced programming language, offering high-level capabilities. Initially designed to introduce object-orientation to the C language, C++ has become a cornerstone in the world of programming.
To truly grasp a programming language, active practice through writing programs is essential. Our collection of C++ programs covers a range of topics, including control statements, loops, classes & objects, functions, arrays, and more. Each program has been meticulously tested and is accompanied by its output.
Explore our comprehensive list of fundamental C++ programs below, designed to accelerate your learning process. Utilize the Online C++ Editor to run and modify programs for a hands-on understanding.
C++ Basic Examples
Hello World Program in C++: Kickstart your C++ journey with a classic “Hello World!” program. This simple yet foundational program is a standard introductory exercise across various programming languages.
1 2 3 4 5 6 7 8 | #include <iostream> int main() { std::cout << "Hello World!" << std::endl; return 0; } |
Output:
1 2 3 | Hello World! |
C++ program to print to console
The C++ standard library, specifically iostream
, offers three built-in methods for console output:
cout:
cout
is a versatile tool for displaying various messages or data on the console.
In contrast to the C language, there’s no need to specify the data type when using cout
.
1 2 3 4 5 6 7 8 9 10 | #include <iostream> using namespace std; int main() { cout << "Hello World"; return 0; } |
Output:
1 2 3 | Hello World! |
Utilize cout
to effortlessly print messages and data in your C++ programs. It simplifies the output process by eliminating the need for explicit data type declarations.
clog:
clog
is another output stream that can be used for logging information to the console.
It provides a buffered stream, making it suitable for handling log messages.
1 2 3 4 5 6 7 8 9 10 | #include <iostream> using namespace std; int main() { clog << "Logging information"; return 0; } |
Output:
1 2 3 | Logging information |
When you require a buffered stream for logging purposes, consider employing clog
to efficiently manage your log messages.
cerr:
cerr
is designed for error messages and behaves similarly to clog
with the added benefit of being unbuffered.
It is particularly useful for immediate and unaltered display of error information.
1 2 3 4 5 6 7 8 9 10 | #include <iostream> using namespace std; int main() { cerr << "Error: Something went wrong"; return 0; } |
Output:
1 2 3 | Error: Something went wrong |
………………..
C++ basic input output Integer
Unlike C language C++ does not require to specify the type of data for IO (Input/Output) operation. You can directly print any desirable data to the console using cout with the insertion operator (<<). Similarly, for taking input you can use cin with the extraction operator(>>).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <iostream> using namespace std; int main() { int number; cout << "Enter any number : "; cin >> number; cout << endl << "Your entered number : " << number; return 0; } |
Output:
1 2 3 4 | Enter any number : 100 Your entered number : 100 |
C++ basic input output string
In C++, capturing string input from users is efficiently achieved through the getline
method when utilizing the string data type. Alternatively, you can employ cin
for string input; however, it halts reading characters upon encountering a space.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> #include <string> using namespace std; int main() { string name; // Prompt the user to input their name cout << "Enter your name: "; // Utilize getline to capture the entire line, including spaces getline(cin, name); // Present a personalized greeting cout << endl << "Hello, " << name; return 0; } |
Output:
1 2 3 4 5 | Enter your name: Tommy Hello, Tommy |
C++ addition of two user given numbers
This example program illustrates how to perform the addition of two numbers provided by the user in C++.
In this program, we prompt the user to input two integer numbers. After receiving the inputs, the program calculates the sum and displays the result on the console.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; int main() { int num1, num2, sum; // Prompt the user to enter the 1st number cout << "Enter 1st number: "; cin >> num1; // Prompt the user to enter the 2nd number cout << endl << "Enter 2nd number: "; cin >> num2; // Calculate the sum sum = num1 + num2; // Display the result cout << endl << "Result = " << sum; return 0; } |
Output:
1 2 3 4 5 6 7 | Enter 1st number: 25 Enter 2nd number: 70 Result = 95 |
C++ swap two numbers using temporary variable
Swapping numbers involves exchanging values between variables. This program demonstrates how to swap two user-provided numbers using a temporary variable.
Logic:
- Assign the value of variable
a
to the variabletemp
, storing the original value ofa
. - Assign the value of
b
toa
. - Assign the value stored in
temp
(originala
) tob
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <iostream> using namespace std; int main() { int a, b, temp; // Prompt the user to enter number a cout << "Enter number a: "; cin >> a; // Prompt the user to enter number b cout << endl << "Enter number b: "; cin >> b; cout << endl << "Before swapping a = " << a << " b = " << b; // Swapping numbers temp = a; a = b; b = temp; cout << endl << "After swapping a = " << a << " b = " << b << endl; return 0; } |
Output:
1 2 3 4 5 6 7 8 | Enter number a: 15 Enter number b: 75 Before swapping a = 15 b = 75 After swapping a = 75 b = 15 |
C++ swap two numbers without temporary variable
Swapping numbers
Swapping numbers means exchanging the values between two or more variables. In this program we are going to swap two numbers without using any temporary variable.
Logic
- Store addition of variable a and b (a+b) to variable a.
- Now extract b from a and store it to b.
- Extract b from a and store it to a.
Now b is holding a’s original value and similarly a is holding b’s original value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include <iostream> using namespace std; int main() { int a, b; cout << "Enter number a : "; cin >> a; cout << endl << "Enter number b : "; cin >> b; cout << endl << "Before swapping a = " << a << " b = " << b; //Swapping number a = a + b; b = a - b; a = a - b; cout << endl << "After swapping a = " << a << " b = " << b << endl; return 0; } |
C++ program to calculate area of a circle
The area of a circle is the number of square units within the circle. To calculate the area of a circle the standard formula is: Area = Pi R Square
Area of circle = (A = πr²)
Logic
Here we have taken radius as input from the user, and to calculate the area of the circle we have to multiply the value of pi with the square of the radius.
Value of Pi = (3.14159)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <iostream> using namespace std; int main() { float radius, area; cout << "Enter radius of the circle : "; cin >> radius; area = 3.14 * (radius * radius); cout << endl << "Area of circle : " << area; return 0; } |
1 2 3 4 | Enter radius of the circle : 25.125 Area of circle : 1982.17 |
C++ program to calculate simple interest
Simple interest is a simple way to calculate the interest on a loan. Simple interest is determined by multiplying the principal by the daily interest rate multiplied by the number of days elapsed between payments. – Investopedia
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <iostream> using namespace std; int main() { float principal, rate, time, result; cout << "Enter principal : "; cin >> principal; cout << endl << "Enter rate : "; cin >> rate; cout << endl << "Enter time (year) : "; cin >> time; // Calculate simple interest result = (principal * rate * time) / 100; cout << endl << "Simple interest : " << result; return 0; } |
Output:
1 2 3 4 5 6 | Enter principal : 1000 Enter rate : 4 Enter time (year) : 2 Simple interest : 80 |
C++ program to calculate compound interest
Compound interest (or compounding interest) is the interest calculated on the principal, including all cumulative interest on deposits or loans in the previous period.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include <iostream> #include <math.h> using namespace std; int main() { float principal, rate, time, result; cout << "Enter principal : "; cin >> principal; cout << endl << "Enter rate : "; cin >> rate; cout << endl << "Enter time (year) : "; cin >> time; // Calculate compound interest result = principal * pow((1 + rate / 100), time); cout << endl << "Compound interest : " << result; return 0; } |
C++ program to find ASCII value of a character
ASCII (American Standard Code for Information Interchange) is the character encoding standard of electronic communication. ASCII codes represent text within computers, telecommunications equipment, and other devices. – Wikipedia
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> using namespace std; int main() { int a; char ch; cout << "Enter any character : "; cin >> ch; a = ch; cout << endl << "ASCII value of " << ch << " is " << a; return 0; } |
Output:
1 2 3 4 | Enter any character : a ASCII value of a is 97 |
C++ calculate year week and days from given total days
In this C++ program, we are going to see how we can calculate Year, Week and Days from given total days. We all know that 1 year = 365 (ignoring leap year) and 1 week = 7 days on this basis we can determine the year, week and days from given total no of days.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <iostream> using namespace std; int main() { int year, week, days, temp; cout << "Enter total number of days : "; cin >> days; year = days / 365; temp = days % 365; week = temp / 7; days = temp % 7; cout << endl << "Years : " << year; cout << endl << "Weeks : " << week; cout << endl << "Days : " << days; return 0; } |
C++ program to print size of different datatypes
This program shows how you can print the size of any data type available in C++ language. To find the size of any data type, C and C++ have one special operator sizeof. It simply calculates and returns the size of any given data type in bytes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <iostream> using namespace std; int main() { int year, week, days, temp; cout << "Enter total number of days : "; cin >> days; year = days / 365; temp = days % 365; week = temp / 7; days = temp % 7; cout << endl << "Years : " << year; cout << endl << "Weeks : " << week; cout << endl << "Days : " << days; return 0; } |
C++ If Else Examples
C++ check whether a character is alphabet or not
In this program, we are going to see whether a user given character is an alphabet or not. To determine the type of character, we have to check it’s ASCII value range.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; int main() { char ch; cout << "Enter any character: "; cin >> ch; if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { cout << endl << ch << " is ALPHABET."; } else { cout << endl<< ch << " is NOT ALPHABET."; } return 0; } |
C++ check whether a character is alphabet, digit or special character
This program is much similar to the previous one but here we are checking whether the given character is an alphabet, digit or a special character.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <iostream> using namespace std; int main() { char ch; cout << "Enter any character : "; cin >> ch; if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { cout << endl << ch << " is ALPHABET."; } else if(ch >= '0' && ch <= '9') { cout << endl << ch << " is DIGIT."; } else { cout << endl << ch << " is SPECIAL CHARACTER."; } return 0; } |
C++ find largest number among three number using if statement
In this program, we are going to see how to find the largest number among three numbers using if statement.
Logic
Here we have to compare each number with another two numbers, if it is greater than the both then simply print it.
Let’s say A = 11, B = 22 and C = 15
Then steps would be
- if A > B and A > C that means A is the largest number.
- if B > A and B > C that means B is the largest number.
- Similarly if C > A and C > B that means C is the largest number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #include <iostream> using namespace std; int main() { float num1, num2, num3; cout << "Enter 1st number : "; cin >> num1; cout << endl << "Enter 2nd number : "; cin >> num2; cout << endl<< "Enter 3rd number : "; cin >> num3; if(num1 >= num2 && num1 >= num3) { cout << endl << num1 << " is largest number"; } if(num2 >= num1 && num2 >= num3) { cout << endl << num2 << " is largest number"; } if(num3 >= num1 && num3 >= num2) { cout << endl << num3 << " is largest number"; } return 0; } |
C++ find largest number among three number using if else statement
This program is similar to the previous one, with a single modification, here we will use if else statement to find the largest number.
Logic
The logic to find the largest number among the three numbers, we have to compare each number with the other two numbers.
Let three variables be: A = 400, B = 200 and C = 300
- if A > B and A > C, then print A.
- else if B > A and B > C, then print B.
- else print C.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include <iostream> using namespace std; int main() { float num1, num2, num3; cout << "Enter 1st number : "; cin >> num1; cout << endl << "Enter 2nd number : "; cin >> num2; cout << endl << "Enter 3rd number : "; cin >> num3; if(num1 >= num2 && num1 >= num3) { cout << endl << num1 << " is largest number"; } else if(num2 >= num3) { cout << endl << num2 << " is largest number"; } else { cout << endl << num3 << " is largest number"; } return 0; } |
C++ find largest number among three number using nested if else statement
In this program, we are going to find the largest number among three numbers, similar to the previous one, but it is nested if-else version.
Logic
Let three variables be: A = 400, B = 200 and C = 300
The logic goes like this:
- if A >= B then check for if A >= C, then print A else print C.
- else part: if B >= C then print B else print C.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #include <iostream> using namespace std; int main() { float num1, num2, num3; cout << "Enter 1st number : "; cin >> num1; cout << endl << "Enter 2nd number : "; cin >> num2; cout << endl << "Enter 3rd number : "; cin >> num3; if(num1 >= num2) { if(num1 >= num3) { cout << endl << num1 << " is largest number"; } else { cout << endl << num3 << " is largest number"; } } else { if(num2 >= num3) { cout << endl << num2 << " is largest number"; } else { cout << endl << num3 << " is largest number"; } } return 0; } |
C++ program to check whether a year is leap year or not
Leap year
A leap year is a calendar year that includes an additional day to synchronize the calendar year with the astronomical or seasonal year. – Wikipedia
Logic
The Logic to check this is quite simple. We only need to check if the given year is multiple of 4 or 400, but it should not be multiple of 100.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include <iostream> using namespace std; int main() { int year; cout << "Enter a year : "; cin >> year; if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { cout << endl << year << " is a leap year."; } else { cout << endl << year << " is not a leap year."; } } else { cout << endl << year << " is a leap year."; } } else { cout << endl << year << " is not a leap year."; } return 0; } |
C++ program to check whether number is even or odd
Even number
Even numbers are numbers that have a difference of 2 unit or number. In other words, if the number is completely divisible by 2 then it is an even number.
Odd number
Opposite of even numbers, odd numbers are having a difference of 3 unit or number. In other words, if the number is not completely divisible by 2 then it is an odd number.
Logic
To find if a number is even or odd we only need to check if the given number is multiple of 2 or not, If it is multiple of 2 that means it is even number otherwise an odd number.
To check if it is multiple of 2 or not we use modulus operator.
If the expression number % 2 returns 0 that means the number is a multiple of 2. In other words, it is completely divisible by 2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> using namespace std; int main() { int number; cout << "Enter an integer : "; cin >> number; if (number % 2 == 0) { cout << endl << number << " is even number."; } else { cout << endl << number << " is odd number."; } return 0; } |
C++ check whether a number is negative, positive or zero
Positive number
All the numbers greater than 0, but not equal to 0 are positive numbers.
Negative number
Similarly all the number less than 0, but not equal to 0 are negative numbers.
Logic
If the number is greater than zero that means it is positive. If the number is less than zero that means it is negative. If the number is equal to zero that means it is absolute zero.
- if number > 0 then print Positive.
- if number < 0 then print Negative.
- if number == 0 then print Zero.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include <iostream> using namespace std; int main() { int number; cout << "Enter any number : "; cin >> number; if(number > 0) { cout << endl << "POSITIVE NUMBER" << endl; } if(number < 0) { cout << endl << "NEGATIVE NUMBER" << endl; } if(number == 0) { cout << endl << "NUMBER IS ZERO" << endl; } return 0; } |
C++ check whether a character is upper or lowercase alphabet
If the ASCII value of a character lies between 65 (A) to 90 (Z) then it is an uppercase character or if the character’s ASCII value lies between 97 (a) to 122 (z) then it is a lowercase character.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <iostream> using namespace std; int main() { char ch; cout << "Enter any character : "; cin >> ch; if(ch >= 'A' && ch <= 'Z') { cout << endl << ch << " is UPPERCASE alphabet."; } else if(ch >= 'a' && ch <= 'z') { cout << endl << ch << " is LOWERCASE alphabet."; } else { cout << endl << ch << " is not an alphabet."; } return 0; } |
C++ check whether a character is vowel or consonant
There are five vowel characters {a, e, i, o, u}. If the user given character input is one of them that means it is a vowel otherwise it is a consonant.
Logic
Here we have to manually check the given character with all the vowel characters, we cannot use ASCII value range to determine whether it is a vowel or a consonant. The given character can also be in the form of uppercase.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <iostream> using namespace std; int main() { char c; cout << "Enter a alphabet : "; cin >> c; // if given character is Lower case Vowel or Upper case Vowel // then print vowel otherwise consonant if ((c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') || (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')) { cout << endl << c << " is a vowel."; } else{ cout << endl << c << " is a consonant."; } return 0; } |
C++ print day name of week from number
In this program, we are going to print day name based on week no. Like – If the user enters 1 that means it is Monday.
Logic
After taking input (Week no) from the user, we have to compare that number with 1 to 7 or we can say comparing that number with a day of a week. So the logic goes like – if the number is equal to 1 then it is Monday, if the number is 2 then it is Tuesday etc… Like that we have to compare with each day of the week.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | #include <iostream> using namespace std; int main() { int weekday; cout << "Enter weekday day number (1-7) : "; cin >> weekday; if(weekday == 1) { cout << endl << "Monday"; } else if(weekday == 2) { cout << endl << "Tuesday"; } else if(weekday == 3) { cout << endl << "Wednesday"; } else if(weekday == 4) { cout << endl << "Thursday"; } else if(weekday == 5) { cout << endl << "Friday"; } else if(weekday == 6) { cout << endl << "Saturday"; } else if(weekday == 7) { cout << endl << "Sunday"; } else { cout << endl << "Please enter weekday number between 1-7."; } return 0; } |
C++ Loop Examples
C++ program to print all odd numbers from 1 to N
Odd number
Opposite of even numbers, odd numbers are having a difference of 3 unit or number. In other words, if the number is not completely divisible by 2 then it is an odd number.
Logic
The logic for printing odd numbers are pretty simple and straight forward, we only need to check if the number is not divisible by 2. If the number is not divisible by 2, then we have to print it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <iostream> using namespace std; int main() { int i, n; // Take input from user. cout << "Print all odd numbers till : "; cin >> n; cout << endl << "Odd numbers from 1 to " << n << " are : " << endl; for(i = 1; i <= n; i++) { // Check for odd or not. if((i % 2) != 0) { cout << i << " "; } } return 0; } |
C++ program to calculate sum of first N odd numbers
Odd number
The Opposite of even numbers. Odd numbers have a difference of 3 unit or number. In other words, if the number is not completely divisible by 2 then it is an odd number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <iostream> using namespace std; int main() { int i, n, sum = 0; // Take input from user. cout << "Print sum of odd numbers till : "; cin >> n; for(i = 1; i <= n; i++) { // Check for odd or not. if((i % 2) != 0) { sum += i; } } cout << endl << "Sum of odd numbers from 1 to " << n << " is : " << sum; return 0; } |
C++ program to print all even numbers from 1 to N
Even number
Even number are numbers that have a difference of 2 unit or number. In other words, if the number is completely divisible by 2 then it is an even number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <iostream> using namespace std; int main() { int i, n; // Take input from user. cout << "Print all even numbers till : "; cin >> n; cout << endl << "Even numbers from 1 to " << n << " are : " << endl; for(i = 1; i <= n; i++) { // Check for even or not. if((i % 2) == 0) { cout << i << " "; } } return 0; } |
C++ program to calculate sum of first N even numbers
Even number
Even numbers are numbers that have a difference of 2 unit or number. In other words, if the number is completely divisible by 2 then it is an even number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <iostream> using namespace std; int main() { int i, n, sum = 0; // Take input from user. cout << "Print sum of even numbers till : "; cin >> n; for(i = 1; i <= n; i++) { // Check for even or not. if((i % 2) == 0) { sum += i; } } cout << endl << "Sum of even numbers from 1 to " << n << " is : " << sum; return 0; } |
C++ program to print first N natural numbers using for loop
Natural number
Natural numbers are numbers that are common and clearly in nature. As such, it is a whole, nonnegative number.
Logic
To print the first N natural number we only have to run one single loop from 1 to N.
After taking input (num) from user start one loop from 1 to num, and then inside the loop simply print the current variable “i”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <iostream> using namespace std; int main() { int i, num; // Take number from user cout << "Enter any number : "; cin >> num; cout << endl << "Natural numbers from 1 to " << num << endl; for(i = 1; i <= num; i++) { cout << i << " "; } return 0; } |
C++ program to calculate sum of first N natural numbers
Natural number
Natural numbers are numbers that are common and clear in nature. As such, it is a whole, non-negative number.
Logic
To print the sum of first N natural numbers, we need to run one loop from 1 to N, and each time inside the loop we have to add / sum value of “i” (current number) into one temporary variable.
Once the loop is over, outside of the loop we have to print a temporary variable containing the sum of natural numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> using namespace std; int main() { int i, num, sum = 0; // Take number from user cout << "Enter any number : "; cin >> num; for(i = 1; i <= num; i++) { sum += i; } cout << endl << "Sum of first " << num << " natural numbers : " << sum; return 0; } |
C++ program to print all prime numbers between 1 to N
Prime number
A prime number is an integer greater than 1 whose only factors are 1 and itself. A factor is an integer that can be divided evenly into another number.
Logic
To print all the prime numbers up to N, we start one loop from 2 to N and then inside the loop we check current number or “num” is prime or not. To check if it is prime or not we again need one nested loop. It is not an efficient way to check prime number but it is simpler to understand the basic of looping in C++.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include <iostream> using namespace std; int main() { int num, i, upto; // Take input from user cout << "Find prime numbers upto : "; cin >> upto; cout << endl << "All prime numbers upto " << upto << " are : " << endl; for(num = 2; num <= upto; num++) { for(i = 2; i <= (num / 2); i++) { if(num % i == 0) { i = num; break; } } // If the number is prime then print it. if(i != num) { cout << num << " "; } } return 0; } |
C++ program to find sum of prime numbers between 1 to N
Prime number
A prime number is an integer greater than 1 whose only factors are 1 and itself. A factor is an integer that can be divided evenly into another number.
Logic
To print the sum of all prime numbers up to N we have to iterate through each number up to the given number and check if the number is a prime or not if it is a prime number then simply sum it or add it in one temporary variable.
Once the outer loop is completed we have to print that temporary variable containing the sum of primes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include <iostream> using namespace std; int main() { int num, i, upto, sum = 0; // Take input from user cout << "Find sum of prime numbers upto : "; cin >> upto; for(num = 2; num <= upto; num++) { for(i = 2; i <= (num / 2); i++) { if(num % i == 0) { i = num; break; } } // If the number is prime then add it. if(i != num) { sum += num; } } cout << endl << "Sum of all prime numbers upto " << upto << " : " << sum; return 0; } |
C++ program to find all factors of a number
Factor
A factor is an integer that can be divided evenly into another number or in other words factors of a number are numbers that multiply to form a product.
Logic
To print all the factors of a particular number we have to iterate through all the smaller numbers up to the given number. If the user given number is completely divisible by any number then it is a factor of that number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; int main() { int i, num; // Take input from user cout << "Enter any number : "; cin >> num; cout << endl << "All factors of " << num << " are : " << endl; for(i = 1; i <= num; i++) { if(num % i == 0) { cout << i << " "; } } return 0; } |
C++ program to print alphabets from a to z
In this program, we are going to see how we can print alphabets in C++. The program is pretty simple and straight forward. Here ASCII value of the characters comes into the picture, we use the ASCII value of starting and end character to run the loop.
Logic
ASCII value of small letter “a” is 97 and for “z” it is 122, so we run the loop from 97 to 122 and then inside the loop we have to print the current character.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> using namespace std; int main() { char c; cout << "Alphabets from a - z are : " << endl; // Start from ASCII value of small letter a. for(c = 'a'; c <= 'z'; c++) { cout << c << " "; } return 0; } |
C++ program to check whether a given number is perfect number or not
Perfect number
A perfect number is a positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3.
Logic
To check if the number is perfect or not we have to run one loop from 1 to N and sum all the numbers between 1 to N, if the sum is equal to N then it is a perfect number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <iostream> using namespace std; int main() { int i, num, sum = 0; // Take input from user cout << "Enter any number : "; cin >> num; // Calculate sum of all proper divisors for(i = 1; i < num; i++) { if(num % i == 0) { sum += i; } } // Check whether the sum of divisors is equal to num if(sum == num) { cout << endl << num << " is PERFECT NUMBER"; } else { cout << endl << num << " is NOT PERFECT NUMBER"; } return 0; } |
C++ program to check whether a given number is Armstrong number or not
Armstrong number
An Armstrong number is a number that is equal to the sum of the digits that rise to the total number of digits of the power. Some Armstrong numbers are: 0, 1, 2, 3, 153, 370, 407, 1634, 8208, etc.
Know more about Armstrong number – Wikipedia
Logic
After taking input from the user, we have to calculate the total number of digits in the given number. Here we are using log10 method of math library to achieve this. After doing that we have to run one loop until the value of user given number “num” does not reach 0 or becomes less than zero.
Now inside the loop each time we have to find the last digit of user given number and then calculate the power of that number with total no of digits in the “num”, round off the result and store it in one temporary variable “sum” once the loop is finished we have to check if the value of variable sum is equivalent to user given number, if yes, then it is an Armstrong number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #include <iostream> #include <math.h> using namespace std; int main() { int originalNum, num, lastDigit, digits, sum; // Take number from user cout << "Enter number to check : "; cin >> num; sum = 0; originalNum = num; // Find total digits in given number digits = (int) log10(num) + 1; while(num > 0) { lastDigit = num % 10; sum = sum + round(pow(lastDigit, digits)); // Remove the last digit num = num / 10; } // Check for armstrong or not if(originalNum == sum) { cout << endl << originalNum << " is ARMSTRONG NUMBER"; } else { cout << endl << originalNum << " is NOT ARMSTRONG NUMBER"; } return 0; } |
C++ program to check whether a number is palindrome or not
Palindrome
A palindrome is anything that reads the same backward and forward. In other words after reversing any number, word or phrase if it remains the same as original then it is a palindrome.
Logic
To check whether a number is a palindrome number or not we have to reverse it first. After reversing it we compare the reversed number with the original number. If both the numbers are similar then it means the number we have is a palindrome number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <iostream> using namespace std; int main() { int num, temp, reverse = 0; // Take input from user cout << "Enter any number : "; cin >> num; temp = num; while(temp != 0) { reverse = (reverse * 10) + (temp % 10); temp /= 10; } // Check for palindrome if(reverse == num) { cout << endl << num << " is a palindrome."; } else { cout << endl << num << " is not a palindrome."; } return 0; } |
C++ program to check whether a number is prime number or not
Prime number
A prime number is an integer which is greater than 1 whose only factors are 1 and itself. A factor is an integer that can be divided evenly into another number.
Logic
The logic to check a number is prime or not is really simple. We only need to check if the given number is completely divisible by any other smaller number or not, but not by 1 and itself.
After taking input from the user, we have to run one loop up to half of the given number. Now the reason for running one loop up to half of the given number is because we know, a number can only be divisible by a number which is lesser than its half.
Inside the loop we have to check if the given number “num” is completely divisible by current number “i” or not, If yes then set the value of the variable i to num and terminate the loop here, if no then continue the loop.
Once the loop is completed or terminated control comes out of the loop, here we have to check if the value of the variable i is equivalent to the given number or not. If yes then it is not a Prime number otherwise it is a prime number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <iostream> using namespace std; int main() { int i, num; // Take input from user cout << "Enter any number : "; cin >> num; for(i = 2; i <= (num / 2); i++) { if((num % i) == 0) { i = num; break; } } if(i == num) { cout << endl << num << " is not a prime number."; } else { cout << endl << num << " is a prime number."; } return 0; } |
C++ program to count number of digits in a given integer
Count number of digits in a given integer
To count the number of digits in a number we have to divide that number by 10 until it becomes 0 or less than 0. If you divide any number by 10 and store the result in an integer then it strips the last digit. So we have to apply the same logic here also.
Logic
After taking the input from the user, run one while loop that runs until the user given number becomes 0. Inside the loop for each iteration increase the counter variable by one and divide the user given number by 10 and store it in the same variable again.
Notice here we are using /= operator that performs division and stores the result in the same variable again.
Once the loop is over we have to print counter variable “count” containing the total number of digits.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <iostream> using namespace std; int main() { int num, temp; int count = 0; // Take input from user cout << "Enter any number : "; cin >> num; // Store to temporary variable. temp = num; while(temp != 0) { // Increment counter count++; // Remove last digit of 'temp' temp /= 10; } cout << endl << "Total digits in " << num << " : " << count; return 0; } |
C++ program to find product of digits in a number
Product of digits in a number
This program is closely similar to this one: Count number of digits in a given integer. The only difference here is instead of counting the total number of digits we are multiplying each digit by another one until the user given number becomes 0 or less than 0.
Logic
First of all, we are declaring one variable product with value 1, we are going to use this variable to store the product of all digits, now after taking input from the user, inside the while loop, we have to extract each digit by performing modulo operation.
The modulo operation returns the remainder after dividing a number by another number. If we perform modulo operation with 10 on any number it will return the last most digit, we have to multiply and store the result into the variable product.
After that remove the last most digit from the number and perform the same again until the number becomes 0 or less than 0. Once the loop is completed simple print the variable product containing the product of all digit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <iostream> using namespace std; int main() { int num, temp; int product = 1; // Take input from user cout << "Enter any number : "; cin >> num; temp = num; while(temp != 0) { product = product * (temp % 10); // Remove last digit from temp. temp = temp / 10; } cout << endl << "Product of all digits in " << num << " : " << product; return 0; } |
C++ program to find sum of all digits in a number
Sum of digits in a number
This program is much similar to this one: Find product of digits in a number. The only difference is instead of multiply we have to perform addition here.
Logic
First of all, we are declaring one variable sum with value 0, we are going to use this variable to store the sum of all digits, now after taking input from the user, inside the while loop, we have to extract each digit by performing modulo operation.
The modulo operation returns the remainder after dividing a number by another number. If we perform modulo operation with 10 on any number it will return the last most digit, we have to add it into variable sum and store the result again in variable sum.
After that remove the last most digit from the number and perform the same again until the number becomes 0 or less than 0. Once the loop is completed simply print the variable sum containing the sum of all digit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <iostream> using namespace std; int main() { int num, temp, sum = 0; // Take numbers from user cout << "Enter any number : "; cin >> num; // Store to temporary variable. temp = num; while(temp != 0) { sum += temp % 10; // Remove last digit of 'temp' temp /= 10; } cout << endl << "Sum of all digits in " << num << " : " << sum; return 0; } |
C++ program to calculate factorial of a number
Factorial
A factorial is a product of an integer and all the integers below it. In other words, factorial (!) Is the product of all integers from 1 to n.
For example:
If N = 5, then 5! is 5 x 4 x 3 x 2 x 1 = 120
Logic
First of all, we declare one temporary variable fact with value 1, now we are going to use this variable to store factorial.
After taking input from the user, we need to start one loop from 1 to N, and inside the loop we multiply current number “i” with variable fact and then store the result again in fact variable until the loop terminates. Once the loop is over we have to print the fact variable containing factorial of a given number (N).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> using namespace std; int main() { int i, num; int fact = 1; // Take numbers from user cout << "Enter any number : "; cin >> num; for(i = 1; i <= num; i++) { fact = fact * i; } cout << endl << "Factorial of " << num << " : " << fact; return 0; } |
C++ program to find HCF of two user given numbers
HCF
The greatest common divisor of two or more numerical values is called the highest common factor (HCF). In other words, the largest number that can completely divide two or more numbers is the highest common factor.
Logic
Let declare one temporary variable hcf by 1, we are going to use this variable to store HCF.
Here we are calculating HCF of two user given numbers, after taking both the numbers (num1, num2) from the user, we have to find out which number is smaller, we store the minimum one in the variable min.
Now we start one loop from 1 to min (Minimum between both numbers), and inside the loop, we have to check if both the numbers are completely divisible by current number “i” or not. If yes then we update temporary variable hcf by current number “i”, otherwise continue with the loop.
Once the loop is over simply print the variable hcf containing the highest common factor of num1 and num2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <iostream> using namespace std; int main() { int i, num1, num2, min, hcf=1; // Take two numbers from user cout << "Enter two numbers : "; cin >> num1 >> num2; // Find minimum between two numbers min = num1; if(num2 < num1) { min = num2; } for(i = 1; i <= min; i++) { if((num1 % i) == 0 && (num2 % i) == 0) { hcf = i; } } cout << endl << "HCF of " << num1 << " and " << num2 << " : " << hcf; return 0; } |
C++ program to find LCM of two user given numbers
LCM
The least / lowest common multiple (LCM) of two or more than two numbers is the smallest number (not zero) which is a multiple of all of the numbers.
Logic
Let declare one temporary variable lcm by 1, we are going to use this variable to store LCM.
Here we are calculating LCM of two user given numbers, after taking both the numbers (num1, num2) from the user, we have to find out the maximum number, we store the maximum one in variable max and also assign the value of max to the variable i.
Now we start one infinite loop while(1), inside the loop we have to check if both the numbers can completely divide max value. If yes then we terminate the loop with break statement and assign current value of “i” to lcm, otherwise, continue the loop.
Once the loop is over, simply print the variable lcm containing the lowest common multiple of num1 and num2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include <iostream> using namespace std; int main() { int i, num1, num2, max, lcm=1; // Take two numbers from user cout << "Enter any two number : "; cin >> num1 >> num2; // Find the max number max = (num1 > num2) ? num1 : num2; i = max; while(1) { if((i % num1) == 0 && (i % num2) == 0) { lcm = i; break; } i += max; } cout << endl << "LCM of " << num1 << " and " << num2 << " : " << lcm; return 0; } |
C++ program to calculate power of a number using for loop
Power of a number
The power of a number represents the number of times to use that number in a multiplication. Usually, power is represented with a base number and an exponent.
Logic
Let’s declare one temporary variable power with value 1, we have used the data-type long long so that it can hold a big long value.
To calculate the power of a number we need a base and an exponent value, we are taking these two values from the user, after taking input (base, exponent) from the user we start one loop from 1 to exponent.
Inside the loop, for every iteration, we multiply the base by power (base * power) and store the result again in variable power until the loop is completed.
Once the loop is over, simply print the variable power containing the resultant power value of a given number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; int main() { int base, exponent; long long power = 1; int i; // Take input from user cout << "Enter base and exponent : "; cin >> base >> exponent; // Multiply base, exponent times for(i = 1; i <= exponent; i++) { power = power * base; } cout << endl << "Result " << base << " ^ " << exponent << " : " << power; return 0; } |
C++ program to find reverse of any number
n this program, we are going to see how we can reverse any user given number. Reversing any word, phrase or number is pretty simple if we treat it as a string data. We can simply iterate through each character in reverse order and then append it to one temporary variable. But here we are only dealing with numbers and for numbers, there is a better approach.
Logic
First of all, we have to declare one temporary variable reverse with value 0, we will use this variable to store the reverse of the number.
After taking input from the user, we have to assign the input to one temporary variable temp, Now to reverse a number we have to extract each digit of that number one by one. To extract digits we can use % (modulo) operator. If we perform modulo operation with 10 on any number it will return the last most digit.
Now after extracting the digit, we have to append it to our temporary variable reverse, but we cannot directly append the digit on it. To append the digit, first, we need to multiply 10 on existing reversed value and then perform addition with the extracted digit.
At the end remove the last most digit and repeat the same again until the value of temp becomes 0 or less than 0.
Once the loop is finished simply print the variable reverse.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include <iostream> using namespace std; int main() { int num, temp, reverse = 0; // Take numbers from user cout << "Enter any number : "; cin >> num; temp = num; while(temp != 0) { reverse = (reverse * 10) + (temp % 10); temp /= 10; } cout << endl << "Reverse of " << num << " : " << reverse; return 0; } |
C++ program to print multiplication table of a any given number
In this program, we are going to see how we can print the multiplication table of any user given input number.
Logic
Printing multiplication table of any number is quite simple and an easy task. After taking input (num) from the user we have to start one loop from 1 to 10, and then inside the loop simply multiply num by current number “i” and print it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> using namespace std; int main() { int i, num; // Take input from user cout << "Enter number to print table : "; cin >> num; cout << endl; for(i = 1; i <= 10; i++) { cout << num << " * " << i << " = " << (num * i) << endl; } return 0; } |
Area of Triangle with Base & Heigth
This program finds area of a triangle based on its base and height value. The question is, write a program in C++ to find area of a triangle with base and height entered by user at run-time. Here is its answer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include<iostream> using namespace std; int main() { float b, h, area; cout<<"Enter Base length of Triangle: "; cin>>b; cout<<"Enter Height length of Triangle: "; cin>>h; area = 0.5*b*h; cout<<"\nArea = "<<area; cout<<endl; return 0; } |
Perimeter of Triangle with 3 Sides
Now let’s create a program to find the perimeter of a triangle using values of its three sides given by user at run-time:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include<iostream> using namespace std; int main() { float a, b, c, per; cout<<"Enter Length of First Side: "; cin>>a; cout<<"Enter Length of Second Side: "; cin>>b; cout<<"Enter Length of Third Side: "; cin>>c; per = a+b+c; cout<<"\nPerimeter = "<<per; cout<<endl; return 0; } |
Find Area of Circle
To calculate area of any circle in C++ programming, you have to ask from user to enter the radius of circle, place the radius in a variable say rad and then initialize 3.14*rad*rad in a variable that holds the value of area of circle, as shown here in the following program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include<iostream> using namespace std; int main() { float rad, area; cout<<"Enter the Radius of Circle: "; cin>>rad; area = 3.14*rad*rad; cout<<"\nArea of Circle = "<<area; cout<<endl; return 0; } |
Find Circumference of Circle
The question is, write a program in C++ to find circumference of a circle. The answer to this question is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include<iostream> using namespace std; int main() { float rad, circum; cout<<"Enter the Radius of Circle: "; cin>>rad; circum = 2*3.14*rad; cout<<"\nCircumference of Circle = "<<circum; cout<<endl; return 0; } |
Program to find area of a trapezoid in C++
we will learn how to calculate or find the area of a trapezoid in C++.
A trapezoid is a quadrilateral with two parallel sides and the other two sides which are not parallel. The parallel sides are called bases and the other two sides are called legs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include<iostream> using namespace std; int main() { float b1=12; float b2=13.5; float h=6.8; float A; /* A=1/2*(b1+b2)*h; */ A=(b1+b2)*h/2; cout<<"Area of trapezoid is "<<A<<"\n"; return 0; } |