0% found this document useful (0 votes)
7 views

C-Programs-Code-Explanation-Line-by-Line

C++ is a high-level, general-purpose programming language developed in 1983, known for its performance and versatility in various applications. It supports object-oriented programming and multiple paradigms, making it suitable for developing complex software. The document includes several examples of C++ programs with explanations, covering basic operations and concepts.

Uploaded by

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

C-Programs-Code-Explanation-Line-by-Line

C++ is a high-level, general-purpose programming language developed in 1983, known for its performance and versatility in various applications. It supports object-oriented programming and multiple paradigms, making it suitable for developing complex software. The document includes several examples of C++ programs with explanations, covering basic operations and concepts.

Uploaded by

cafer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

C++ PROGRAMS AND

EXPLANATIONS

WWW.CODE4EXAMPLE.COM
C++ is a high-level, general-purpose programming language developed by Bjarne Stroustrup
in 1983. It is an extension of the C language and is widely used for developing operating
systems, system software, and various applications such as gaming, financial modeling, and
scientific simulations.

C++ is an object-oriented language, which means it allows for encapsulation, inheritance, and
polymorphism, making it easier for developers to write maintainable and reusable code. It
also supports multiple programming paradigms, including procedural, functional, and generic
programming.

One of the main advantages of C++ is its performance. It is compiled, meaning that its code is
translated into machine code that is executed directly by the computer's hardware. This results
in faster execution times compared to interpreted languages like Python or JavaScript.

Another feature of C++ is its Standard Template Library (STL), which provides a collection
of pre-written algorithms and data structures that can be easily reused, making it easier to
develop complex programs.

C++ is widely used in the industry, with many well-known companies relying on it for their
software development. This is because it is a versatile language that can be used for many
different purposes, making it a valuable tool for software developers.

Overall, C++ is a powerful and widely-used programming language that is used for
developing a wide range of applications. Its performance, versatility, and extensive library
make it a valuable tool for software developers.

Here is C++ Programs and explanations line by line.


Contents
Example 1: Print Number Entered by User.................................................................................... 3
Example 2: Program to Add Two Integers ..................................................................................... 4
Example 3: Compute quotient and remainder ............................................................................... 5
Example 4: Swap Numbers (Using Temporary Variable) ............................................................. 7
Example 5: Swap Numbers Without Using Temporary Variables ............................................... 9
Example 6: Check Whether Number is Even or Odd using if else ............................................. 11
Example 7: Check Whether Number is Even or Odd using ternary operators......................... 13
Example 8: Find Largest Number Using if...else Statement ........................................................ 14
Example 9: Find the Largest Number Using Nested if...else statement...................................... 15
Example 10: Roots of a Quadratic Equation ................................................................................ 17
Example 11: Sum of Natural Numbers using loop ....................................................................... 19
Example 12: Check Leap Year Using if...else Ladder .................................................................. 20
Example 13: Check Leap Year Using Nested if ............................................................................ 21
Example 14: Find the Factorial of a Given Number .................................................................... 22
Example 15: Display Multiplication Table up to a Given Range ................................................ 23
Example 16: Fibonacci Series up to n number of terms .............................................................. 24
Example 17: Program to Generate Fibonacci Sequence Up to a Certain Number ................... 26
Example 18: Find HCF/GCD using for loop ................................................................................. 28
Example 19: Find GCD/HCF using while loop ............................................................................. 30
Example 20: Find LCM .................................................................................................................. 32
For Others Examples Click Here(40+ Examples and Explanations) ................................................... 33
Example 1: 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;
}

Output:

Enter an integer: 112


You entered 112

Here's an explanation of the code line by line:

#include <iostream> is a preprocessor directive that includes the iostream library in the
program. This library provides input/output functionality to the program.

using namespace std; allows the use of standard library objects and functions without
having to qualify them with std::.

int main() is the main function of the program. All C++ programs must have a main
function.

