# Loops 1

Hello coders : )

We have completed the concepts and practice problems upon if...else statements and if...else ladder. I hope you had fun doing them! Now it's time to have some practice upon our next topic of Control Flow: **Loops. **

Prerequisite:Read the 'while loop' , 'for loop' articles in the control flow module. Also solve the problems given in the 'standard problems' article of the same module.

Loops, as the name suggests might make you feel stuck sometimes. A few **suggestions** before moving to the problems would be:

- Decode the start and end i.e. the range of loops carefully so that you don't end up getting stuck in an endless loop.
- Update loop control variables within the loop body to ensure the loop will eventually terminate.
**Dry Run the Code:**Take a pen and paper if you want but always dry run the code, while writing the solution as it helps you to relate the code with actual examples. This suggestion is a universal one for all programming problems : )

Ready now? Let's move to our problems then 🚀

## Problem 1

Write a C++ program to input a number and find the sum of first and last digit of the number using a for loop.

### Input

`num = 12345`

### Output

`Sum of first and last digit = 6`

#### Intuition

In the given problem, our major task is to find the first and last digit of the given number: `num`

. If you have solved the 'standard problems' article given in 'Control Flow Module' then you might have decoded the way to do it. If not, then do read 'Problem 3' of that article to understand this problem better : )

Now let's solve:

We know that the last digit of any integer is the remainder that we get after dividing the number by 10. Hence,**To find the last digit:**`num`

% 10 value is nothing but the last digit of the given number. Store this value in a variable say`last_digit`

.Our human eyes are great as they can identify any digit directly but mathematically, it's a bit complex. We already know how to remove last digit of a number: by dividing the number by 10. So if we keep doing this again and again until a single digit is left, then won't that digit be our first digit??**To find the first digit:**

Wait, did I say 'keep doing this again and again' ?? Are we talking about loops? YES! But how to apply them here?

We'll keep dividing the `num`

by 10 until a single digit is left. In other words, "while ( `num`

>= 10 ): do ( `num`

/ 10 )"

And after the loop ends, the `num`

that we got is our first digit. Store it in a variable say `first_digit`

. Now simply add the `first_digit`

and `last_digit`

and print it as the output.

#### Logic

- Input a number from user. Store it in some variable say
`num`

. - To find last digit of a given number we modulo divide the given number by 10. Which is
`last_digit = num % 10`

. - To find first digit we divide the given number by 10 till num is greater than 0.
- Finally, calculate sum of first and last digit i.e.
`sum = first_digit + last_digit`

.

## Solution

```
#include <iostream>
using namespace std;
int main() {
int num, sum = 0, first_digit, last_digit;
/* Input a number from the user */
cout << "Enter any number to find the sum of the first and last digit: ";
cin >> num;
/* Find last digit to sum */
last_digit = num % 10;
/* Copy num to the first digit: first_digit is num itself after continuously
divided by 10 until and unless a single digit is left. Hence, we initialise
first_digit with num itself. */
first_digit = num;
/* Find the first digit by dividing num by 10 until the first digit is left */
while (num >= 10) {
num = num / 10;
}
first_digit = num;
/* Find the sum of the first and last digit */
sum = first_digit + last_digit;
cout << "Sum of the first and last digit = " << sum << endl;
return 0;
}
```

## Problem 2

Write a C++ program to input a number from the user and calculate product of its digits.

### Input

`num = 1234`

### Output

`Product of digits: 24`

#### Intuition

Before we move to the current problem, it's recommended to read 'Problem 3' of 'Standard Problems' article in the 'Control Flow' Module. I hope you already did that 🥺.

Now in the given problem, we need to find the product of the digits. So let's initialise a variable `product`

that will keep multiplying our digits one by one and return it as the output in the end. Can you guess the initial value of `product`

? It would be 1 as any number multiplied by 1 is the number itself. Try to relate it with the fact that we initialise a sum variable with 0. Multiplying a number with 1 returns same, so as summation with 0 returns same. Hence, I have initialized product with 1.

Be sure to initialize the `product`

with 0 if num is 0 because if num = 0 then output (product of digits) should be 0. Also initialise `product`

as a ** long long data type** because multiplying so many numbers might generate a very large value beyond the range of an integer data type. 'int' data type will only work for small products.

Now coming to our main problem. How to calculate this `product`

?

Just like our 'Reverse number' and the last problem, we'll keep extracting digits one by one from the end of the number and keep multiplying it to the `product`

. We'll repeat this process until our given number `num`

becomes 0.

#### Logic

- Input a number from user. Store it in some variable say num.
- Initialize another variable to store product i.e.
`product = 1`

. - Find last digit of number by performing modulo division by 10 i.e.
`lastDigit = num % 10`

. - Multiply last digit found above with product i.e.
`product = product * lastDigit`

. - Remove last digit by dividing the number by 10 i.e.
`num = num / 10`

. - Repeat step 3-5 till number becomes 0. Finally you will be left with product of digits in product variable.

## Solution

```
#include <iostream>
using namespace std;
int main() {
int num;
/*Initialize product as long long data type*/
long long product = 1ll;
/* Input number from the user */
cout << "Enter any number to calculate the product of digits: "<<endl;
cin >> num;
product = (num == 0 ? 0 : 1ll);
/* Repeat the steps until num becomes 0 */
while (num != 0) {
/* Get the last digit from num and multiply it to product */
product = product * (num % 10);
/* Remove the last digit from num */
num = num / 10;
}
cout << "Product of digits = " << product << endl;
return 0;
}
```

