0% found this document useful (0 votes)
22 views5 pages

C++ For Loops and Nested Loops Guide

This document provides an overview of for loops and nested loops in C++, including their syntax and implementation. It includes example programs demonstrating the use of these loops, as well as practice exercises for finding factorials, GCD, and summing series. Additionally, it includes a rubric for evaluating performance in lab exercises.

Uploaded by

moeeniqbal175
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views5 pages

C++ For Loops and Nested Loops Guide

This document provides an overview of for loops and nested loops in C++, including their syntax and implementation. It includes example programs demonstrating the use of these loops, as well as practice exercises for finding factorials, GCD, and summing series. Additionally, it includes a rubric for evaluating performance in lab exercises.

Uploaded by

moeeniqbal175
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Computer Programming Lab 7

Repetition Statements-II
1: Objective:
• To learn about syntax and implementation of for loops

2: For Loops

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a
specific number of times. Syntax
for ( inital; condition; increment )
{ statement(s);
}

Here is the flow of control in a for loop −


The init (initialization) step is executed first, and only once. This step allows you to declare and initialize any
loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop
does not execute and flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This
statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes, and the process repeats itself (body of loop,
then increment step, and then again condition). After the condition becomes false, the for loop terminates.
Example Program

#include <iostream>

using namespace std;

int main ()

for( int a = 10; a <20;

a = a + 1 )

{ cout << "value of a: "

<< a << endl;


Computer Programming Lab 7

return 0;

Output

3: Nested Loops
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.

Syntax
The syntax for a nested for loop statement in C++ is as follows −

for ( init; condition; increment ) {


for ( init; condition; increment ) {
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a nested while loop statement in C++ is as follows −
Computer Programming Lab 7

while(condition)
{ while(condition)
{ statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a nested do...while loop statement in C++ is as follows −
do { statement(s); // you can put more
statements.
do {
statement(s); }
while( condition );

} while( condition );
Example Program

#include <iostream> using

namespace std; int main

() {

int i, j; for(i = 2; i<30; i++)

for(j = 2; j <= (i/j); j++)

if(!(i%j)) break; // if factor found, not prime

if(j > (i/j))

cout << i << " is prime\n";

return 0;

}
Output
Computer Programming Lab 7

3: Practice Exercise

1) Write a program in C++ to find the factorial of a number. Go to the editor


Sample output:
Input a number to find the factorial: 5
The factorial of the given number is: 120
2) Write a program in C++ to find the Greatest Common Divisor (GCD) of two numbers. Go to the editor
Sample Output:
Input the first number: 25
Input the second number: 15
The Greatest Common Divisor is: 5
3) Write a program that runs a loop from 1 to 10.
When there comes an odd number, the program displays
the sum of all numbers from 1 to that specific odd
number.E.g;
When there comes 1, it displays “Sum of numbers upto 1 is 1”
When there comes 3, it displays “Sum of numbers upto 3 is 4”
When there comes 5, it displays “Sum of numbers upto 5 is 9” And
so on.
Nested Loops
1) Write a program in C++ to calculate the sum of the series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) +
... + (n*n). Go to the editor. Sample Output:
Input the value for nth term: 5
1*1 = 1
2*2 = 4
3*3 = 9
4*4 = 16
5*5 = 25
The sum of the above series is: 55
2) Write a program in C++ to display the pattern like right angle triangle using an asterisk. Go to the
editor
Sample Output:
Input number of rows: 5
*
**
***
****
*****
Computer Programming Lab 7

Name: Roll No:

Instructor Signature: ___________________________

Lab Rubrics

Sr. Performance Excellent Good Fair Poor (0 Marks)


# Indicator (5 Marks) (4-3 Marks) (2-1 Marks)
Skill to Quite able to Able to conduct Able to conduct and Unable to
perform test conduct and and demonstrate demonstrate the conduct and
experiment demonstrate the the problem- problem-based task demonstrate the
(PLO-05) problem-based task based task with with insufficient problem-based
1 (P-4) with complete sufficient implementation task.
implementation and implementation and inadequate
results but inadequate results
interpretation. results Interpretation.
Interpretation.
Scale

Sr. Performance Excellent Good Fair Poor (0 Marks)


# Indicator (5 Marks) (4-3 Marks) (2-1 Marks)
Data Correctly analyses Analyses and Analyses and Fails to analyze and
exploration and interprets the interprets data interprets data interpret data.
and analysis data with useful with basic level of at basic level
2
conclusions. conclusions. without useful
(PLO-04) conclusions
(C-4)
Scale

Common questions

Powered by AI

A do-while loop is preferred when it is essential for the loop body to execute at least once regardless of whether the condition is initially true or false. Unlike a for loop or a while loop, a do-while loop guarantees that the loop body executes first, and the condition is evaluated after the execution of the loop's block . This characteristic is particularly useful in scenarios such as menu-driven programs where a menu should be shown and processed at least once before deciding to continue based on user input. The do-while loop thus ensures that the procedural logic inside the loop is executed at least once, making it suitable for such interactive applications.