int number; declares an integer variable named number.

cout << "Enter an integer: "; writes the string "Enter an integer: " to the console.

cin >> number; reads an integer from the user and stores it in the number variable.

cout << "You entered " << number; writes the string "You entered " followed by the
value of number to the console.

return 0; ends the main function and returns a value of 0 to the operating system, indicating
that the program ran successfully.
Example 2: 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;
}

Output:

Enter two integers: 12


23
12 + 23 = 35

Here's an explanation of the code line by line:

#include <iostream>: This line includes the standard input/output library in the program.

using namespace std;: This line includes the standard namespace in the program.

int main(): The main function, the starting point of the program.

int first_number, second_number, sum;: Three integer variables are declared,


first_number and second_number to store the input numbers, and sum to store the sum of
the two numbers.

cout << "Enter two integers: ";: This line outputs the prompt "Enter two integers: " on
the screen.

cin >> first_number >> second_number;: This line reads two integers from the input
stream and stores them in first_number and second_number respectively.

sum = first_number + second_number;: The sum of first_number and second_number


is calculated and stored in the sum variable.

cout << first_number << " + " << second_number << " = " << sum;: This line
outputs the expression first_number + second_number = sum on the screen.

return 0;: This line returns 0 to indicate that the program executed successfully.

The program ends.

Click here for more examples


Example 3: 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;
}

Output:

Enter dividend: 120


Enter divisor: 25
Quotient = 4
Remainder = 20

Here's an explanation of the code line by line:

#include <iostream>: This line includes the iostream library, which provides input and
output functions (e.g. cin and cout).

using namespace std;: This line makes all the symbols in the std namespace accessible
without the std:: prefix.

int main(): This line defines the main function, which is the entry point of the program. The
int keyword indicates that the function returns an integer.

int divisor, dividend, quotient, remainder;: This line declares four variables named
divisor, dividend, quotient, and remainder, all of type int.

cout << "Enter dividend: ";: This line outputs the text "Enter dividend: " to the console
using the cout stream.

cin >> dividend;: This line inputs an integer from the user and stores it in the dividend
variable using the cin stream.

cout << "Enter divisor: ";: This line outputs the text "Enter divisor: " to the console
using the cout stream.

cin >> divisor;: This line inputs an integer from the user and stores it in the divisor
variable using the cin stream.

quotient = dividend / divisor;: This line calculates the integer division of dividend
by divisor and stores the result in the quotient variable.
remainder = dividend % divisor;: This line calculates the remainder of dividend
divided by divisor using the modulo operator % and stores the result in the remainder
variable.

cout << "Quotient = " << quotient << endl;: This line outputs the value of quotient
to the console, followed by a newline character.

cout << "Remainder = " << remainder;: This line outputs the value of remainder to the
console.

return 0;: This line returns the value 0 to indicate that the program executed successfully.

}: This closes the main function definition.


Example 4: 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

Here's an explanation of the code line by line:

#include <iostream>: This line includes the iostream library, which provides input and
output functions (e.g. cin and cout).

using namespace std;: This line makes all the symbols in the std namespace accessible
without the std:: prefix.

int main(): This line defines the main function, which is the entry point of the program. The
int keyword indicates that the function returns an integer.

int a = 5, b = 10, temp;: This line declares three variables named a, b, and temp, with a
initialized to 5, b initialized to 10, and temp uninitialized.

cout << "Before swapping." << endl;: This line outputs the text "Before swapping." to
the console, followed by a newline character, using the cout stream.

cout << "a = " << a << ", b = " << b << endl;: This line outputs the values of a and
b to the console, separated by a comma and a space, followed by a newline character, using
the cout stream.

temp = a;: This line stores the value of a in temp.

a = b;: This line assigns the value of b to a.

b = temp;: This line assigns the value of temp to b.


cout << "\nAfter swapping." << endl;: This line outputs the text "After swapping." to
the console, followed by a newline character, using the cout stream.

