0% found this document useful (0 votes)
5 views55 pages

C++ File

The document provides a comprehensive guide to basic C++ programming concepts through various examples, including creating a 'Hello, World!' program, user input, arithmetic operations, and control structures. It covers topics such as printing numbers, adding integers, finding quotients and remainders, checking even or odd numbers, and identifying vowels or consonants. Additionally, it includes examples for finding the largest number among three inputs and solving quadratic equations.

Uploaded by

123ayushboss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views55 pages

C++ File

The document provides a comprehensive guide to basic C++ programming concepts through various examples, including creating a 'Hello, World!' program, user input, arithmetic operations, and control structures. It covers topics such as printing numbers, adding integers, finding quotients and remainders, checking even or odd numbers, and identifying vowels or consonants. Additionally, it includes examples for finding the largest number among three inputs and solving quadratic equations.

Uploaded by

123ayushboss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1. C++ "Hello, World!" Program.

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.

C++ "Hello World!" Program


// Your First C++ Program

#include <iostream>

int main() {
std::cout << "Hello World!";
return 0;
}
Run Code

Output

Hello World!

Working of C++ "Hello World!" Program

1. // Your First C++ Program

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.

For now, just remember that we need to use #include <iostream> to


use cout that allows us to print output on the screen.
3. int main() {...}

A valid C++ program must have the main() function. The curly braces indicate the
start and the end of the function.

The execution of code beings from this function.


4. std::cout << "Hello World!";

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.

Note: ; is used to indicate the end of a statement.


5. return 0;

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.

Print Number Entered by User

#include <iostream>
using namespace std;

int main() {
int number;

cout << "Enter an integer: ";


cin >> number;

cout << "You entered " << number;


return 0;
}
Run Code

Output

Enter an integer: 23
You entered 23

This program asks the user to enter a number.

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

Example: Program to Add Two Integers


#include <iostream>
using namespace std;

int main() {

int first_number, second_number, sum;

cout << "Enter two integers: ";


cin >> first_number >> second_number;

// sum of two numbers in stored in variable sumOfTwoNumbers


sum = first_number + second_number;

// prints sum
cout << first_number << " + " << second_number << " = " << sum;

return 0;
}
Run Code

Output

Enter two integers: 4


5
4 + 5 = 9

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.

Example: Compute quotient and remainder


#include <iostream>
using namespace std;

