Loops Practice 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:
- To find the last digit: We know that the last digit of any integer is the remainder that we get after dividing the number by 10. Hence,
num
% 10 value is nothing but the last digit of the given number. Store this value in a variable saylast_digit
. - To find the first 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??
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
C++ Code
#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;
}
Java Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Declare variables
int num, sum = 0, firstDigit, lastDigit;
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
num = scanner.nextInt();
// Find last digit by taking modulo 10 of the number
lastDigit = num % 10;
// Copy num to firstDigit: Initially set firstDigit to num.
// The firstDigit will be found after repeatedly dividing num by 10
// until only a single digit remains.
firstDigit = num;
// Loop to find the first digit by continuously dividing num by 10
// until only the leftmost digit (first digit) remains
while (num >= 10) {
num = num / 10;
}
firstDigit = num; // Now num holds the first digit
// Calculate the sum of the first and last digit
sum = firstDigit + lastDigit;
// Display the result
System.out.println("Sum of the first and last digit = " + sum);
// Close the scanner object
scanner.close();
}
}
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
C++ Code
#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;
}
Java Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Declare variable for input number
int num;
// Initialize product as a long data type to handle large products
long product = 1L;
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
num = scanner.nextInt();
// Set product to 0 if the number is 0, otherwise initialize to 1
product = (num == 0 ? 0 : 1L);
// Loop to process each digit of the number
while (num != 0) {
// Multiply product by the last digit of num (using modulo 10)
product *= num % 10;
// Remove the last digit from num by dividing it by 10
num /= 10;
}
// Output the result
System.out.println("Product of digits = " + product);
// Close the scanner
scanner.close();
}
}
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
C++ Code
#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;
}
Java Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Declare variables for the original number, a copy of the number, and its reverse
int n, num, rev = 0;
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Input a number from the user
n = scanner.nextInt();
// Copy the original number to 'num' for comparison later
num = n;
// Find the reverse of the number and store it in 'rev'
while (n != 0) {
// Extract the last digit of 'n' and add it to the reverse (multiplied by 10)
rev = (rev * 10) + (n % 10);
// Remove the last digit from 'n'
n /= 10;
}
// Check if the reverse of the number is equal to the original number
if (rev == num) {
System.out.println(num + " is a palindrome.");
} else {
System.out.println(num + " is not a palindrome.");
}
// Close the scanner to free resources
scanner.close();
}
}
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
C++ Code
#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;
}
Java Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Declare variables for base, exponent, and power
int base, exponent;
long power = 1;
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Input base and exponent from the user
// System.out.println("Enter base:");
base = scanner.nextInt();
// System.out.println("Enter exponent:");
exponent = scanner.nextInt();
// Multiply base by itself exponent times
for (int i = 1; i <= exponent; i++) {
power *= base;
}
// Display the result
System.out.println(base + " ^ " + exponent + " = " + power);
// Close the scanner to free up resources
scanner.close();
}
}
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
: Updatea
to the value of the second numberb
.b = c
: Updateb
to the value of the calculated numberc
.- Update
c
to the sum of previous 2 elements:a
andb
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
andc=0
.Here c is the current term, b is the n-1th term and a is n-2th 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-1th term to n-2th term i.e.
a = b
.Next, copy the value of nth to n-1th termb = 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
C++ Code
#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;
}
Java Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Declare variables to store Fibonacci terms and loop counter
int a, b, c, i, terms;
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Input the number of terms from the user
// System.out.println("Enter number of terms:");
terms = scanner.nextInt();
// Initialize the first two terms of the Fibonacci sequence
a = 0;
b = 1;
c = 0;
System.out.print("Fibonacci terms: ");
// Loop through the specified number of terms
for (i = 1; i <= terms; i++) {
// Print the current term
System.out.print(c + " ");
// Update terms for the next iteration:
// - Move b to a (previous term)
// - Move c to b (current term)
// - Calculate the new term as the sum of a and b
a = b; // Set the (n-1) term as the (n-2) term
b = c; // Set the current term as the (n-1) term
c = a + b; // Calculate the next term
}
// Close the scanner to free up resources
scanner.close();
}
}
With this we end our first practice article on loops. Not enough yet? Then do proceed to the upcoming articles : )