Skip to main content

Control Flow

Standard Problems

Till now we learnt many important concepts not only of control flow but of C++ programming as a whole. We did a lot of examples while learning them but now it's time to get our hands on the standard problems.

Don't worry they are nothing complex but just some more cool problems on Control Flow πŸ˜‰

Tip: Try solving problems on your own first. It might be very confusing and mind-boggling initially but don't move to the solutions without giving it a shot yourself. You can be wrong but you'll be better : )

Now let's move to the problems πŸš€

Problem 1

Write a C++ program to print alphabets from a to z using for loop.

Output

a b c d e f g h i j k l m n o p q r s t u v w x y z

You have printed numbers in a given range and so this might look like a basic problem to you, but there's just addition of 'ASCII' values when printing such alphabets. Do you know about ASCII values and their use? If not, then give it a read below.

ASCII Values

Every character, like alphabets (a,b,c...), digits (1,2,3...), or special symbols (@,%,&), has a unique number assigned to it, called the ASCII value. When you input a character, we can figure out if it's a letter, number, or special character based on its ASCII value. For our programming use, we only need to know the ASCII values of alphabets (lowercase & uppercase) and digits.

Here are the ranges:

For big letters (A to Z): ASCII values are between 65 and 90.
For small letters (a to z): ASCII values are between 97 and 122.
For numbers (0 to 9): ASCII values are between 48 and 57.

Therefore, you can treat characters in C++ as integers and can perform all basic arithmetic operations on characters.

Logic

  1. Declare a character variable, say ch.
  2. Initialize loop counter variable from ch = 'a', that goes till ch <= 'z', increment the loop by 1 in each iteration. The loop structure should look like for(ch='a'; ch<='z'; ch++).
  3. Inside the loop body print the value of ch.

NOTE: ASCII values play a crucial role in controlling the loop and determining when it should terminate. So, the loop starts with ch having the ASCII value of 'a' (97), and it continues to iterate as long as ch is less than or equal to the ASCII value of 'z' (122). This ensures that the loop runs through all lowercase letters from 'a' to 'z'.

Try it yourself

Solution
#include <iostream>
using namespace std;

int main() {
    char ch;

    cout << "Alphabets from a - z are: " << " ";
    for (ch = 'a'; ch <= 'z'; ch++) {
        cout << ch << endl;
    }

    return 0;
}

P.S. If you want to see the entire ASCII chart, here is it for your reference. Don't try to memorize it ; p


Problem 2

Sum of Even and Odd Numbers

Write a C++ program to calculate the sum of all even and odd numbers from 1 to N separately.

Input

N = 7

Output

Sum of even numbers from 1 to 7 is: 12
Sum of odd numbers from 1 to 7 is: 16

Intuition

This question might seem like a complex one but is just a combination of multiple basic concepts. Let's break it down and see what all do we have to solve:

  1. Check if N is a valid natural number
  2. Check for even numbers between 1 to N
  3. Check for odd numbers between 1 to N
  4. We need to add them up

Part 1: We'll proceed with the loops but what if user is mischievous and enters some negative number XD. Don't worry, we coders got it πŸ’ͺ. What we can do is add an if condition that checks if N<=0. If true then we'll ask the user to provide a positive number as input and return.

Part 2 & 3: How to get even numbers? We'll check a numbers divisibility with 2 and if remainder is 0 then it's even else odd. This checked by using modulo operator.
Example to check a number x: 'if(x % 2 == 0) then x is even; else x is odd'.

Part 4: Now comes the loop. We can check for odd and even numbers individually but how to check all from 1 to N & add them all together. We'll run a loop on variable 'number' from 1 to N as given in the problem and perform the odd even check on each 'number' as said before.

We'll create 2 separate variables sum_even and sum_odd in which we'll keep adding the even and odd no.s respectively.

Can you guess the initial values of sum_even and sum_odd? It would be 0 so that we could add the required numbers easily as 0 added to any number is the number itself!

Logic

  1. Check if user's input is a positive no. using an if statement. If(N <= 0) then return from the program
  2. Initialize three variables: sum_even to store the sum of even numbers, sum_odd to store the sum of odd numbers, and number to keep track of the current number being processed.
  3. Use a while loop that runs until the value of number reaches 'N'.
  4. Check if the current number is even by using the modulo operator (%). If it's even, add it to sum_even. If the current number is odd, add it to sum_odd.
  5. Increment the value of number for the next iteration.
  6. After the loop completes, display the calculated sums of even and odd numbers up to 'N'.

Try it yourself

Solution
#include <iostream>
using namespace std;

int main() {
    int N;
    int sum_even = 0;
    int sum_odd = 0;
    int number = 1;

    cout << "Enter a positive integer 'N': "<<endl;
    cin >> N;

    if (N <= 0) {
        cout << "Please enter a positive integer." << endl;
        return 1; // Exit with an error code
    }

    while (number <= N) {
        if (number % 2 == 0) {
            // It's an even number
            sum_even += number;
        } else {
            // It's an odd number
            sum_odd += number;
        }
        number++;
    }

    cout << "Sum of even numbers from 1 to " << N << " is: " << sum_even << endl;
    cout << "Sum of odd numbers from 1 to " << N << " is: " << sum_odd << endl;

    return 0;
}
πŸ’‘
Note: Here we could also use a for loop ranging on i from 1 to N. In that case, number would be equivalent to i. This can be done in many problems including the previous one as well. It's upto you that which loop do you want to use : )