int main()
{
int divisor, dividend, quotient, remainder;

cout << "Enter dividend: ";


cin >> dividend;

cout << "Enter divisor: ";


cin >> divisor;

quotient = dividend / divisor;


remainder = dividend % divisor;

cout << "Quotient = " << quotient << endl;


cout << "Remainder = " << 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.

To find the size of variable, sizeof operator is used.

sizeof(dataType);

Example: Find Size of a Variable

#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

Size of char: 1 byte


Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
6. C++ Program to Swap Two Numbers

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.

Example 1: Swap Numbers (Using Temporary Variable)

#include <iostream>
using namespace std;

int main()
{
int a = 5, b = 10, temp;

cout << "Before swapping." << endl;


cout << "a = " << a << ", b = " << b << endl;

temp = a;
a = b;
b = temp;

cout << "\nAfter swapping." << endl;


cout << "a = " << a << ", b = " << b << endl;

return 0;
}

Output

Before swapping.
a = 5, b = 10

After swapping.
a = 10, b = 5

To perform swapping in above example, three variables are used.

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.

Example 2: Swap Numbers Without Using Temporary


Variables

#include <iostream>
using namespace std;

int main()
{

int a = 5, b = 10;

cout << "Before swapping." << endl;


cout << "a = " << a << ", b = " << b << endl;

a = a + b;
b = a - b;
a = a - b;

cout << "\nAfter swapping." << endl;


cout << "a = " << a << ", b = " << b << endl;

return 0;
}

The output of this program is the same as the first program above.

Let us see how this program works:

1. Initially, a = 5 and b = 10.


2. Then, we add a and b and store it in a with the code a = a + b. This
means a = 5 + 10. So, a = 15 now.
3. Then we use the code b = a - b. This means b = 15 - 10. So, b =
5 now.
4. Again, we use the code a = a - b. This means a = 15 - 5. So finally, a
= 10.
hence, the numbers have been swapped.

7. C++ Program to Check Whether Number is Even or

Odd

In this example, if...else statement is used to check whether a number


entered by the user is even or odd.

To understand this example, you should have the knowledge of the


following C++ programming topics:
 C++ if, if...else and Nested if...else
 C++ Ternary Operator
Integers that are perfectly divisible by 2 are called even numbers.

And those integers that are not perfectly divisible by 2 are not known as
odd numbers.

To check whether an integer is even or odd, the remainder is calculated


when it is divided by 2 using modulus operator %. If the remainder is zero,
that integer is even if not that integer is odd.

Example 1: Check Whether Number is Even or Odd using


if else
#include <iostream>
using namespace std;

int main() {
int n;

cout << "Enter an integer: ";


cin >> 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.

In this program, an if..else statement is used to check whether n % 2


== 0 is true or not.
If this expression is true, n is even. Else, n is odd.
You can also use ternary operators ?: instead of if..else statement.
The ternary operator is a shorthand notation of if...else statement.
8. C++ Program to Check Whether a character is

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.

Example: Check Vowel or a Consonant Manually

#include <iostream>
using namespace std;

int main() {
char c;
bool isLowercaseVowel, isUppercaseVowel;

cout << "Enter an alphabet: ";


cin >> c;

// evaluates to 1 (true) if c is a lowercase vowel


isLowercaseVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' ||
c == 'u');

// evaluates to 1 (true) if c is an uppercase vowel


isUppercaseVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' ||
c == 'U');

// show error message if c is not an alphabet


if (!isalpha(c))
printf("Error! Non-alphabetic character.");
else if (isLowercaseVowel || isUppercaseVowel)
cout << c << " is a vowel.";
else
cout << c << " is a consonant.";

return 0;
}

Output

Enter an alphabet: u
u is a vowel.

The character entered by the user is stored in variable c.


The isLowerCaseVowel evaluates to true if c is a lowercase vowel and false for
any other character.
Similarly, isUpperCaseVowel evaluates to true if c is an uppercase vowel
and false for any other character.
If both isLowercaseVowel and isUppercaseVowel is true, the character entered
is a vowel, if not the character is a consonant.
The isalpha() function checks whether the character entered is an alphabet or not. If it is
not, it prints an error message.

9. C++ Program to Find Largest Number Among Three

Numbers

In this example, you'll learn to find the largest number among three
numbers using if, if else and nested if else statements.

To understand this example, you should have the knowledge of the


following C++ programming topics:
 C++ if, if...else and Nested if...else
In this program, the user is asked to enter three numbers.
Then this program finds out the largest number among three numbers
entered by user and displays it with a proper message.

This program can be written in more than one way.

Example 1: Find Largest Number Using if...else


Statement
#include <iostream>
using namespace std;

int main() {

double n1, n2, n3;

cout << "Enter three numbers: ";


cin >> n1 >> n2 >> n3;

// check if n1 is the largest number


if(n1 >= n2 && n1 >= n3)
cout << "Largest number: " << n1;

// check if n2 is the largest number


else if(n2 >= n1 && n2 >= n3)
cout << "Largest number: " << n2;

// if neither n1 nor n2 are the largest, n3 is the largest


else
cout << "Largest number: " << n3;

return 0;
}
Run Code

Output

Enter three numbers: 2.3


8.3
-4.2
Largest number: 8.3
Example 2: Find the Largest Number Using Nested
if...else statement
#include <iostream>
using namespace std;

