C++ is one of the most powerful and high-level programming language. The main purpose of C ++ programming was to add object-orientation to the C language.
To understand a programming language you must practice the programs, this way you can learn the language faster. This page includes c++ programs on various c++ topics such as control statements, loops, classes & objects, functions, arrays etc. All the programs are tested and provided with the output.
Here is the list of all C++ basic program we have created for you that might help you to learn the language quickly. Try running and modifying the program inĀ Online C++ EditorĀ to better understand.
C++ Basic Examples
C++ program to print hello world
A āHello world!ā program is usually a computer program that displays the message āHello world!ā. It is very simple in most of the programming languages.
Let see how to write hello world program in c++.
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> using namespace std; int main() { cout << "Hello World"; return 0; } |
Output:
1 2 3 |
Hello World |
C++ program to print to console
The standard C++ library iostreamĀ provides three built-in ways to print into the console.
- cout
- clog
- cerr
Cout
It is used to print any kind of message or data on the console. Unlike C language here we donāt need to provide the type of data we want to print.
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> using namespace std; int main() { cout << "Hello World"; return 0; } |
Output:
1 2 3 |
Hello World |
Clog
Clog is much similar to cout but it is mainly used for logging.
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> using namespace std; int main() { clog << "I, am an error!"; return 0; } |
Output:
1 2 3 |
I, am an error! |
Cerr
Cerr also produces output like cout, but the main purpose of cerr is to print errors on the console.
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> using namespace std; int main() { cerr << "I, am an error!"; return 0; } |
Output:
1 2 3 |
I, am an error! |
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
To read string input from the userĀ getlineĀ method can be used with the string datatype. You can also useĀ cinĀ for reading string input, butĀ cinĀ will only read string without space, once it encounters space it stops reading further characters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <string> using namespace std; int main() { string name; cout << "Enter your name : "; getline(cin, name); cout << endl << "Hello " << name; return 0; } |
Output:
1 2 3 4 |
Enter your name : Karan Hello Karan |
C++ addition of two user given numbers
This is an example program that demonstrates how you can perform the addition of two user given numbers in C++.
In this program first we are taking two integer numbers from the user, and then displaying the result of addition into the console.
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 num1, num2, sum; cout << "Enter 1st number : "; cin >> num1; cout << endl << "Enter 2nd number : "; cin >> num2; sum = num1 + num2; cout << endl << "Result = " << sum; return 0; } |
Output:
1 2 3 4 5 |
Enter 1st number : 10 Enter 2nd number : 40 Result = 50 |
C++ swap two numbers using temporary variable
Swapping numbers
Swapping numbers means exchanging the values between two or more variables. In this program, we are going to see how we can swap two user-given number with the help of one temporary variable.
Logic
- Assign variableĀ aāsĀ value to variableĀ temp, so now the temp is holdingĀ aāsĀ original value.
- AssignĀ bāsĀ value to a.
- Assign tempās (holding a) value to b.
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, temp; cout << "Enter number a : "; cin >> a; cout << endl << "Enter number b : "; cin >> b; cout << endl << "Before swapping a = " << a << " b = " << b; //Swapping number temp = a; a = b; b = temp; cout << endl << "After swapping a = " << a << " b = " << b << endl; return 0; } |
Output:
1 2 3 4 5 6 |
Enter number a : 10 Enter number b : 200 Before swapping a = 10 b = 200 After swapping a = 200 b = 10 |
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; } |
Output:
1 2 3 4 5 6 |
Enter number a : 10 Enter number b : 200 Before swapping a = 10 b = 200 After swapping a = 200 b = 10 |
C++ program to calculate area of a circle
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; } |
Output:
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
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; } |
Output:
1 2 3 4 5 6 |
Enter principal : 100 Enter rate : 25 Enter time (year) : 6 Compound interest : 381.47 |
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; } |
Output:
1 2 3 4 5 6 |
Enter total number of days : 1212 Years : 3 Weeks : 16 Days : 5 |
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 |
#include <iostream> using namespace std; int main() { cout << "Type Size (bytes)" << endl; cout << "Characte " << sizeof(char) << endl; cout << "Integer " << sizeof(int) << endl; cout << "Long int " << sizeof(long int) << endl; cout << "Float " << sizeof(float) << endl; cout << "Double " << sizeof(double) << endl; cout << "Long double " << sizeof(long double) << endl; return 0; } |
Output:
1 2 3 4 5 6 7 8 9 |
Type Size (bytes) Characte 1 Integer 4 Long int 8 Float 4 Double 8 Long double 16 |
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; } |
Output:
1 2 3 4 |
Enter any character : x x is ALPHABET. |
C++ check whether a character is alphabet, digit or 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; } |
Output:
1 2 3 4 |
Enter any character : # # is SPECIAL CHARACTER. |
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; } |
Output:
1 2 3 4 5 6 |
Enter 1st number : 10 Enter 2nd number : 5 Enter 3rd number : 11 11 is largest number |
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; } |
Output:
1 2 3 4 5 6 |
Enter 1st number : 10 Enter 2nd number : 200 Enter 3rd number : 11 200 is largest number |
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; } |
Output
1 2 3 4 5 6 |
Enter 1st number : 100 Enter 2nd number : 10 Enter 3rd number : 99 100 is largest number |
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; } |
Output
1 2 3 4 |
Enter a year : 2012 2012 is a leap year. |
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; } |
Output
1 2 3 4 |
Enter an integer : 886 886 is even number. |
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; } |
Output
1 2 3 4 |
Enter any number : 101 POSITIVE NUMBER. |
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; } |
Output
1 2 3 4 |
Enter any character : S S is UPPERCASE alphabet. |
C++ check whether a character is vowel or 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; } |
Output
1 2 3 4 |
Enter a alphabet : A A is a vowel. |
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; } |
Output
1 2 3 4 |
Enter weekday day number (1-7) : 4 Thursday |
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; } |
Output
1 2 3 4 5 |
Print all odd numbers till : 50 Odd numbers from 1 to 50 are : 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 |
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; } |
Output
1 2 3 4 |
Print sum of odd numbers till : 50 Sum of odd numbers from 1 to 50 is : 625 |
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; } |
Output
1 2 3 4 5 |
Print all even numbers till : 50 Even numbers from 1 to 50 are : 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 |
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; } |
Output
1 2 3 4 |
Print sum of even numbers till : 100 Sum of even numbers from 1 to 100 is : 2550 |
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; } |
Output
1 2 3 4 |
Enter any number : 10 Natural numbers from 1 to 10 1 2 3 4 5 6 7 8 9 10 |
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; } |
Output
1 2 3 4 |
Enter any number : 50 Sum of first 50 natural numbers = 1275 |
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; } |
Output
1 2 3 4 5 |
Find prime numbers upto : 100 All prime numbers upto 100 are : 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 |
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; } |
1 2 3 4 |
Find sum of prime numbers upto : 50 Sum of all prime numbers upto 50 : 326 |
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; } |
Output
1 2 3 4 5 |
Enter any number : 50 All factors of 50 are : 1 2 5 10 25 50 |
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; } |
Output
1 2 3 4 |
Alphabets from a - z are: a b c d e f g h i j k l m n o p q r s t u v w x y z |
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; } |
Output
1 2 3 4 |
Enter any number : 5 5 is NOT PERFECT NUMBER |
C++ program to check whether a given number is Armstrong number or not
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; } |
Output
1 2 3 4 |
Enter number to check : 1634 1634 is ARMSTRONG NUMBER |
C++ program to check whether a number is palindrome or not
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; } |
Output
1 2 3 4 |
Enter any number : 121 121 is a palindrome. |
C++ program to check whether a number is prime number or not
C++ program to count number of digits in a given integer
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; } |
Output
1 2 3 4 |
Enter any number : 123456 Total digits in 123456 : 6 |
C++ program to find product of digits in a number
C++ program to find sum of all digits in a 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 |
#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; } |
Output
1 2 3 4 |
Enter any number : 123456 Sum of all digits in 123456 : 21 |
C++ program to calculate factorial of a number
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; } |
Output
1 2 3 4 |
Enter any number : 5 Factorial of 5 : 120 |
C++ program to find HCF of two user given numbers
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; } |
Output
1 2 3 4 |
Enter two numbers : 12 30 HCF of 12 and 30 : 6 |
C++ program to find LCM of two user given numbers
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; } |
Output
1 2 3 4 |
Enter any two number : 6 24 LCM of 6 and 24 : 24 |
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.
Output
1 2 3 4 |
Enter base and exponent : 2 5 Result : 2 ^ 5 = 32 |
C++ program to find reverse of any 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 |
#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; } |
Output
1 2 3 4 |
Enter any number : 123456 Reverse of 123456 : 654321 |
C++ program to print multiplication table of a any given number