Try it yourself

Solution using for loop
#include <iostream>
using namespace std;

int main() {
    int N;
    int sum_even = 0;
    int sum_odd = 0;

    cout << "Enter a positive integer 'N': "<<endl;
    cin >> N;

    if (N <= 0) {
        cout << "Please enter a positive integer." << endl;
        return 1; // Exit with an error code
    }

    for (int i = 1; i <= N; i++) {
        if (i % 2 == 0) {
            // It's an even number
            sum_even += i;
        } else {
            // It's an odd number
            sum_odd += i;
        }
    }

    cout << "Sum of even numbers from 1 to " << N << " is: " << sum_even << endl;
    cout << "Sum of odd numbers from 1 to " << N << " is: " << sum_odd << endl;

    return 0;
}

Problem 3

Reverse Number

Write a C++ program to reverse a given number

Input

num = 7834

Output

4387

Intuition

Feeling confused? Well, let's start from the basic. Create a variable rev that will store the reverse of the given number of the final output. Now if I had to do this manually, I'd keep removing a digit from the end and keep adding it to my rev. So now let's figure out how can we extract our last digitπŸ€”

Going back to our basic maths, last digit is just the remainder that we get when we divide a no. by 10. Now how to get this remainder in using C++? Remember modulo operator? Modulo operator is used for the very same purpose i.e. to give the remainder's value.
Hence, we now know that num%10 will give us last digit.

But how to add that as a digit to rev? Let's understand with example: Suppose we want to add digit 7 to a number x = 658 to achieve output as 6587. To achieve this, I'll multiply x by 10 = 6580 and then add 7 = 6587. This process can be repeated as many times as I want to add a last digit. Wait! What I said? Process can be repeated multiple times? Is it a loop? YES!

First things first, to add a digit to rev, I'll multiply revwith 10 and then add last digit of num i.e. num%10. Hence revbecomes (rev* 10 + num%10).

Now coming back to our great discovery of loops XD, we'll do this procedure of removing and adding last digit of num to revuntil our num gets exhausted and all our digits are added to rev. Basically, while(nums>0), keep doing this process right? Hence we'll use a while loop!

Wait, something's missing! How will our num get exhausted? We are adding the last digit to rev, but we need to remove it too! To remove the last digit of num, we'll simply divide it by 10. Try doing this with any number say 274. 274/10 as an integer is 27. This is nothing but 274 without its last digit.

Now we are good to proceed to the step-by-step descriptive code logic for this solution : )

Logic

  1. Input a number from user to find reverse. Store it in some variable say num.
  2. Declare and initialize another variable to store reverse of num, say rev = 0.
  3. Extract last digit of the given number by performing modulo division. Store the last digit to some variable say lastDigit = num % 10.
  4. Increase the place value of rev by one. To increase place value multiply rev variable by 10 i.e. rev= rev* 10.
  5. Add lastDigit to revi.e. rev= rev+ lastDigit.
  6. Since last digit of num is processed hence, remove last digit of num. To remove last digit divide num by 10 i.e. num = num / 10.
  7. Repeat step 3 to 6 till num is not equal to (or greater than) zero.

Try it yourself

Solution
#include <iostream>
using namespace std;

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

    /* Input a number from the user */
    cout << "Enter any number to find reverse: "<<endl;
    cin >> num;

    /* Repeat the process until 'num' becomes 0 */
    while (num != 0) {
        /* Increase the place value of rev and add the last digit to rev */
        rev = (rev * 10) + (num % 10);

        /* Remove the last digit from 'num' */
        num /= 10;
    }

    /* Print the reversed number */
    cout << "Reverse = " << rev;

    return 0;
}

Problem 4

Input

num = 5

Output

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

Intuition

Let's start with a very basic question. How to write a multiplication table of a given number say num. We go from 1 to 10 and keep multiplying num with it. You got your solution!

We'll run a loop on i from 1 to 10, multiply our num with i and keep printing it.

Logic

  1. Input a number from the user to generate a multiplication table. Store it in some variable say num.
  2. To print a multiplication table we need to iterate from 1 to 10. Run a loop from 1 to 10, increment 1 on each iteration. The loop structure should look like for(i = 1; i<=10; i++).
  3. Inside loop generate multiplication table using num * i and print in the specified format.

Try it yourself

Solution
#include <iostream>
using namespace std;

int main() {
    int i, num;

    /* Input a number to print the table */
    cout << "Enter the number to print the table: "<<endl;
    cin >> num;

    for (i = 1; i <= 10; i++) {
        cout << num << " * " << i << " = " << (num * i) << endl;
    }

    return 0;
}

I hope you got some idea about control flow problems and how studied concepts are practically applied to solve these problems. But these aren't all! Do checkout the 'Control Flow: Practice' module to get an intense practice of many more problems : )