Initialization in a for loop is critical as it sets the starting point for the index or counters used within the loop. This step is executed only once at the beginning of the loop, preparing any variables necessary for the subsequent iterations. Omission of initialization could lead to undefined behavior if the control variable is used without a prior assignment, potentially causing errors in execution if the variable has an unspecified value at the loop's beginning . The initialization phase ensures that loop control variables are properly set, thus enabling predictable loop behavior and flow control.

Nested loops involve placing one loop inside another, allowing the inner loop to complete all its iterations for each iteration of the outer loop. This is particularly useful in scenarios where multi-dimensional data needs to be processed, such as matrix operations or generating combinatorial patterns. For instance, nested loops can be efficiently used in algorithms to check for prime numbers within a range, where the outer loop iterates through each number and the inner loop checks for divisors . An example of nested loops is the program that calculates if numbers between 2 and 30 are prime by dividing each number by all numbers less than its square root via nested loops, as shown in the provided example program .

Practice exercises in programming labs play a crucial role by providing students with hands-on opportunities to apply concepts learned in lectures. The lab rubrics indicate performance indicators such as skill to perform test experiments and data exploration and analysis . These exercises promote active engagement, critical thinking, and the application of theoretical knowledge to problem-solving, enhancing students’ coding abilities through iterative practice and experimentarily-driven learning. By tackling incrementally challenging tasks, students also develop competencies in interpreting results effectively and performing data analysis, which are key skill areas evaluated within the rubrics. The structured approach ensures comprehensive understanding and retention, preparing students for more complex programming challenges.

To implement a C++ program to find the greatest common divisor (GCD) of two numbers, the Euclidean algorithm can be utilized, which leverages the property that GCD(a, b) = GCD(b, a % b) until b equals zero. The program steps involve repeatedly replacing the larger number by the remainder when the larger number is divided by the smaller number until a remainder of zero is encountered. This efficient mathematical approach reduces computational complexity by breaking down the problem into smaller, manageable subproblems . In C++, this can be coded using a while loop to continue the division process until one of the numbers becomes zero, returning the other number as the GCD.

Structured programming exercises, like creating series summation or pattern display programs, provide beginner programmers with foundational skills in logical thinking, problem-solving, and algorithmic design. These exercises reinforce the understanding of loops, conditionals, and iteration structures, offering practical experience in translating mathematical concepts into code. Beginners develop a deeper comprehension of programming constructs by implementing code that outputs predictable, incremental, and verifiable results, such as computing (n*n) or displaying patterns like triangles of increasing rows . These tasks also foster debugging and error identification skills, crucial for clearer code comprehension and improved coding proficiency.

For loops provide a concise and efficient means to iterate over a block of code a known number of times. Unlike while loops, which evaluate the condition before executing the loop body, for loops integrate initialization, condition checking, and increment/decrement expressions in a single line, enhancing code readability and compactness. The flow of control in a for loop begins with the initialization step, followed by condition evaluation, execution of the loop body if the condition is true, and finally, the increment step, which repeats until the condition becomes false . While loops continue until a condition becomes false and are often used when the number of iterations is not predetermined, whereas do-while loops execute the block at least once before checking the condition. This makes for loops particularly suitable for iterating over arrays or other collections where the number of elements is known beforehand.

A nested do-while loop is beneficial in scenarios that require at least one execution and a repeated pattern with complex conditional logic, such as in a text-based game menu where the user is prompted with different options that need to be validated. For instance, consider a menu that presents options including Start Game, View High Scores, and Exit, repeatedly prompting the user until a valid input is provided, while each menu action itself involves recursive decision-making processes wherein actions like navigating through a complex hierarchical menu are involved. Here, the outer do-while loop ensures the menu is displayed every time, and nested loops within handle specific game actions, prompting the user for actions at least once per menu interaction. The expected outcome is a robust menu navigation system that guides users through various game features and ensures inputs are iteratively validated and processed . This approach guarantees at least one opportunity to execute even when conditions are not initially met, due to its post-condition checking nature.

Understanding variable scope is essential in programming, particularly with loops, because it determines the visibility and lifetime of variables within a program. Correctly managing variable scope reduces errors related to unexpected value changes and ensures that variables maintain consistent values throughout their intended lifetime. In C++, variables declared inside a loop, such as the control variable in a for loop, are generally accessible only within that loop's body, which prevents accidental modifications from outside the loop. This is especially critical in nested loops, where each iteration might rely on distinct variable states, and a misunderstanding of scope can lead to incorrect results or logic errors . Proper scope management also supports code readability and maintainability by limiting the variables' visibility to necessary contexts.

Calculating the factorial of a number using loops is a common algorithmic task that showcases the utility of loops in reducing repetitive operations to a compact code block. Factorials are used in permutations, combinations, and other mathematical computations. In the context of loop implementation, a simple for loop repeatedly multiplies the accumulating product by successive integers from 1 up to the given number, effectively calculating the factorial . The sample output from the text demonstrates this by inputting a number, such as 5, and iteratively computing the product to yield 120, illustrating how loop constructs simplify complex arithmetic series.

You might also like