## Problem 3

Write a C++ program to input number from user and check number is palindrome or not using loop.

### Input

`num = 121`

### Output

`121 is palindrome`

#### Hint

Wikipedia says: "A ** palindromic number** is a number (such as 16461) that remains the same when its digits are reversed."

#### Hint 2

We just need to check if reverse of the given number `num`

is equal to `num`

or not!? And we know how to find reverse of a number right??

#### Logic

- Input a number from user. Store it in some variable say num.
- Find reverse of the given number. Store it in some variable say reverse.
- Compare num with reverse. If both are same then the number is palindrome otherwise not.

## Solution

```
#include <iostream>
using namespace std;
int main() {
int n, num, rev = 0;
/* Input a number from the user */
cout << "Enter any number to check palindrome: "<<endl;
cin >> n;
/* Copy the original value to 'num' */
num = n;
/* Find the reverse of n and store it in rev */
while (n != 0) {
rev = (rev * 10) + (n % 10);
n /= 10;
}
/* Check if the reverse is equal to 'num' or not */
if (rev == num) {
cout << num << " is a palindrome." << endl;
} else {
cout << num << " is not a palindrome." << endl;
}
return 0;
}
```

## Problem 4

Write a C++ program to find power of a number using for loop.

### Input

```
base = 2
exponent = 5
```

### Output

`2 ^ 5 = 32`

#### Intuition

Create a variable `power`

that will store the final output. Now how is a number's power calculated? The simplest way is to multiply `base`

(2) `exponent`

(5) no. of times. Similarly, we'll keep multiplying `power`

with the `base`

for `exponent`

no. of times. As read in the second problem, we'll initialize `product`

with 1 (multiplicative identity).

Now, how to perform the multiplication operation for `exponent`

no. of times? We'll run a loop from 1 to `exponent`

and keep multiplying `power`

with `base`

. At the end, we'll simply print `power`

as the output.

#### Logic

- Input base and exponents from user. Store it in two variables say base and expo.
- Declare and initialize another variable to store power say
`power = 1`

. - Run a loop from 1 to expo, increment loop counter by 1 in each iteration. The loop structure must look similar to
`for(i=1; i<=expo; i++)`

. - For each iteration inside loop multiply power with num i.e.
`power = power * base`

. - Finally after loop you are left with power in power variable.

## Solution

```
#include <iostream>
using namespace std;
int main() {
int base, exponent;
long long power = 1;
int i;
/* Input base and exponent from the user */
cout << "Enter base: "<<endl;
cin >> base;
cout << "Enter exponent: "<<endl;
cin >> exponent;
/* Multiply base, exponent times */
for (i = 1; i <= exponent; i++) {
power = power * base;
}
cout << base << " ^ " << exponent << " = " << power;
return 0;
}
```

## Problem 5

Write a C++ program to print Fibonacci series up to n terms using loop.

### Input

`N = 10`

### Output

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

#### What is Fibonacci Series?

Fibonacci series is a series of numbers where the current number is the sum of previous two terms. For Example: 0, 1, 1, 2, 3, 5, 8, 13, 21, … , (n-1th + n-2th).

#### Intuition

Let's start from the basic definition: Fibonacci terms are numbers where each term is the sum of the two preceding ones. For example: The 3rd term is the sum of 1st + 2nd. 4th is sum of 3rd + 2nd, 5th is sum of 4th + 3rd and so on. This means that we always need to keep track of last 2 terms. So lets create 2 variables: `a`

as 1st term with value 0 and `b`

as 2nd term with value 1.

Now we will print the remaining n-2 terms using loop. Since we need to calculate and print till N elements, we'll run a loop from 1 to N. Inside this loop:

- First print the current element of the sequence. Let this current element be
`c`

. - Now before we run the loop again for next iteration, we need to update the previous 2 no.s right? Let's do that.
`a = b`

: Update`a`

to the value of the second number`b`

.`b = c`

: Update`b`

to the value of the calculated number`c`

.- Update
`c`

to the sum of previous 2 elements:`a`

and`b`

to get the subsequent element.

There's one more part left: With what will we initialize c? Since c is the no. that we are printing, we'll initialize it with the first element of Fibonacci series, i.e. 0.

#### Logic

- Input number of Fibonacci terms to print from user. Store it in a variable say terms.
- Declare and initialize three variables.
`a=0`

,`b=1`

and`c=0`

.Here c is the current term, b is the n-1^{th}term and a is n-2^{th}term. - Run a loop from 1 to terms, increment loop counter by 1. The loop structure should look like
`for(i=1; i<=term; i++)`

. It will iterate through n terms - Inside the loop copy the value of n-1
^{th}term to n-2^{th}term i.e.`a = b`

.Next, copy the value of n^{th}to n-1^{th}term`b = c`

. Finally, compute the new term by adding previous two terms i.e.`c = a + b`

. - Print the value of current Fibonacci term i.e. c.

## Solution

```
#include <iostream>
using namespace std;
int main() {
int a, b, c, i, terms;
/* Input number from user */
cout << "Enter number of terms: "<<endl;
cin >> terms;
/* Fibonacci initialization */
a = 0;
b = 1;
c = 0;
cout << "Fibonacci terms: " << endl;
/* Iterate through n terms */
for (i = 1; i <= terms; i++) {
cout << c << ", ";
a = b; // Copy n-1 to n-2
b = c; // Copy current to n-1
c = a + b; // New term
}
return 0;
}
```

With this we end our first practice article on loops. Not enough yet? Then do proceed to the upcoming articles : )