cout << "a = " << a << ", b = " << b << endl;: This line outputs the values of a and
b to the console, separated by a comma and a space, followed by a newline character, using
the cout stream.

return 0;: This line returns the value 0 to indicate that the program executed successfully.

}: This closes the main function definition.

Click here for more examples


Example 5: 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;
}

Output:

Before swapping.
a = 5, b = 10

After swapping.
a = 10, b = 5

Here's an explanation of the code line by line:

#include <iostream>: This line includes the iostream library, which provides input and
output functions (e.g. cin and cout).

using namespace std;: This line makes all the symbols in the std namespace accessible
without the std:: prefix.

int main(): This line defines the main function, which is the entry point of the program. The
int keyword indicates that the function returns an integer.

int a = 5, b = 10;: This line declares two variables named a, b, with a initialized to 5 and
b initialized to 10.

cout << "Before swapping." << endl;: This line outputs the text "Before swapping." to
the console, followed by a newline character, using the cout stream.

cout << "a = " << a << ", b = " << b << endl;: This line outputs the values of a and
b to the console, separated by a comma and a space, followed by a newline character, using
the cout stream.

a = a + b;: This line adds the values of a and b and stores the result in a.

b = a - b;: This line subtracts the value of b from a and stores the result in b.

a = a - b;: This line subtracts the value of b from a and stores the result in a.
cout << "\nAfter swapping." << endl;: This line outputs the text "After swapping." to
the console, followed by a newline character, using the cout stream.

cout << "a = " << a << ", b = " << b << endl;: This line outputs the values of a and
b to the console, separated by a comma and a space, followed by a newline character, using
the cout stream.

return 0;: This line returns the value 0 to indicate that the program executed successfully.

}: This closes the main function definition.


Example 6: 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;
}

Output:

Enter an integer: 123


123 is odd.

Explanation line by line:

#include <iostream>: The standard library iostream header file is included. It contains
functions to input and output data, such as cin and cout.

using namespace std;: The standard namespace std is defined, so that the standard library
functions can be called without using the namespace name.

int main(): The main function is the starting point of the program. The int in front of main
indicates that the main function returns an integer value.

int n;: An integer variable n is declared.

cout << "Enter an integer: ";: The message "Enter an integer: " is printed to the
console.

cin >> n;: The user is prompted to enter an integer, which is stored in the n variable.

if ( n % 2 == 0): The if statement checks if n is even. If n is evenly divisible by 2, n % 2


will equal 0. The == operator is used to compare two values for equality. If the comparison is
true, the code inside the if block will execute.

cout << n << " is even.";: The message "is even" is printed to the console, along with
the value of n.

else: If the comparison in the if statement is false, the code inside the else block will
execute.

cout << n << " is odd.";: The message "is odd" is printed to the console, along with the
value of n.
return 0;: The main function returns the integer value 0, indicating that the program has run
successfully.
Example 7: Check Whether Number is Even or Odd using
ternary operators
#include <iostream>
using namespace std;

int main() {
int n;

cout << "Enter an integer: ";


cin >> n;

(n % 2 == 0) ? cout << n << " is even." : cout << n << " is odd.";

return 0;
}

Output:

Enter an integer: 246


246 is even.

Here's an explanation of the code line by line:

The line #include <iostream> includes the standard input/output library in the program,
which allows us to use the input/output stream operators cin and cout.

The line using namespace std; allows us to use the standard library without having to
qualify it with std::.

The line int main() declares the main function, which is the starting point of the program.
The line int n; declares the integer variable n, which will be used to store the input entered
by the user.

The lines cout << "Enter an integer: "; and cin >> n; prompt the user to enter an
integer, which is stored in the variable n.

