Back-End Programming Exam  >  Back-End Programming Notes  >  Learn to Program with C++: Beginner to Expert  >  Programming Examples - Decisions and Loops

Programming Examples - Decisions and Loops | Learn to Program with C++: Beginner to Expert - Back-End Programming PDF Download

Example 1: 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.
Integers which are perfectly divisible by 2 are called even numbers.
And those integers which are not perfectly divisible by 2 are not known as odd number.
To check whether an integer is even or odd, the remainder is calculated when it is divided by 2 using modulus operator %. If remainder is zero, that integer is even if not that integer is odd.

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

Output
Enter an integer: 23
23 is odd.

In this program, if..else statement is used to check whether n%2 == 0 is true or not. If this expression is true, n is even if not n is odd.
You can also use ternary operators ?: instead of if..else statement. Ternary operator is short hand notation of if...else statement.

Program 2: 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;
}


Example 2: 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.
Five alphabets a, e, i, o and u are known as vowels. All other alphabets except these 5 alphabets are known are consonants.
This program assumes that the user will always enter an alphabet.

Program: Check Vowel or a Consonant Manually
include <iostream>
using namespace std;
int main()
{
    char c;
    int 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');
    // evaluates to 1 (true) if either isLowercaseVowel or isUppercaseVowel is true
    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.

Example 3: 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.
In this program, 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 proper message.
This program can be used in more than one way.

Program 1: Find Largest Number Using if Statement

#include <iostream>
using namespace std;
int main()
{    
   float n1, n2, n3;
   cout << "Enter three numbers: ";
   cin >> n1 >> n2 >> n3;
   if(n1 >= n2 && n1 >= n3)
   {
       cout << "Largest number: " << n1;
    }
    if(n2 >= n1 && n2 >= n3)
    {
       cout << "Largest number: " << n2;
    }
    if(n3 >= n1 && n3 >= n2) {
       cout << "Largest number: " << n3;
    }
    return 0;
}

Output
Enter three numbers: 2.3
8.3
-4.2

Largest number: 8.3

Program 2: Find Largest Number Using if...else Statement

#include <iostream>
using namespace std;
int main()
{
    float n1, n2, n3;
    cout << "Enter three numbers: ";
    cin >> n1 >> n2 >> n3;
    if((n1 >= n2) && (n1 >= n3))
        cout << "Largest number: " << n1;
    else if ((n2 >= n1) && (n2 >= n3))
        cout << "Largest number: " << n2;
    else
        cout << "Largest number: " << n3;
    return 0;
}

Output
Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3

Program 3: Find Largest Number Using Nested if...else statement

#include <iostream>
using namespace std;
int main()
{
    float n1, n2, n3;
    cout << "Enter three numbers: ";
    cin >> n1 >> n2 >> n3;
    if (n1 >= n2)
    {
        if (n1 >= n3)
            cout << "Largest number: " << n1;
        else
            cout << "Largest number: " << n3;
    }
    else
    {
        if (n2 >= n3)
            cout << "Largest number: " << n2;
        else
            cout << "Largest number: " << n3;
    }
    return 0;
}
Output
Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3

Example 4: 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).
For a quadratic equation ax2+bx+c = 0 (where a, b and c are coefficients), it's roots is given by following the formula.
Programming Examples - Decisions and Loops | Learn to Program with C++: Beginner to Expert - Back-End  Programming
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