int main() {

double n1, n2, n3;

cout << "Enter three numbers: ";


cin >> n1 >> n2 >> n3;

// check if n1 is greater than n2


if (n1 >= n2) {

// if n1 is also greater than n3,


// then n1 is the largest number
if (n1 >= n3)
cout << "Largest number: " << n1;

// but if n1 is less than n3


// but n1 is greater than n2
// then n3 is the largest number
else
cout << "Largest number: " << n3;
}

// else, n2 is greater than n1


else {

// if n2 is also greater than n3,


// then n2 is the largest number
if (n2 >= n3)
cout << "Largest number: " << n2;

// but if n2 is less than n3


// but n2 is greater than n1
// then n3 is the largest number
else
cout << "Largest number: " << n3;
}

return 0;
}
Run Code

Output

Enter three numbers: 2.3


8.3
-4.2
Largest number: 8.3
10. C++ Program to Find All Roots of a Quadratic

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.

Formula Formula to Find Roots of Quadratic Equation

The term b2-4ac is known as the discriminant of a quadratic equation. The


discriminant tells the nature of the roots.
 If discriminant is greater than 0, the roots are real and different.

 If discriminant is equal to 0, the roots are real and equal.

 If discriminant is less than 0, the roots are complex and different.


Calculate Root of Quadratic Equation

Example: Roots of a Quadratic Equation

#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

Enter coefficients a, b and c: 4


5
1
Roots are real and different.
x1 = -0.25
x2 = -1

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

In this example, you'll learn to calculate the sum of natural numbers.

To understand this example, you should have the knowledge of the


following C++ programming topics:
 C++ for Loop
Positive integers 1, 2, 3, 4... are known as 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.

Example: Sum of Natural Numbers using loop

#include <iostream>
using namespace std;

int main() {
int n, sum = 0;

cout << "Enter a positive integer: ";


cin >> n;

for (int i = 1; i <= n; ++i) {


sum += i;
}

cout << "Sum = " << sum;


return 0;
}

Output

Enter a positive integer: 50


Sum = 1275

This program assumes that user always enters positive number.


If user enters negative number, Sum = 0 is displayed and program is
terminated.
This program can also be done using recursion. Check out this article
for calculating sum of natural numbers using recursion.
12. C++ Program to Check Leap Year

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,

Leap Year Not Leap Year

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;

// leap year if perfectly divisible by 400


if (year % 400 == 0) {
cout << year << " is a leap year.";
}
// not a leap year if divisible by 100
// but not divisible by 400
else if (year % 100 == 0) {
cout << year << " is not a leap year.";
}
// leap year if not divisible by 100
// but divisible by 4
else if (year % 4 == 0) {
cout << year << " is a leap year.";
}
// all other years are not leap years
else {
cout << year << " is not a leap year.";
}

return 0;
}
Run Code

Output 1

Enter a year: 1900


1900 is not a leap year.

Output 2

Enter a year: 2012


2012 is a leap year.

Example 2: Check Leap Year Using Nested if


#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 << 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;

cout << "Enter a year: ";


cin >> year;

// if year is divisible by 4 AND not divisible by 100


// OR if year is divisible by 400
// then it is a leap year
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
cout << year << " is a leap year.";
}
else {
cout << year << " is not a leap year.";
}

return 0;
}
13. C++ Program to Find Factorial

The factorial of a positive integer n is equal to 1*2*3*...n. You will learn to


calculate the factorial of a number using for loop in this example.

To understand this example, you should have the knowledge of the


following C++ programming topics:
 C++ for Loop
The factorial of a number is the product of all the integers from 1 up to
that number. The factorial can only be defined for positive integers.
The factorial of a negative number doesn't exist. And the factorial
of 0 is 1.
For example,

The factorial of a positive number n, say 5, is denoted by 5! and is given


by:

5! = 1 * 2 * 3 * 4 * 5 = 120

So, the Mathematical logic for factorial is:

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.

Example: Find the Factorial of a Given Number


#include <iostream>
using namespace std;

