C-Programs-Code-Explanation-Line-by-Line
C-Programs-Code-Explanation-Line-by-Line
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.
int main() {
int number;
Output:
#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.
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() {
// prints sum
cout << first_number << " + " << second_number << " = " << sum;
return 0;
}
Output:
#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.
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.
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.
int main()
{
int divisor, dividend, quotient, remainder;
return 0;
}
Output:
#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.
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
#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.
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.
int main()
{
int a = 5, b = 10;
a = a + b;
b = a - b;
a = a - b;
return 0;
}
Output:
Before swapping.
a = 5, b = 10
After swapping.
a = 10, b = 5
#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.
int main() {
int n;
if ( n % 2 == 0)
cout << n << " is even.";
else
cout << n << " is odd.";
return 0;
}
Output:
#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.
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.
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;
(n % 2 == 0) ? cout << n << " is even." : cout << n << " is odd.";
return 0;
}
Output:
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.
#include <iostream>
using namespace std;
int main() {
return 0;
}
Output:
Include the iostream library and use the "using namespace std;" directive to allow for using
the standard input and output functions.
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() {
return 0;
}
Output:
#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() {
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:
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.
int main() {
int n, sum = 0;
Output:
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.
#include <iostream>
using namespace std;
int main() {
int year;
cout << "Enter a year: ";
cin >> year;
return 0;
}
Output:
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".
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;
}
Output:
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".
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;
}
Output:
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.
int main() {
int n, range;
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
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".
int main() {
int n, t1 = 0, t2 = 1, nextTerm = 0;
Output:
#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.
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;
nextTerm = t1 + t2;
while(nextTerm <= n) {
cout << nextTerm << ", ";
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
Output:
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.
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.
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.
int main() {
int n1, n2, hcf;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
return 0;
}
Output:
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.
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;
while(n1 != n2) {
if(n1 > n2)
n1 -= n2;
else
n2 -= n1;
}
return 0;
}
Output:
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.
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;
do
{
if (max % n1 == 0 && max % n2 == 0)
{
cout << "LCM = " << max;
break;
}
else
++max;
} while (true);
return 0;
}
Output:
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.
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.
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.