C++ File
C++ File
In this example, we will learn to create a simple program named "Hello World" in C+
+ programming.
A "Hello, World!" is a simple program that outputs Hello, World! on the screen.
Since it's a very simple program, it's often used to introduce a new programming
language to a newbie.
Let's see how C++ "Hello, World!" program works.
#include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
}
Run Code
Output
Hello World!
In C++, any line starting with // is a comment. Comments are intended for the
person reading the code to better understand the functionality of the program. It is
completely ignored by the C++ compiler.
2. #include <iostream>
The #include is a preprocessor directive used to include files in our program. The
above code is including the contents of the iostream file.
This allows us to use cout in our program to print output on the screen.
A valid C++ program must have the main() function. The curly braces indicate the
start and the end of the function.
std::cout prints the content inside the quotation marks. It must be followed
by << followed by the format string. In our example, "Hello World!" is the format
string.
The return 0; statement is the "Exit status" of the program. In simple terms, the
program ends with this statement.
2. C++ Program to Print Number Entered by User
In this example, you'll learn to print the number entered by a user using
C++ cout statement.
#include <iostream>
using namespace std;
int main() {
int number;
Output
Enter an integer: 23
You entered 23
When the user enters an integer, it is stored in variable number using cin.
Then it is displayed on the screen using cout.
3. C++ Program to Add Two Numbers
In this program, user is asked to enter two integers. Then, the sum of those two
integers is stored in a variable and displayed on the screen. Primary tabs
int main() {
// prints sum
cout << first_number << " + " << second_number << " = " << sum;
return 0;
}
Run Code
Output
In this program, the user is asked to enter two integers. These two integers are
stored in variables first_number and second_number respectively.
Then, the variables are added using the + operator and stored in the sum variable.
Finally, sum is displayed on the screen.
4. C++ Program to Find Quotient and Remainder
In this example, you will learn to find the quotient and remainder of a given dividend
and divisor.
In this program, the user is asked to enter two integers (divisor and dividend) and the
quotient and the remainder of their division is computed.
To compute quotient and remainder, both divisor and dividend should be integers.
int main()
{
int divisor, dividend, quotient, remainder;
return 0;
}
Run Code
Output
Enter dividend: 13
Enter divisor: 4
Quotient = 3
Remainder = 1
The division operator / computes the quotient (either between float or integer
variables).
The modulus operator % computes the remainder when one integer is divided by
another (modulus operator cannot be used for floating-type variables).
5. C++ Program to Find Size of int, float, double and char in Your
System.
This program declares 4 variables of type int, float, double and char. Then, the size
of each variable is evaluated using sizeof operator.
sizeof(dataType);
#include <iostream>
using namespace std;
int main()
{
cout << "Size of char: " << sizeof(char) << " byte" << endl;
cout << "Size of int: " << sizeof(int) << " bytes" << endl;
cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes" << endl;
return 0;
}
Output
This example contains two different techniques to swap numbers in C programming. The first
program uses temporary variable to swap numbers, whereas the second program doesn't use
temporary variables.
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
return 0;
}
Output
Before swapping.
a = 5, b = 10
After swapping.
a = 10, b = 5
The contents of the first variable is copied into the temp variable. Then,
the contents of second variable is copied to the first variable.
Finally, the contents of the temp variable is copied back to the second
variable which completes the swapping process.
You can also perform swapping using only two variables as below.
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10;
a = a + b;
b = a - b;
a = a - b;
return 0;
}
The output of this program is the same as the first program above.
Odd
And those integers that are not perfectly divisible by 2 are not known as
odd numbers.
int main() {
int n;
if ( n % 2 == 0)
cout << n << " is even.";
else
cout << n << " is odd.";
return 0;
}
Run Code
Output
Enter an integer: 23
23 is odd.
Vowel or Consonant.
In this example, if...else statement is used to check whether an alphabet entered by the user is
a vowel or a constant.
To understand this example, you should have the knowledge of the following C++
programming topics:
C++ if, if...else and Nested if...else
Five alphabets a, e, i, o and u are known as vowels. All other alphabets except these 5
alphabets are known as consonants.
This program assumes that the user will always enter an alphabet.
#include <iostream>
using namespace std;
int main() {
char c;
bool isLowercaseVowel, isUppercaseVowel;
return 0;
}
Output
Enter an alphabet: u
u is a vowel.
Numbers
In this example, you'll learn to find the largest number among three
numbers using if, if else and nested if else statements.
int main() {
return 0;
}
Run Code
Output
int main() {
return 0;
}
Run Code
Output
Equation
This program accepts coefficients of a quadratic equation from the user and displays the roots
(both real and complex roots depending upon the discriminant).
To understand this example, you should have the knowledge of the following C++
programming topics:
C++ if, if...else and Nested if...else
For a quadratic equation ax2+bx+c = 0 (where a, b and c are coefficients), it's roots
is given by following the formula.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float a, b, c, x1, x2, discriminant, realPart, imaginaryPart;
cout << "Enter coefficients a, b and c: ";
cin >> a >> b >> c;
discriminant = b*b - 4*a*c;
if (discriminant > 0) {
x1 = (-b + sqrt(discriminant)) / (2*a);
x2 = (-b - sqrt(discriminant)) / (2*a);
cout << "Roots are real and different." << endl;
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
}
else if (discriminant == 0) {
cout << "Roots are real and same." << endl;
x1 = -b/(2*a);
cout << "x1 = x2 =" << x1 << endl;
}
else {
realPart = -b/(2*a);
imaginaryPart =sqrt(-discriminant)/(2*a);
cout << "Roots are complex and different." << endl;
cout << "x1 = " << realPart << "+" << imaginaryPart << "i" <<
endl;
cout << "x2 = " << realPart << "-" << imaginaryPart << "i" <<
endl;
}
return 0;
}
Output
In this program, sqrt() library function is used to find the square root of a number.
11. C++ Program to Calculate Sum of Natural
Numbers
This program takes a positive integer from user( suppose user entered n )
then, this program displays the value of 1+2+3+....+n.
#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
Output
This program checks whether an year (integer) entered by the user is a leap year or not.
To understand this example, you should have the knowledge of the following C++
programming topics:
C++ if, if...else and Nested if...else
C++ Operators
All years which are perfectly divisible by 4 are leap years except for century years (years
ending with 00), which are leap years only if they are perfectly divisible by 400.
For example,
1968 1971
2004 2006
2012 2010
1200 1700
1600 1800
2000 1900
In the examples below, the user is asked to enter a year, and the program checks whether the
year entered by the user is a leap year or not.
Example 1: Check Leap Year Using if...else Ladder
#include <iostream>
using namespace std;
int main() {
int year;
cout << "Enter a year: ";
cin >> year;
return 0;
}
Run Code
Output 1
Output 2
int main() {
int year;
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) {
cout << year << " is a leap year.";
}
else {
cout << year << " is not a leap year.";
}
}
else {
cout << year << " is a leap year.";
}
}
else {
cout << year << " is not a leap year.";
}
return 0;
}
Run Code
Here, we have used nested if statements to check whether the year given by the user is a
leap year or not.
First, we check if year is divisible by 4 or not. If it is not divisible, then it is not a leap year.
If it is divisible by 4, then we use an inner if statement to check whether year is divisible
by 100.
If it is not divisible by 100, it is still divisible by 4 and so it is a leap year.
We know that the century years are not leap years unless they are divisible by 400.
So, if year is divisible by 100, another inner if statement checks whether it is divisible
by 400 or not.
If it's divisible by 400, it is a leap year. Otherwise, it's not a leap year.
Example 3: Check Leap Year Using Logical Operators
We can combine the conditions required for a leap year into a single if...else statement
using the && and || operators.
#include <iostream>
using namespace std;
int main() {
int year;
return 0;
}
13. C++ Program to Find Factorial
5! = 1 * 2 * 3 * 4 * 5 = 120
n! = 1 * 2 * 3 * ... * n
n! = 1 if n = 0 or n = 1
In this program, the user is asked to enter a positive integer. Then the
factorial of that number is computed and displayed on the screen.
int main() {
int n;
long factorial = 1.0;
if (n < 0)
cout << "Error! Factorial of a negative number doesn't exist.";
else {
for(int i = 1; i <= n; ++i) {
factorial *= i;
}
cout << "Factorial of " << n << " = " << factorial;
}
return 0;
}
Run Code
Output
In this program, we take a positive integer from the user and compute the
factorial using for loop. We print an error message if the user enters a
negative number.
We declare the type of factorial variable as long since the factorial of a
number may be very large.
When the user enters a positive integer (say 4), for loop is executed and
computes the factorial. The value of i is initially 1.
The program runs until the statement i <= n becomes false. This
prints Factorial of 4 = 24 on the screen. Here’s how the program
executes when n = 4.
i <= 4 fact *= i
1 <= 4 fact = 1 * 1 = 1
2 <= 4 fact = 1 * 2 = 2
3 <= 4 fact = 2 * 3 = 6
fact = 6 * 4 = 24
4 <= 4
int main() {
int n;
return 0;
}
Run Code
Output
#include <iostream>
using namespace std;
int main() {
int n, range;
return 0;
}
Run Code
Output
Enter an integer: 8
Enter range: 12
8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80
8 * 11 = 88
8 * 12 = 96
15. C++ Program to Display Fibonacci Series
In this article, you will learn to print fibonacci series in C++ programming
(up to nth term, and up to a certain number).
#include <iostream>
using namespace std;
int main() {
int n, t1 = 0, t2 = 1, nextTerm = 0;
Output
#include <iostream>
using namespace std;
int main() {
int t1 = 0, t2 = 1, nextTerm = 0, n;
nextTerm = t1 + t2;
while(nextTerm <= n) {
cout << nextTerm << ", ";
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
Output
Enter a positive integer: 100
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
16. C++ Program to Find GCD
For example, the GCD of 4 and 10 is 2 since it is the largest integer that
can divide both 4 and 10.
Example: 1. Find HCF/GCD using for loop
#include <iostream>
using namespace std;
int main() {
int n1, n2, hcf;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
return 0;
}
Run Code
int main() {
int n1, n2;
while(n1 != n2) {
if(n1 > n2)
n1 -= n2;
else
n2 -= n1;
}
return 0;
}
Run Code
Output
n1 n2 n1 > n2 n1 -= n2 n2 -= n1 n1 != n2
16 76 false - 60 true
16 60 false - 44 true
16 44 false - 28 true
16 28 false - 12 true
16 12 true 4 - true
4 12 false - 8 true
4 8 false - 4 false
#include <iostream>
using namespace std;
int main()
{
int n1, n2, max;
do
{
if (max % n1 == 0 && max % n2 == 0)
{
cout << "LCM = " << max;
break;
}
else
++max;
} while (true);
return 0;
}
Output
#include <iostream>
using namespace std;
int main()
{
int n1, n2, hcf, temp, lcm;
while(hcf != temp)
{
if(hcf > temp)
hcf -= temp;
else
temp -= hcf;
}
int main() {
while(n != 0) {
remainder = n % 10;
reversed_number = reversed_number * 10 + remainder;
n /= 10;
}
return 0;
}
Run Code
Output
This program takes an integer input from the user and stores it in
variable n.
Then the while loop is iterated until n != 0 is false.
In each iteration, the remainder when the value of n is divided by 10 is
calculated, reversed_number is computed and the value of n is
decreased 10 fold.
Let us see this process in greater detail:
n n != 0 remainder reversed_number
2345 true 5 0 * 10 + 5 = 5
234 true 4 5 * 10 + 4 = 54
23 true 3 54 * 10 + 3 = 543
This program takes two numbers from the user (a base number and an
exponent) and calculates the power.
#include <iostream>
using namespace std;
int main()
{
int exponent;
float base, result = 1;
cout << base << "^" << exponent << " = ";
while (exponent != 0) {
result *= base;
--exponent;
}
return 0;
}
Output
Enter base and exponent respectively: 3.4
5
3.4^5 = 454.354
53 = 5 x 5 x 5 = 125
Here, 5 is the base and 3 is the exponent.
In this program, we have calculated the power of a number using
a while loop.
while (exponent != 0) {
result *= base;
--exponent;
}
#include <iostream>
#include <cmath>
int main()
{
float base, exponent, result;
cout << base << "^" << exponent << " = " << result;
return 0;
}
Output
In this program, we have used the pow() function to calculate the power
of a number.
Notice that we have included the cmath header file in order to use
the pow() function.
We take the base and exponent from the user.
We then use the pow() function to calculate the power. The first
argument is the base, and the second argument is the exponent .
Increment ++ and Decrement -- Operator Overloading in C++
Programming
In this example, you'll learn to overload increment ++ and decrement --
operators in C++.
#include <iostream>
using namespace std;
class Check
{
private:
int i;
public:
Check(): i(0) { }
void operator ++()
{ ++i; }
void Display()
{ cout << "i=" << i << endl; }
};
int main()
{
Check obj;
return 0;
}
Output
i=0
i=1
Initially when the object obj is declared, the value of data member i for
object obj is 0 (constructor initializes i to 0).
When ++ operator is operated on obj, operator function void operator+
+( ) is invoked which increases the value of data member i to 1.
This program is not complete in the sense that, you cannot used code:
obj1 = ++obj;
Here is the little modification of above program so that you can use
code obj1 = ++obj.
#include <iostream>
using namespace std;
class Check
{
private:
int i;
public:
Check(): i(0) { }
return temp;
}
void Display()
{ cout << "i = " << i << endl; }
};
int main()
{
Check obj, obj1;
[Link]();
[Link]();
obj1 = ++obj;
[Link]();
[Link]();
return 0;
}
Output
i = 0
i = 0
i = 1
i = 1
The only difference is that, the return type of operator function is Check in
this case which allows to use both codes ++obj; obj1 = ++obj;. It is
because, temp returned from operator function is stored in object obj.
Since, the return type of operator function is Check, you can also assign
the value of obj to another object.
Notice that, = (assignment operator) does not need to be overloaded
because this operator is already overloaded in C++ library.
This is the modification of above program to make this work both for
prefix form and postfix form.
#include <iostream>
using namespace std;
class Check
{
private:
int i;
public:
Check(): i(0) { }
Check operator ++ ()
{
Check temp;
temp.i = ++i;
return temp;
}
void Display()
{ cout << "i = "<< i <<endl; }
};
int main()
{
Check obj, obj1;
[Link]();
[Link]();
return 0;
}
Output
i = 0
i = 0
i = 1
i = 1
i = 2
i = 1
#include <iostream>
using namespace std;
class Check
{
private:
int i;
public:
Check(): i(3) { }
Check operator -- ()
{
Check temp;
temp.i = --i;
return temp;
}
void Display()
{ cout << "i = "<< i <<endl; }
};
int main()
{
Check obj, obj1;
[Link]();
[Link]();
return 0;
}
Output
i = 3
i = 3
i = 2
i = 2
i = 1
i = 2
Palindrome or Not
This program reverses an integer (entered by the user) using while loop. Then, if
statement is used to check whether the reversed number is equal to the original
number or not.
To understand this example, you should have the knowledge of the following C++
programming topics:
C++ while and do...while Loop
C++ if, if...else and Nested if...else
This program takes an integer from user and that integer is reversed.
If the reversed integer is equal to the integer entered by user then, that number is a
palindrome if not that number is not a palindrome.
#include <iostream>
using namespace std;
int main()
{
int n, num, digit, rev = 0;
n = num;
do
{
digit = num % 10;
rev = (rev * 10) + digit;
num = num / 10;
} while (num != 0);
cout << " The reverse of the number is: " << rev << endl;
if (n == rev)
cout << " The number is a palindrome.";
else
cout << " The number is not a palindrome.";
return 0;
}
Output
In the above program, use is asked to enter a positive number which is stored in the
variable num .
The number is then saved into another variable n to check it when the original
number has been reversed.
Inside the do...while loop, last digit of the number is separated using the
code digit = num % 10; . This digit is then added to the rev variable.
Before adding the digit to rev , we first need to multiply the current data in
the rev variable by 10 in order to add the digit to the nth place in the number.
For example: in the number 123, 3 is in the zeroth place, 2 in the oneth place and 1 in
the hundredth place.
So, to add another number 4 after 123, we need to shift the current numbers to the
left, so now 1 is in the thousandth place, 2 in the oneth place, 3 is in the onethplace
and 4 in the zeroth place.
This is done easily by multiplying 123 by 10 which gives 1230 and adding the
number 4, which gives 1234. The same is done in the code above.
When the do while loop finally ends, we have a reversed number in rev . This
number is then compared to the original number n .
If the numbers are equal, the original number is a palindrome, otherwise it's not.