int main() {
int n;
long factorial = 1.0;

cout << "Enter a positive integer: ";


cin >> n;

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

Enter a positive integer: 4


Factorial of 4 = 24

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

5 <= 4 Loop terminates.

Note: This program can calculate the factorial only up to the


number 20. Beyond that, the program can no longer calculate the
factorial as the results exceed the capacity of
the factorial variable.
14. C++ Program to Generate Multiplication Table

Example to generate the multiplication table of a number (entered by the


user) using for loop.

To understand this example, you should have the knowledge of the


following C++ programming topics:
 C++ for Loop

Example 1: Display Multiplication Table up to 10


#include <iostream>
using namespace std;

int main() {

int n;

cout << "Enter a positive integer: ";


cin >> n;

// run a loop from 1 to 10


// print the multiplication table
for (int i = 1; i <= 10; ++i) {
cout << n << " * " << i << " = " << n * i << endl;
}

return 0;
}
Run Code

Output

Enter a positive integer: 5


5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

This program above computes the multiplication table up to 10 only.

Example 2: Display Multiplication Table up to a Given


Range

The program below is a modification of the above program in which the


user is asked to enter the range up to which the multiplication table
should be displayed.

#include <iostream>
using namespace std;

int main() {

int n, range;

cout << "Enter an integer: ";


cin >> n;

cout << "Enter range: ";


cin >> range;

for (int i = 1; i <= range; ++i) {


cout << n << " * " << i << " = " << n * i << endl;
}

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).

To understand this example, you should have the knowledge of the


following C++ programming topics:
 C++ for Loop
 C++ while and do...while Loop
The Fibonacci sequence is a series where the next term is the sum of the
previous two terms. The first two terms of the Fibonacci sequence
is 0 followed by 1.

The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21

Example 1: Fibonacci Series up to n number of terms

#include <iostream>
using namespace std;

int main() {
int n, t1 = 0, t2 = 1, nextTerm = 0;

cout << "Enter the number of terms: ";


cin >> n;

cout << "Fibonacci Series: ";

for (int i = 1; i <= n; ++i) {


// Prints the first two terms.
if(i == 1) {
cout << t1 << ", ";
continue;
}
if(i == 2) {
cout << t2 << ", ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;

cout << nextTerm << ", ";


}
return 0;
}

Output

Enter the number of terms: 10


Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Example 2: Program to Generate Fibonacci Sequence Up


to a Certain Number

#include <iostream>
using namespace std;

int main() {
int t1 = 0, t2 = 1, nextTerm = 0, n;

cout << "Enter a positive number: ";


cin >> n;

// displays the first two terms which is always 0 and 1


cout << "Fibonacci Series: " << t1 << ", " << t2 << ", ";

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

Examples on different ways to calculate GCD of two integers (for both


positive and negative integers) using loops and decision making
statements.

To understand this example, you should have the knowledge of the


following C++ programming topics:
 C++ if, if...else and Nested if...else
 C++ for Loop
 C++ while and do...while Loop
The largest integer which can perfectly divide two integers is known as
GCD or HCF of those two numbers.

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;

// swapping variables n1 and n2 if n2 is greater than n1.


if ( n2 > n1) {
int temp = n2;
n2 = n1;
n1 = temp;
}

for (int i = 1; i <= n2; ++i) {


if (n1 % i == 0 && n2 % i ==0) {
hcf = i;
}
}
cout << "HCF = " << hcf;

return 0;
}
Run Code

The logic of this program is simple.

In this program, the smaller integer between n1 and n2 is stored in n2.


Then the loop is iterated from i = 1 to i <= n2 and in each iteration, the
value of i is increased by 1.
If both numbers are divisible by i then, that number is stored in
variable hcf.
This process is repeated in each iteration. When the iteration is finished,
HCF will be stored in variable hcf.
Example 2: Find GCD/HCF using while loop
#include <iostream>
using namespace std;

int main() {
int n1, n2;

cout << "Enter two numbers: ";


cin >> n1 >> n2;

while(n1 != n2) {
if(n1 > n2)
n1 -= n2;
else
n2 -= n1;
}

cout << "HCF = " << n1;

return 0;
}
Run Code

Output

Enter two numbers: 16


76
HCF = 4

In the above program, the smaller number is subtracted from the


larger number and that number is stored in place of the larger
number.

Here, n1 -= n2 is the same as n1 = n1 - n2 . Similarly, n2 -= n1 is the


same as n2 = n2 - n1 .

This process is continued until the two numbers become equal


which will be HCF.

Let us look at how this program works when n1 = 16 and n2 = 76 .

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

Here, the loop terminates when n1 != n2 becomes false .


After the final iteration of the loop, n1 = n2 = 4 . This is the value of
the GCD/HCF since this is the greatest number that can divide
both 16 and 76.

17. C++ Program to Find LCM

Examples on different ways to calculate the LCM (Lowest Common


Multiple) of two integers using loops and decision making statements.

To understand this example, you should have the knowledge of the


following C++ programming topics:
 C++ if, if...else and Nested if...else
 C++ while and do...while Loop
LCM of two integers a and b is the smallest positive integer that is
divisible by both a and b.
Example 1: Find LCM

#include <iostream>
using namespace std;

int main()
{
int n1, n2, max;

cout << "Enter two numbers: ";


cin >> n1 >> n2;

// maximum value between n1 and n2 is stored in max


max = (n1 > n2) ? n1 : n2;

do
{
if (max % n1 == 0 && max % n2 == 0)
{
cout << "LCM = " << max;
break;
}
else
++max;
} while (true);

return 0;
}

Output

Enter two numbers: 12


18
LCM = 36

In above program, user is asked to integer two integers n1 and n2 and


largest of those two numbers is stored in max.
It is checked whether max is divisible by n1 and n2, if it's divisible by both
numbers, max (which contains LCM) is printed and loop is terminated.
If not, value of max is incremented by 1 and same process goes on
until max is divisible by both n1 and n2.

Example 2: Find LCM using HCF

The LCM of two numbers is given by:

LCM = (n1 * n2) /

#include <iostream>
using namespace std;

int main()
{
int n1, n2, hcf, temp, lcm;

cout << "Enter two numbers: ";


cin >> n1 >> n2;
hcf = n1;
temp = n2;

while(hcf != temp)
{
if(hcf > temp)
hcf -= temp;
else
temp -= hcf;
}

lcm = (n1 * n2) / hcf;

cout << "LCM = " << lcm;


return 0;
}

18. C++ Program to Reverse a Number

Example to reverse an integer entered by the user in C++ programming.


This problem is solved by using while loop in this example.
To understand this example, you should have the knowledge of the
following C++ programming topics:
 C++ while and do...while Loop

Example: C++ Program to Reverse an Integer


#include <iostream>
using namespace std;

int main() {

int n, reversed_number = 0, remainder;

cout << "Enter an integer: ";


cin >> n;

while(n != 0) {
remainder = n % 10;
reversed_number = reversed_number * 10 + remainder;
n /= 10;
}

cout << "Reversed Number = " << reversed_number;

return 0;
}
Run Code

Output

Enter an integer: 2345


Reversed number = 5432

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

2 true 2 543 * 10 + 2 = 5432

0 false - Loop terminates.

Finally, reversed_number (which contains the reversed number) is printed


on the screen.

19. C++ Program to Calculate Power of a Number

In this article, we will learn to compute power to a number manually, and


by using pow() function.
To understand this example, you should have the knowledge of the
following C++ programming topics:
 C++ while and do...while Loop

This program takes two numbers from the user (a base number and an
exponent) and calculates the power.

Power of a number = baseexponent

Example 1: Compute Power Manually

#include <iostream>
using namespace std;

int main()
{
int exponent;
float base, result = 1;

cout << "Enter base and exponent respectively: ";


cin >> base >> exponent;

cout << base << "^" << exponent << " = ";

while (exponent != 0) {
result *= base;
--exponent;
}

cout << result;

return 0;
}

Output
Enter base and exponent respectively: 3.4
5
3.4^5 = 454.354

As we know, the power of a number is the number multiplied by itself


repeatedly. For example,

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;
}

Remember that we have already initialized result as 1 during the


beginning of the program.
Let us see how this while loop works if base == 5 and exponent == 3.
Iteration result *= base exponent exponent != 0 Execute Loop?

1st 5 3 true Yes

2nd 25 2 true Yes

3rd 125 1 true Yes

4th 625 0 false No

However, the above technique works only if the exponent is a positive


integer.
If you need to find the power of a number with any real number as an
exponent, you can use pow() function.

Example 2: Compute power using pow() Function

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
float base, exponent, result;

cout << "Enter base and exponent respectively: ";


cin >> base >> exponent;

result = pow(base, exponent);

cout << base << "^" << exponent << " = " << result;

return 0;
}