Programming Examples - Decisions and Loops | Learn to Program with C++: Beginner to Expert - Back-End  Programming
Programming Examples - Decisions and Loops | Learn to Program with C++: Beginner to Expert - Back-End  Programming
Programming Examples - Decisions and Loops | Learn to Program with C++: Beginner to Expert - Back-End  Programming
Program 1: 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 + sqrt(discriminant)) / (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.

Example 5: C++ Program to Calculate Sum of Natural Numbers
In this example, you'll learn to calculate the sum of natural numbers.
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.
Program: 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.

Example 6: C++ Program to Check Leap Year
This program checks whether an year (integer) entered by the user is a leap year or not.
All years which are perfectly divisible by 4 are leap years except for century years (years ending with 00) which is leap year only it is perfectly divisible by 400.
For example: 2012, 2004, 1968 etc are leap year but, 1971, 2006 etc are not leap year. Similarly, 1200, 1600, 2000, 2400 are leap years but, 1700, 1800, 1900 etc are not.
In this program below, user is asked to enter a year and this program checks whether the year entered by user is leap year or not.

Program: Check if a year is leap year or not

#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: 2014
2014 is not a leap year.


Example 7: 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.
For any positive number n, it's factorial is given by:
factorial = 1*2*3...*n
Factorial of negative number cannot be found and factorial of 0 is 1.
In this program below, user is asked to enter a positive integer. Then the factorial of that number is computed and displayed in the screen.

Program: Find Factorial of a given number

#include <iostream>
using namespace std;
int main()
{
    unsigned int n;
    unsigned long long factorial = 1;
    cout << "Enter a positive integer: ";
    cin >> n;
    for(int i = 1; i <=n; ++i)
    {
        factorial *= i;
    }
    cout << "Factorial of " << n << " = " << factorial;    
    return 0;
}

Output
Enter a positive integer: 12
Factorial of 12 = 479001600

Here variable factorial is of type unsigned long long.
It is because factorial of a number is always positive, that's why unsigned qualifier is added to it.
Since the factorial a number can be large, it is defined as long long.

Example 8: C++ Program to Generate Multiplication Table
Example to generate the multiplication table of a number (entered by the user) using for loop.

Program 1: Display Multiplication table up to 10

#include <iostream>
using namespace std;
int main()
{
    int n;
    cout << "Enter a positive integer: ";
    cin >> n;
    for (int i = 1; i <= 10; ++i) {
        cout << n << " * " << i << " = " << n * i << endl;
    }
       return 0;
}

Output
Enter an 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.
The program below is the modification of above program in which the user is also asked to entered the range up to which multiplication table should be displayed.

Program 2: 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: 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


Example 9: 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).
The Fibonacci sequence is a series where the next term is the sum of pervious 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

Program 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, 

Program 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


Example 10: 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.
The largest integer which can perfectly divide two integers is known as GCD or HCF of those two numbers.

Program 1: Find GCD 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: 78
52
HCF = 26

In above program, smaller number is subtracted from larger number and that number is stored in place of larger number.
This process is continued until, two numbers become equal which will be HCF.

Program 2: 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;
}

The logic of this program is simple.
In this program, small integer between n1 and n2 is stored in n2. Then the loop is iterated from i = 1 to i <= n2 and in each iteration, value of i is increased by 1.
If both numbers are divisible by then, that number is stored in variable hcf.
When the iteration is finished, HCF will be stored in variable hcf.

Example 11: 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.
LCM of two integers a and b is the smallest positive integer that is divisible by both a and b.

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

Program 2: Find LCM using HCF
The LCM of two numbers is given by:
LCM = (n1 * n2) / HCF

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


Example 12: 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.

Program: C++ Program to Reverse an Integer

#include <iostream>
using namespace std;
int main()
{
    int n, reversedNumber = 0, remainder;
    cout << "Enter an integer: ";
    cin >> n;
    while(n != 0)
    {
        remainder = n;
        reversedNumber = reversedNumber*10 + remainder;
        n /= 10;
    }
    cout << "Reversed Number = " << reversedNumber;
    return 0;
}

Output
Enter an integer: 12345
Reversed number = 54321

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, reversedNumber is computed and the value of n is decreased 10 fold.
Finally, the reversedNumber (which contains the reversed number) is printed on the screen.

Example 13: C++ Program to Calculate Power of a Number
In this article, you will learn to compute power to a number manually, and by using pow() function.
This program takes two numbers from the user (a base number and an exponent) and calculates the power.
Power of a number = baseexponent
Program 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

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

The document Programming Examples - Decisions and Loops | Learn to Program with C++: Beginner to Expert - Back-End Programming is a part of the Back-End Programming Course Learn to Program with C++: Beginner to Expert.
All you need of Back-End Programming at this link: Back-End Programming
73 videos|7 docs|23 tests

FAQs on Programming Examples - Decisions and Loops - Learn to Program with C++: Beginner to Expert - Back-End Programming