The line (n % 2 == 0) ? cout << n << " is even." : cout << n << " is odd.";
uses a ternary operator to check if n is even or odd. If n is divisible by 2 with no remainder,
then n % 2 will equal 0, so the expression n % 2 == 0 will evaluate to true and the program
will print n followed by "is even". If n is not divisible by 2 with no remainder, then the
expression n % 2 == 0 will evaluate to false, and the program will print n followed by "is
odd".

Finally, the line return 0; ends the main function and returns a value of 0 to indicate
successful completion of the program.

Click here for more examples


Example 8: Find Largest Number Using if...else Statement
This program calculates the largest number from 3 inputted numbers. The code uses
conditional statements to check which number is the largest and outputs it.

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

Output:

Enter three numbers: 50


30
40
Largest number: 50

Here's an explanation of the code line by line:

Include the iostream library and use the "using namespace std;" directive to allow for using
the standard input and output functions.

The main function starts.

Three double variables, n1, n2, and n3, are declared to store the inputted numbers.

The user is prompted to enter three numbers and the values are stored in the n1, n2, and n3
variables using the cin function.

An if-else statement is used to check if n1 is the largest number. If n1 is greater than or equal
to both n2 and n3, the message "Largest number: n1" is outputted.

Another if-else statement is used to check if n2 is the largest number. If n2 is greater than or
equal to both n1 and n3, the message "Largest number: n2" is outputted.

The last else statement checks if neither n1 nor n2 are the largest number. In this case, n3
must be the largest number and the message "Largest number: n3" is outputted.

The main function returns 0, indicating that the program has run successfully.
Example 9: 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;
}

Output:

Enter three numbers: 50


30
40
Largest number: 50

Here's an explanation line by line:

#include <iostream>: This line includes the standard input/output library in the C++
program, which provides functions like cin and cout.

using namespace std;: This line is used to include the standard namespace in the program,
so you don't have to qualify cout and cin with the scope operator std::.

int main(): This line declares the main function, which is the starting point of the program.
double n1, n2, n3;: These lines declare three variables, n1, n2, and n3, of type double to
store the three numbers entered by the user.

cout << "Enter three numbers: ";: This line prints the message "Enter three numbers: "
to the console to prompt the user to enter three numbers.

cin >> n1 >> n2 >> n3;: This line reads the three numbers entered by the user and stores
them in the variables n1, n2, and n3.