Output

Enter base and exponent respectively: 2.3


4.5
2.3^4.5 = 42.44

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

To understand this example, you should have the knowledge of the


following C++ programming topics:
 C++ Classes and Objects
 C++ Constructors
 C++ Operator Overloading
In this tutorial, increment ++ and decrements -- operator are overloaded
in best possible way, i.e., increase the value of a data member by 1 if ++
operator operates on an object and decrease value of data member by 1 if
-- operator is used.

Example 1: Prefix ++ Increment Operator Overloading


with no return type

#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;

// Displays the value of data member i for object obj


[Link]();
// Invokes operator function void operator ++( )
++obj;

// Displays the value of data member i for object obj


[Link]();

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;

It is because the return type of operator function in above program is


void.

Here is the little modification of above program so that you can use
code obj1 = ++obj.

Example 2: Prefix Increment ++ operator overloading


with return type

#include <iostream>
using namespace std;

class Check
{
private:
int i;
public:
Check(): i(0) { }

// Return type is Check


Check operator ++()
{
Check temp;
++i;
temp.i = i;

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

This program is similar to the one above.

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.

Example 3: Postfix Increment ++ Operator Overloading

Overloading of increment operator up to this point is only true if it is used


in prefix form.

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;
}

// Notice int inside barcket which indicates postfix increment.


Check operator ++ (int)
{
Check temp;
temp.i = i++;
return temp;
}

void Display()
{ cout << "i = "<< i <<endl; }
};
int main()
{
Check obj, obj1;
[Link]();
[Link]();

// Operator function is called, only then value of obj is assigned


to obj1
obj1 = ++obj;
[Link]();
[Link]();

// Assigns value of obj to obj1, only then operator function is


called.
obj1 = obj++;
[Link]();
[Link]();

return 0;
}