1. What is the difference between decisions and loops in back-end programming?
Ans. In back-end programming, decisions and loops are both essential constructs for controlling the flow of execution. - Decisions allow the program to make choices based on certain conditions. They use conditional statements, such as if-else or switch-case, to determine which block of code to execute. Decisions help in implementing logic and handling different scenarios based on the input or state of the program. - Loops, on the other hand, help in executing a block of code repeatedly until a certain condition is met. They are used when we need to perform the same set of instructions multiple times. Common types of loops include for loop, while loop, and do-while loop. Decisions and loops serve different purposes but often work together to create more complex program logic.
2. How can I use an if-else statement to make decisions in back-end programming?
Ans. The if-else statement is a commonly used decision-making construct in back-end programming. It allows the program to perform different actions based on a condition. Here's the syntax of an if-else statement: ``` if (condition) { // code to be executed if the condition is true } else { // code to be executed if the condition is false } ``` The condition is an expression that evaluates to either true or false. If the condition is true, the code inside the if block is executed. If the condition is false, the code inside the else block (if present) is executed. The if-else statement can also be nested inside other if-else statements to handle multiple conditions or scenarios.
3. How can I use a for loop to repeat code execution in back-end programming?
Ans. A for loop is a looping construct used to execute a block of code repeatedly for a specific number of times. It is often used when the number of iterations is known in advance. Here's the syntax of a for loop: ``` for (initialization; condition; increment/decrement) { // code to be executed in each iteration } ``` The initialization step is executed once before the loop starts and is used to initialize the loop variable. The condition is evaluated before each iteration, and if it is true, the loop continues. The increment/decrement step is executed after each iteration and is used to update the loop variable. For example, the following for loop prints the numbers from 1 to 5: ``` for (int i = 1; i <= 5; i++) { System.out.println(i); } ``` The loop variable `i` is initialized to 1, and the loop continues as long as `i` is less than or equal to 5. In each iteration, `i` is incremented by 1, and the current value of `i` is printed.
4. What is the difference between a while loop and a do-while loop in back-end programming?
Ans. Both while and do-while loops are used for repetitive execution of code in back-end programming, but they have some differences in their behavior. - In a while loop, the condition is checked at the beginning of each iteration. If the condition is true, the code inside the loop is executed. If the condition is false initially, the code inside the loop is never executed. - In a do-while loop, the condition is checked at the end of each iteration. This means that the code inside the loop is executed at least once, even if the condition is false. Here's the syntax of a while loop: ``` while (condition) { // code to be executed in each iteration } ``` And here's the syntax of a do-while loop: ``` do { // code to be executed in each iteration } while (condition); ``` The choice between while and do-while depends on the specific requirements of the program. If the code inside the loop must be executed at least once, a do-while loop is appropriate. If the code inside the loop may not need to be executed at all, a while loop can be used.
5. How can I handle multiple conditions using switch-case in back-end programming?
Ans. The switch-case statement is used to handle multiple conditions or scenarios in back-end programming. It provides an alternative to using multiple if-else statements when dealing with a fixed set of values. Here's the syntax of a switch-case statement: ``` switch (expression) { case value1: // code to be executed if expression matches value1 break; case value2: // code to be executed if expression matches value2 break; // more cases... default: // code to be executed if expression doesn't match any case } ``` The expression is evaluated, and its value is compared with the values specified in the case statements. If a match is found, the code block corresponding to that case is executed. The `break` statement is used to exit the switch statement after executing the corresponding code block. If the expression doesn't match any case, the code block inside the `default` case (if present) is executed. Switch-case statements are particularly useful when dealing with multiple options or menu-like scenarios where different actions need to be taken based on the input value.
73 videos|7 docs|23 tests
Download as PDF
Explore Courses for Back-End Programming exam
Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

pdf

,

Exam

,

video lectures

,

study material

,

Semester Notes

,

Extra Questions

,

ppt

,

shortcuts and tricks

,

Programming Examples - Decisions and Loops | Learn to Program with C++: Beginner to Expert - Back-End Programming

,

Sample Paper

,

MCQs

,

Objective type Questions

,

mock tests for examination

,

Programming Examples - Decisions and Loops | Learn to Program with C++: Beginner to Expert - Back-End Programming

,

Programming Examples - Decisions and Loops | Learn to Program with C++: Beginner to Expert - Back-End Programming

,

Previous Year Questions with Solutions

,

practice quizzes

,

Summary

,

Free

,

past year papers

,

Viva Questions

,

Important questions

;