if (n1 >= n2) {: This line starts the first if statement, which checks if n1 is greater than or
equal to n2.

if (n1 >= n3): This line starts the nested if statement, which checks if n1 is also greater
than or equal to n3.

cout << "Largest number: " << n1;: If both conditions in the if statements are true, this
line prints the message "Largest number: " followed by the value of n1.

else: If the condition in the nested if statement is false, this line starts the else block.

cout << "Largest number: " << n3;: This line prints the message "Largest number: "
followed by the value of n3, since n1 is greater than n2 but not n3.

else: If the condition in the first if statement is false, this line starts the else block.

if (n2 >= n3): This line starts a nested if statement, which checks if n2 is greater than or
equal to n3.

cout << "Largest number: " << n2;: If the condition in the nested if statement is true,
this line prints the message "Largest number: " followed by the value of n2.

else: If the condition in the nested if statement is false, this line starts the else block.

cout << "Largest number: " << n3;: This line prints the message "Largest number: "
followed by the value of n3, since n2 is greater than n1 but not n3.

return 0;: This line ends the main function and returns a value of 0 to indicate that the
program ran successfully.
Example 10: 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: 8


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

Here's an explanation line by line:

The code starts by including the iostream and cmath libraries. iostream provides
input/output functions (cin and cout), and cmath provides mathematical functions (sqrt).

This line specifies that the standard namespace std should be used in the program, which
includes the input/output and mathematical functions.

In the main function, variables a, b, c, x1, x2, discriminant, realPart, and imaginaryPart
are declared as float types.

The program outputs a message asking the user to input the coefficients a, b, and c, and then
uses cin to read the user's input into the variables.
The discriminant of a quadratic equation is calculated as b^2 - 4ac. The value is stored in
the variable discriminant.

If the discriminant is greater than 0, then the roots of the equation are real and different. The
roots are calculated using the formula (-b ± √(discriminant)) / (2a), and the results are
stored in x1 and x2. The program outputs a message indicating that the roots are real and
different, and the values of x1 and x2.

If the discriminant is equal to 0, then the roots of the equation are real and the same. The
value of the root is calculated as -b/(2a), and stored in x1. The program outputs a message
indicating that the roots are real and the same, and the value of the root.

return 0;: This line ends the main function and returns a value of 0 to indicate that the
program ran successfully.

Click here for more examples


Example 11: 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: 23


Sum = 276

Here's an explanation line by line:

The program includes the "iostream" library and uses the "std" namespace.

In the main function, an integer variable "n" is declared and initialized by the user's input, and
an integer variable "sum" is initialized to 0.

The program calculates the sum of the first "n" positive integers using a for loop.

In the for loop, the variable "i" is initialized to 1 and increments by 1 until it reaches "n". The
sum is calculated by adding the current value of "i" to the current value of "sum".

After the for loop, the program prints the calculated sum value.

The program returns 0, indicating a successful execution.


Example 12: Check Leap Year Using if...else Ladder
This C++ program determines if a given year is a leap year or not.

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

Output:

Enter a year: 2004


2004 is a leap year.

Here's an explanation line by line:

The program includes the "iostream" library and uses the "std" namespace.

In the main function, an integer variable "year" is declared and initialized by the user's input.

The first if statement checks if the year is perfectly divisible by 400. If true, the program
prints "year is a leap year".

The else if statement checks if the year is divisible by 100 but not divisible by 400. If true, the
program prints "year is not a leap year".

The second else if statement checks if the year is not divisible by 100 but is divisible by 4. If
true, the program prints "year is a leap year".

The final else statement catches all other cases and prints "year is not a leap year".

The program returns 0, indicating a successful execution.


Example 13: 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;
}

Output:

Enter a year: 2004


2004 is a leap year.

Here's an explanation line by line:

The program includes the "iostream" library and uses the "std" namespace.

In the main function, an integer variable "year" is declared and initialized by the user's input.

The first if statement checks if the year is divisible by 4. If true, the program proceeds to the
next step.

The nested if statement checks if the year is divisible by 100. If true, the program proceeds to
the next step.

The nested if statement checks if the year is divisible by 400. If true, the program prints "year
is a leap year".

If the year is not divisible by 400, the program prints "year is not a leap year".

If the year is not divisible by 100, the program prints "year is a leap year".

If the year is not divisible by 4, the program prints "year is not a leap year".

The program returns 0, indicating a successful execution.


Click here for more examples

Example 14: 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;
}

Output:

Enter a positive integer: 6


Factorial of 6 = 720

Here's an explanation line by line:

The program includes the "iostream" library and uses the "std" namespace.

In the main function, an integer variable "n" is declared and initialized by the user's input, and
a long variable "factorial" is initialized to 1.

The program checks if the input integer "n" is less than 0. If true, it prints an error message
"Error! Factorial of a negative number doesn't exist."

If the input integer "n" is non-negative, the program enters the else block and calculates the
factorial using a for loop.

In the for loop, the variable "i" is initialized to 1 and increments by 1 until it reaches "n". The
factorial is calculated by multiplying the current value of "factorial" with the current value of
"i".

After the for loop, the program prints the calculated factorial value.

The program returns 0, indicating a successful execution.


Example 15: Display Multiplication Table up to a Given
Range
#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;
}

Output:

Enter an integer: 7
Enter range: 10
7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
7 * 10 = 70

Here's an explanation line by line:

The program includes the "iostream" library and uses the "std" namespace.

In the main function, two integer variables "n" and "range" are declared and initialized by the
user's input.

The program generates the multiplication table of "n" up to a given range using a for loop.

