LOOPS - EXAMPLES (C, C++, JAVA)
Introduction to Loops in Programming
Loops are a fundamental concept in programming that allow you to execute a block of code repeatedly based on a specific condition. They are crucial for handling repetitive tasks, such as iterating over arrays or processing input data. This guide explores the basic types of loops—for, while, and do-while—and explains when to use each type effectively. Additionally, it covers special cases like infinite loops, offering insight into best practices and edge cases in loop usage.
On this page you will find basic examples from loops. Often, programming requires one or more commands to be repeated multiple times. Now imagine that we need to print certain orders 100, 1000 or 10000 times. It would be a difficult, almost impossible task. The job would be easier if these commands, which we want to repeat, were written only once, and repeated with another command. Before proceeding with the examples, read the lesson on loops in the C++ programming language on the web page
Loops in the C/C++ programming language
Loops in the C/C++ programming language
or, if you work in the JAVA programming language:
Loops in JAVA
Loops in JAVA
When to use different types of loops
- For loop: Best used when you know in advance how many times you want to repeat a block of code. For example, to iterate through a known number of elements in an array or list.
- While loop: Used when the number of iterations is not known, but depends on a condition that can be changed inside the loop. It is ideal for situations when you work with uncertain inputs or events.
Edge cases: Specific conditions and exceptional situations
Infinite loop: A loop that never ends, can happen if the condition never becomes false.
For example:
For example:
while (true) {
// Infinite loop
}
// Infinite loop
}
Solution: Make sure the condition is correct or add a break to avoid problems.
Empty loop: A loop that does not perform any action:
Empty loop: A loop that does not perform any action:
for (int i = 0; i < 100; i++) {
// Empty loop
}
// Empty loop
}
1. The club you support
Using the for cycle, write 10 times the name of the club you support.
2. Printing a sequence of numbers
Print all even numbers in the interval from -55 to 55.
3. Writing numbers by rows and columns
Print the first 100 natural odd numbers in 10 rows and 10 columns
Set the initial value of the control variable to 1, as the first odd number of the required number interval, and to change the control variable, set it to change by 2. That is. the third expression in the for loop should be i=i+2
After printing the number, using the if statement, put a new line, if the current number is divisible by 10
for(int br=1,ciklus=1; br<200; br=br+2,ciklus++)
{
return 0;{
printf("%3d ",br);
if(ciklus % 10 == 0)
printf("\n");
}if(ciklus % 10 == 0)
printf("\n");
}
4. Celsius to Fahrenheit
Create a program that, for the loaded values of initial c1 and final c2 temperatures in degrees Celsius, converts all temperature values in that interval from Celsius to Fahrenheit.
Example 1
Input
10
15
Output
10[C] 50[F]
11[C] 51.8[F]
12[C] 53.6[F]
13[C] 55.4[F]
14[C] 57.2[F]
15[C] 59[F]
Example 1
Input
10
15
Output
10[C] 50[F]
11[C] 51.8[F]
12[C] 53.6[F]
13[C] 55.4[F]
14[C] 57.2[F]
15[C] 59[F]
First enter the values of temperatures c1 and c2 using the cin command (C++) or scanf, and then create a for loop.
Put the control variable c, changes from c1 to c2 and it actually represents the temperature in Celsius.
In the body of the for loop, first calculate the current value in Fahrenheit using the formula:
T[oF]=T[oc]*9/5+32
Second, print these two values on the same line
#include <stdio.h>
using namespace std;
int main()
{
}using namespace std;
int main()
{
double c1,c2,f;
cin << c1 << c2;
/*Control variable c(temperature in Celsius) c changes from start c1 to end c2 with step 1
*/
for(double c=c1; c<=c2; c=c+1)
{
return 0;cin << c1 << c2;
/*Control variable c(temperature in Celsius) c changes from start c1 to end c2 with step 1
*/
for(double c=c1; c<=c2; c=c+1)
{
/*The temperature in F is obtained using the formula:*/
f=c*9.0/5.0+32;
cout << c << "[C] " << f << "[F]"<<endl;
}f=c*9.0/5.0+32;
cout << c << "[C] " << f << "[F]"<<endl;
5. Add even numbers
Add all the even numbers between 10 and 50.
6. Average rating
Enter the number of subjects n, then load the grades from n subjects and calculate the average grade
7. Removing zeros from the right
Load an integer, then remove the zeros from the right side. For example. if the number 12000 is entered, the output should be number 12.
8. Dividing a number with the same divisor
Enter the integer N and the divisor d. Abbreviate the number N with the divisor d as long as possible. Print the remainder as well as the number of cycles on the output. For example. Input: N=36, d=3; Output: 4 2;
Explanation: 1st cycle: 36/3=12, 2nd cycle: 12/3=4, the remainder is 4 and the number of cycles is 2
Explanation: 1st cycle: 36/3=12, 2nd cycle: 12/3=4, the remainder is 4 and the number of cycles is 2
9. Training
The athlete started training and ran X kilometers during the first day. Determine how much he will run each day during n days of preparation, if it is known that he will run 10% more every next day than the previous one. Determine how many kilometers the athlete ran in total during the preparation.
10. Cost sheet
Create a daily cost sheet. The program should first load the value of salary or pocket money for the current month, and then load for each day, the daily expense. Print how much money is left that day. When the value of the remaining money is less than 10, stop loading the daily expenses. At the end, write how much money is left, if the balance is positive, or write how much more you spent, if the balance is negative.
11. Free fall simulation
Create a program that simulates the free fall of a body from a height H0. Enter the initial height of the body and create a loop where the time changes by 0.05 seconds in each cycle. Write down all the current positions and velocities of the body at those moments in time during the fall. Determine the speed of the body when falling to the ground computationally and compare it with the value obtained by simulation.
12. Interest
The initial amount of money, the percentage of annual interest attributed to that sum, and the number of years n are loaded. Calculate what the sum of money will be after 1, 2,... ,n years. Each year, interest is credited to the amount received at the end of the previous year.
Input
The initial amount of money, the amount of annual interest in percentages, and the number of years for which the amount of money with interest should be written.
Output
In the ith line, write the amount of money after i years.
Input
The initial amount of money, the amount of annual interest in percentages, and the number of years for which the amount of money with interest should be written.
Output
In the ith line, write the amount of money after i years.
13. The meeting of two cars
Two cars start at the same time, one from place A to place B, and the other from place B to place A, uniformly in a straight line.
Simulate this movement for the entered car speeds, so that every 0.05s of movement, the current time, the traveled paths of both cars, and the current distance between them are printed. The distance between places A and B is entered by the user.
Set a meeting time.
Simulate this movement for the entered car speeds, so that every 0.05s of movement, the current time, the traveled paths of both cars, and the current distance between them are printed. The distance between places A and B is entered by the user.
Set a meeting time.
14. Ski jumps - average
In the ski jumping competition, in addition to the distance that the jumper jumps, the style of the jumper is evaluated. Five judges evaluate the jumper's style with marks from 0 to 20. Then, from all the marks obtained, one of the lowest and one of the highest are deleted. The final score of the jumper's style is calculated as the average of the remaining scores. Write a program that determines the final score of the jumper's style based on the scores of 5 judges.
15. Stock market
A stock market trader either made a profit or lost money every day during one working week. Of all the days on which he earned something, determine the day on which he earned the least and the value he earned on that day (if there are more such days, report first) or report that he lost money on all days.
Input
From the standard input, 5 integers from the interval [−10000,10000][−10000,10000] (amounts that the trader made on Monday, Tuesday, Wednesday, Thursday and Friday) are entered, each in a separate row.
Output
If the trader made a profit on a certain day (the amount is strictly greater than zero), on the standard output, in the first line, write the smallest amount of profit that was made during the week and in the second line, the designation of the day (MON, TUES, WED, CET or FRI) in which the smallest profit was achieved. If no earnings were made on any day, print a line containing only the character -.
Example 1
Input
3200
-420
-10
1350
5670
Output
1350
CET
Example 2
Input
-4700
-360
-1000
-1550
-3245
Output-
Input
From the standard input, 5 integers from the interval [−10000,10000][−10000,10000] (amounts that the trader made on Monday, Tuesday, Wednesday, Thursday and Friday) are entered, each in a separate row.
Output
If the trader made a profit on a certain day (the amount is strictly greater than zero), on the standard output, in the first line, write the smallest amount of profit that was made during the week and in the second line, the designation of the day (MON, TUES, WED, CET or FRI) in which the smallest profit was achieved. If no earnings were made on any day, print a line containing only the character -.
Example 1
Input
3200
-420
-10
1350
5670
Output
1350
CET
Example 2
Input
-4700
-360
-1000
-1550
-3245
Output-
16. Countdown
Example taken from petlja.org/biblioteka/r/Zbirka/brojevi_obrnuti_redosled
Write a program that counts down from a given number to zero.
Write a program that counts down from a given number to zero.
17. Show announcements
Task from the web portal petlja.org: petlja.org/biblioteka/r/problemi/Zbirka/najave_emisije_u_pravilnim_intervalima
The beginning and end of a movie is known (time in hours and minutes). At regular time intervals, first at the beginning of the movie and then after every mm minutes, an announcement of the next show is shown in the corner of the screen. Write a program that prints the times at which this announcement is shown.
Input
The standard input contains the start time of the movie given in the form of two integers, each in a separate line representing the number of hours and the number of minutes, then, in the next line, the end time of the movie given in the same form and finally one integer representing the interval in minutes in which the announcement is displayed.
Output
On the standard output, display the broadcast times of the announcement in the form of h:m, each in a separate line.
Example
Input
12
0
13
53
15
Output
12:0
12:15
12:30 p.m
12:45
13:0
13:15
13:30
3:45
The beginning and end of a movie is known (time in hours and minutes). At regular time intervals, first at the beginning of the movie and then after every mm minutes, an announcement of the next show is shown in the corner of the screen. Write a program that prints the times at which this announcement is shown.
Input
The standard input contains the start time of the movie given in the form of two integers, each in a separate line representing the number of hours and the number of minutes, then, in the next line, the end time of the movie given in the same form and finally one integer representing the interval in minutes in which the announcement is displayed.
Output
On the standard output, display the broadcast times of the announcement in the form of h:m, each in a separate line.
Example
Input
12
0
13
53
15
Output
12:0
12:15
12:30 p.m
12:45
13:0
13:15
13:30
3:45
18. Read to the end of the entry
Task from the site petlja.org/biblioteka/r/problemi/Zbirka/citanje_do_kraja_ulaza
Whole numbers are entered from the input until the end of the input is reached. Write a program that displays how many numbers have been entered.
Input
Each line of standard input contains one integer. NOTE: when testing the program interactively, the end of the standard input is marked with the ctrl + z key combination if the Windows operating system is used, i.e. ctrl + d if using Linux operating system.
Output
In the first line of standard output, show how many numbers have been entered.
Example
Input
20
145
-23
12
456
13
Output
6
Whole numbers are entered from the input until the end of the input is reached. Write a program that displays how many numbers have been entered.
Input
Each line of standard input contains one integer. NOTE: when testing the program interactively, the end of the standard input is marked with the ctrl + z key combination if the Windows operating system is used, i.e. ctrl + d if using Linux operating system.
Output
In the first line of standard output, show how many numbers have been entered.
Example
Input
20
145
-23
12
456
13
Output
6
19. Reading the grades to the end of the entry and calculating the average
From the entrance, grades from a subject are entered until the end of the entrance is reached. Write a program that displays the average grade.
Input
Each line of standard input contains an integer representing a rate.
Output
Display the average grade in the first line of standard output.
Example
Input
5
2
4
4
2
6
Output
3.83
Input
Each line of standard input contains an integer representing a rate.
Output
Display the average grade in the first line of standard output.
Example
Input
5
2
4
4
2
6
Output
3.83
20. Juice warehouse
Crates with juices are stacked on n shelves in the warehouse. Each crate can fit a bottle of juice. Determine the smallest total number of crates needed to pack all the bottles from the warehouse, if the number of juice bottles on each shelf is known, where only bottles from one shelf can be packed in each crate.
Input
In the first line of the standard input there is a natural number n (1≤n≤100) which represents the number of shelves in the warehouse. In the second, there is a natural number k (5≤k≤30) which represents the capacity of the crate. In each of the following nn lines there is a natural number, from the interval [5,500], which represents the number of bottles on each shelf.
Output
The smallest number of used crates is printed in one line of the standard output.
Example
Input
3
8
31
25
16
Output
10
Input
In the first line of the standard input there is a natural number n (1≤n≤100) which represents the number of shelves in the warehouse. In the second, there is a natural number k (5≤k≤30) which represents the capacity of the crate. In each of the following nn lines there is a natural number, from the interval [5,500], which represents the number of bottles on each shelf.
Output
The smallest number of used crates is printed in one line of the standard output.
Example
Input
3
8
31
25
16
Output
10
21. The cheapest for a dinar
In one store, there is an action in progress in which customers who buy three products are offered to get the cheapest of those three products for one dinar. Write a program that determines the discounted price of three products.
Input
From the standard input, three integers from the interval from 50 to 5000 are entered, which represent the prices in dinars for the three purchased products.
Output
Print an integer representing the total discounted price of those three products to standard output.
Example
Input
2499
3599
899
Output
6099
Input
From the standard input, three integers from the interval from 50 to 5000 are entered, which represent the prices in dinars for the three purchased products.
Output
Print an integer representing the total discounted price of those three products to standard output.
Example
Input
2499
3599
899
Output
6099
22. Broadcast announcements at regular time intervals
The beginning and end of a movie is known (time in hours and minutes). At regular time intervals, first at the beginning of the movie and then after every mm minutes, an announcement of the next show is shown in the corner of the screen. Write a program that prints the times at which this announcement is shown.
Input
The standard input contains the start time of the movie given in the form of two integers, each in a separate line representing the number of hours and the number of minutes, then, in the next line, the end time of the movie given in the same form and finally one integer representing the interval in minutes in which the announcement is displayed.
Output
On the standard output, display the broadcast times of the announcement in the form of h:m, each in a separate line.
Example
Input
12
0
13
53
15
Output
12:0
12:15
12:30 p.m
12:45
13:0
13:15
13:30
13:45
Input
The standard input contains the start time of the movie given in the form of two integers, each in a separate line representing the number of hours and the number of minutes, then, in the next line, the end time of the movie given in the same form and finally one integer representing the interval in minutes in which the announcement is displayed.
Output
On the standard output, display the broadcast times of the announcement in the form of h:m, each in a separate line.
Example
Input
12
0
13
53
15
Output
12:0
12:15
12:30 p.m
12:45
13:0
13:15
13:30
13:45
23. Reading to minus 1 or to the n-th
Task from the site petlja.org/biblioteka/r/problemi/Zbirka/citanje_do_minus_1_ili_do_ntog
During the lesson, Pera played and cut paper squares. The teacher noticed this and gave him the task of calculating the total area of all the squares. Write a program that helps Perry do this. Pera, at the very beginning, enters the number "n" which he is sure is greater than or equal to the number of squares. After that, he enters at most n numbers that represent the lengths of the sides of the squares, and if he notices that there are fewer squares than the number of n, he enters −1, which indicates that the entry needs to be stopped.
During the lesson, Pera played and cut paper squares. The teacher noticed this and gave him the task of calculating the total area of all the squares. Write a program that helps Perry do this. Pera, at the very beginning, enters the number "n" which he is sure is greater than or equal to the number of squares. After that, he enters at most n numbers that represent the lengths of the sides of the squares, and if he notices that there are fewer squares than the number of n, he enters −1, which indicates that the entry needs to be stopped.
Input
The number n (0≤n≤15) is loaded from the standard input, followed by 1≤m≤n integers between 11 and 1010, where, if m<n, then −1 is entered after them.
Output
Print a single integer representing the total area of all the squares to the standard output.
Example 1
Input
5
1
2
3
4
5
Output
55
Example 2
Input
5
1
2
3
-1
Output
14
The number n (0≤n≤15) is loaded from the standard input, followed by 1≤m≤n integers between 11 and 1010, where, if m<n, then −1 is entered after them.
Output
Print a single integer representing the total area of all the squares to the standard output.
Example 1
Input
5
1
2
3
4
5
Output
55
Example 2
Input
5
1
2
3
-1
Output
14
24. Savings in the bank
Determine for how many years the stake in the bank from U dinar with the annual interest rate P% rises to R dinars
25. Monthly earning
Make a mini-bill by month. Load monthly earning. For each day, write down how much money you have spent (one cycle). Read the interruption when less than 10 dinars are left of the total salary. If you have entered the minus print a message about it. Print the number of days you spent money.
26. Target shooting
Given a target of N concentric circles of diameter r = 1,2, ..., 10 and a point A (x,y) in the target. For hitting the circle with the smallest diameter, you get 10 points, and for each subsequent ring, one less. Write a program that determines how many points will be scored for a hit if the user enters the coordinates of point A relative to the center of the target.
27. The salt concentration
In the vessel is contained in liters of p% salt solution. from the vessel, a liter of mixture is poured out and a liter of clean water is added, after which the solution is mixed. If N times are "casting" and "stuffing", write a program that prints the salt concentration table in the court after each "casting" and "filling."
28. The number of k-element variations of n elements without repetition
Enter the number of elements n and the number k of elements that vary. Then determine how many variations there are without repetition.
29. The multiplication table
Create a program that prints the multiplication table on the screen:
1 * 1 = 1
1 * 2 = 2
...
9 * 8 = 72
9 * 9 = 81
1 * 1 = 1
1 * 2 = 2
...
9 * 8 = 72
9 * 9 = 81
30. The Least Common Multiple
Create a program that determines The Least Common Multiple of two entered integers.
If you want more examples from the loop area, go to the page Additional examples for exercise - branching in the program
|
Previous
|< Selection statements - examples |
Next
Nested Loops - examples >| |