Output

i = 0

i = 0

i = 1

i = 1

i = 2

i = 1

When increment operator is overloaded in prefix form; Check operator +


+ () is called but, when increment operator is overloaded in postfix
form; Check operator ++ (int) is invoked.
Notice, the int inside bracket. This int gives information to the compiler
that it is the postfix version of operator.
Don't confuse this int doesn't indicate integer.
Example 4: Operator Overloading of Decrement --
Operator

Decrement operator can be overloaded in similar way as increment


operator.

#include <iostream>
using namespace std;

class Check
{
private:
int i;
public:
Check(): i(3) { }
Check operator -- ()
{
Check temp;
temp.i = --i;
return temp;
}

// Notice int inside barcket which indicates postfix decrement.


Check operator -- (int)
{
Check temp;
temp.i = i--;
return temp;
}

void Display()
{ cout << "i = "<< i <<endl; }
};

int main()
{
Check obj, obj1;
[Link]();
[Link]();

// Operator function is called, only then value of obj is assigned


to obj1
obj1 = --obj;
[Link]();
[Link]();

// Assigns value of obj to obj1, only then operator function is


called.
obj1 = obj--;
[Link]();
[Link]();

return 0;
}

Output

i = 3

i = 3

i = 2

i = 2

i = 1

i = 2

Also, unary operators like: !, ~ etc can be overloaded in similar manner.


20. C++ Program to Check Whether a Number is

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.

Example: Check Palindrome Number

#include <iostream>
using namespace std;

int main()
{
int n, num, digit, rev = 0;

cout << "Enter a positive number: ";


cin >> num;

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

Enter a positive number: 12321


The reverse of the number is: 12321
The number is a palindrome.

Enter a positive number: 12331


The reverse of the number is: 13321
The number is not a palindrome.

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.

You might also like