In the for loop, the variable "i" is initialized to 1 and increments by 1 until it reaches "range".
The multiplication result is calculated by multiplying the current value of "n" and "i".

The program prints each multiplication result, along with the values of "n" and "i".

The program returns 0, indicating a successful execution.


Example 16: 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: 20


Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,
610, 987, 1597, 2584, 4181,

Here is an explanation of the code line by line:

#include <iostream>: This line includes the header file iostream, which provides input
and output functionality in C++.

using namespace std;: This line specifies that all the names in the standard library should
be in the std namespace.

int main(): This is the main function of the program, which is the entry point of the
program and returns an integer value.

int n, t1 = 0, t2 = 1, nextTerm = 0;: This line declares four integer variables, n, t1,
t2, and nextTerm. n is used to store the number of terms to be printed, t1 and t2 are used to
store the first two terms in the Fibonacci series, and nextTerm is used to store the next term in
the series.

cout << "Enter the number of terms: ";: This line outputs the prompt "Enter the
number of terms: " to the console.

cin >> n;: This line reads the number of terms from the user and stores it in the variable n.
cout << "Fibonacci Series: ";: This line outputs the text "Fibonacci Series: " to the
console.

for (int i = 1; i <= n; ++i): This is the start of a for loop that will run n times. i is the
loop counter, which starts from 1 and increases by 1 each iteration until it reaches n.

if (i == 1): This if statement checks if the current value of i is equal to 1. If it is, the first
term of the Fibonacci series is printed to the console.

continue;: This line skips to the next iteration of the loop, bypassing the rest of the code in
the current iteration.

if (i == 2): This if statement checks if the current value of i is equal to 2. If it is, the
second term of the Fibonacci series is printed to the console.

nextTerm = t1 + t2;: This line calculates the next term in the series by adding t1 and t2.

t1 = t2;: This line sets the value of t1 to the value of t2.

t2 = nextTerm;: This line sets the value of t2 to the value of nextTerm.

cout << nextTerm << ", ";: This line outputs the value of nextTerm followed by a
comma and a space to the console.

return 0;: This line returns the value 0 from the main function, indicating that the program
has run successfully.
Example 17: 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 number: 50


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

Here's a line-by-line explanation of the code:

The first line #include <iostream> is a preprocessor directive that includes the input/output
stream library for C++.

The line using namespace std; makes all the standard library functions available to the
program without having to qualify them with the std:: prefix.

int main() is the starting point of every C++ program. It returns an integer value and is the
main function.

int t1 = 0, t2 = 1, nextTerm = 0, n; declares four integer variables: t1 and t2 are


used to store the previous two terms of the Fibonacci series, nextTerm is used to store the
next term of the series, and n is used to store the number up to which the Fibonacci series will
be generated.

cout << "Enter a positive number: "; outputs the message "Enter a positive number: "
on the screen.

cin >> n; is used to read an integer value from the user and store it in the variable n.

cout << "Fibonacci Series: " << t1 << ", " << t2 << ", "; outputs the message
"Fibonacci Series: " followed by the first two terms of the series, which is 0 and 1.

nextTerm = t1 + t2; calculates the next term of the series by adding the previous two
terms.
The while loop is executed while the value of nextTerm is less than or equal to n. Within the
loop, the code:

cout << nextTerm << ", "; outputs the next term of the series.

t1 = t2; assigns the value of t2 to t1.

t2 = nextTerm; assigns the value of nextTerm to t2.

nextTerm = t1 + t2; calculates the next term of the series by adding the previous two
terms.

return 0; returns a value of 0 to the operating system, indicating that the program has
executed successfully.

Click here for more examples


Example 18: 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;
}

Output:

Enter two numbers: 12


16
HCF = 4

Here's a line-by-line explanation of the code:

The first line #include <iostream> is a preprocessor directive that includes the input/output
stream library for C++.

The line using namespace std; makes all the standard library functions available to the
program without having to qualify them with the std:: prefix.

int main() is the starting point of every C++ program. It returns an integer value and is the
main function.

int n1, n2, hcf; declares three integer variables: n1 and n2 are used to store the two
numbers entered by the user, and hcf is used to store the highest common factor of the two
numbers.

cout << "Enter two numbers: "; outputs the message "Enter two numbers: " on the
screen.

cin >> n1 >> n2; is used to read two integer values from the user and store them in the
variables n1 and n2, respectively.

The if-statement if ( n2 > n1) checks if the value of n2 is greater than n1. If true, the code
within the block swaps the values of n1 and n2 using a temporary variable temp.
The for loop is executed for the number of times equal to the value of n2. Within the loop, the
code:

if (n1 % i == 0 && n2 % i ==0) checks if the variables n1 and n2 are divisible by i, the
loop counter.

If the condition is true, hcf = i; assigns the value of i to hcf.

cout << "HCF = " << hcf; outputs the message "HCF = " followed by the value of hcf,
which is the highest common factor of n1 and n2.

return 0; returns a value of 0 to the operating system, indicating that the program has
executed successfully.
Example 19: 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;
}

Output:

Enter two numbers: 12


16
HCF = 4

Here's a line-by-line explanation of the code:

The first line #include <iostream> is a preprocessor directive that includes the input/output
stream library for C++.

The line using namespace std; makes all the standard library functions available to the
program without having to qualify them with the std:: prefix.

int main() is the starting point of every C++ program. It returns an integer value and is the
main function.

int n1, n2; declares two integer variables: n1 and n2 are used to store the two numbers
entered by the user.

cout << "Enter two numbers: "; outputs the message "Enter two numbers: " on the
screen.

cin >> n1 >> n2; is used to read two integer values from the user and store them in the
variables n1 and n2, respectively.

The while loop while(n1 != n2) checks if n1 is not equal to n2. If true, the code within the
loop is executed.

The if-else statement if(n1 > n2) checks if n1 is greater than n2.

If true, n1 -= n2; subtracts n2 from n1.

If false, n2 -= n1; subtracts n1 from n2.


cout << "HCF = " << n1; outputs the message "HCF = " followed by the value of n1,
which is the highest common factor of n1 and n2.

return 0; returns a value of 0 to the operating system, indicating that the program has
executed successfully.
Example 20: 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


16
LCM = 48

Here's a line-by-line explanation of the code:

The first line #include <iostream> is a preprocessor directive that includes the input/output
stream library for C++.

The line using namespace std; makes all the standard library functions available to the
program without having to qualify them with the std:: prefix.

int main() is the starting point of every C++ program. It returns an integer value and is the
main function.

int n1, n2, max; declares three integer variables: n1 and n2 are used to store the two
numbers entered by the user, and max is used to store the maximum value between n1 and n2.

cout << "Enter two numbers: "; outputs the message "Enter two numbers: " on the
screen.

cin >> n1 >> n2; is used to read two integer values from the user and store them in the
variables n1 and n2, respectively.

max = (n1 > n2) ? n1 : n2; assigns the greater of the two values n1 and n2 to the
variable max. The conditional operator (?) checks if n1 is greater than n2, and if true, n1 is
assigned to max. If false, n2 is assigned to max.
The do-while loop do { ... } while (true); executes the code within the loop at least
once and then continues to execute as long as the condition (true) is met.

The if-else statement if (max % n1 == 0 && max % n2 == 0) checks if max is divisible by


both n1 and n2 without a remainder.

If true, cout << "LCM = " << max; outputs the message "LCM = " followed by the value of
max, which is the least common multiple of n1 and n2.

If false, ++max; increments the value of max by 1.

break; terminates the do-while loop when the least common multiple of n1 and n2 is found.

return 0; returns a value of 0 to the operating system, indicating that the program has
executed successfully.

For Others Examples Click Here(40+ Examples and


Explanations)

You might also like