0% found this document useful (0 votes)
19 views15 pages

MCT-242L CP1 2022 LM11 10

The document describes Lab 11 on loop control statements in C programming. It contains 3 objectives: to understand and implement nested loops, learn about different loop control statements with examples, and create programs using loop control statements. It discusses break, continue, and goto statements and their usage. It provides examples of using break statements in while and nested loops. The lab submission task is to create programs using loop control statements to check if a number is prime, calculate a sum allowing a negative number to exit the loop, and a password protected program using a break statement.

Uploaded by

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

MCT-242L CP1 2022 LM11 10

The document describes Lab 11 on loop control statements in C programming. It contains 3 objectives: to understand and implement nested loops, learn about different loop control statements with examples, and create programs using loop control statements. It discusses break, continue, and goto statements and their usage. It provides examples of using break statements in while and nested loops. The lab submission task is to create programs using loop control statements to check if a number is prime, calculate a sum allowing a negative number to exit the loop, and a password protected program using a break statement.

Uploaded by

Eman Ijaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Department of Mechatronics and Control Engineering

University of Engineering and Technology Lahore

LAB 11: LOOP CONTROL STATEMENTS IN C


MCT-242L: Computer Programming-I Lab (Fall-2022)
Registration No. 2022-MC-10

OBJECTIVE:
This lab will introduce advanced concepts in loops available in C Language Program. At the end of this lab,
you should be able to:

 Understand and implement nested loops in C language program


 Learn about different loop control statements with examples

APPARATUS:
 Laptop\PC with following tools installed
o Visual Studio Code with C/C++ and Code Runner Extensions
o C/C++ mingw-w64 tools for Windows 10

LOOP CONTROL STATEMENTS


Loop control statements change execution from its normal sequence. They can be used to skip iterations of a
loop, to break out of a loop early, or to continue with the next iteration of a loop. C supports the following
control statements.

Control Statement Description


break statement Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
continue statement Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
goto statement Transfers control to the labeled statement.

When execution leaves a scope, all automatic objects that were created in that scope are destroyed. It
means that when a function or block of code finishes executing, all of the local variables that were created
within that function or block of code are automatically destroyed. This is known as automatic garbage
collection. Automatic garbage collection is a feature of many programming languages, including C, C++,
and Java. It is important because it ensures that memory is not wasted. When an object is no longer needed,
it is automatically destroyed by the garbage collector. This frees up memory so that it can be used for other
things.

void my_function() {
int i = 10; // i is an automatic object
// Do something with i
}
int main() {
my_function();
// i is no longer in scope and is automatically destroyed by the garbage collector
return 0;}
1|Page Computer Programming-I Lab
Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

In this example, the variable i is an automatic object because it is declared within the my_function()
function. When the my_function() function returns, the variable i is automatically destroyed by the
garbage collector. This is because the i variable is no longer in scope. Automatic garbage collection can
help to prevent memory leaks and make code more efficient.

break Statement

The break statement in C programming has the following two usages:

 When a break statement is encountered inside a loop, the loop is


immediately terminated, and the program control resumes at the next
statement following the loop.
 It can be used to terminate a case in the switch statement

break;
Syntax of break Statement

Following examples shows a use of break statement in while loop.

Example 11.1: break statement in C


/* Example_11_1.c: break statement in C
---------------------------------------------------------------------------
This program demonstrates the use of break statement in C. It takes a number
as input form user and displays values on screen from 0 to given number -1 or
maximum to 4 in case of break command.
---------------------------------------------------------------------------
Written by Shujat Ali ([email protected]) on 6-Oct-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>
void print_loop_control_variable(int num) {
int i = 0;
while (i < num) {
printf("The value of loop control variable is %d\n", i++);
if (i > 4) {
/* terminate the loop using break statement */
break;
}
}
}
int main() {
int num = 0;
printf("Enter a number >> ");
scanf("%d", &num);

2|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

// Call the print_loop_control_variable function


print_loop_control_variable(num);
return 0;}
// End of program
Enter a number >> 3
The value of loop control variable is 0
Program Output 1
The value of loop control variable is 1
The value of loop control variable is 2
Enter a number >> 100
The value of loop control variable is 0
The value of loop control variable is 1
Program Output 2
The value of loop control variable is 2
The value of loop control variable is 3
The value of loop control variable is 4

Example 11.2: break statement in nested loop


/* Example_11_2.c: break statement in nested loop
---------------------------------------------------------------------------
This program illustrates the use of break statement in nested loop. When
break statement is used in inner loop, then it only terminates the execution
of inner loop and outer loop carry on its execution.
---------------------------------------------------------------------------
Written by Shujat Ali ([email protected]) on 12-Oct-2022.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */
#include <stdio.h>

void print_stars_pattern(int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j > 3)
break;
else
printf("*");
}
printf("\n");
}
}

int main() {

int num = 0;
printf("Enter a number >> ");
scanf("%d", &num);

3|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

print_stars_pattern(num);

return 0;
}
// End of program
Enter a number >> 6
****
****
Program Output 1 ****
****
****
****
Enter a number >> 3
****
Program Output 2
****
****

LAB SUBMISSION:
Create a Visual Studio Code Workspace, Lab_11 and c files (Task_11_1.c to Task_11_9.c) for individual
tasks and add them to Lab_11 workspace.

TASK 11.1: Prime Number [1 point]


Write a program that asks user to enter an integer and returns if the
number is prime or composite. Make a function IsPrime().
Enter the number >> 19
Sample Output 1
You entered a prime number!
Enter the number >> 57
Sample Output 2
You entered a composite number!

Answer:

#include <stdio.h> int Isprime(int num); int main() { int num = 0; printf("Enter your number:"); scanf("%d", &num);

TASK 11.2: No Negative Sum [1 point]


Write a program that calculates sum of numbers (maximum 10 numbers) and
if the user enters a negative number, the program returns the current
value of sum. Hint: Use loop with a break statement. Make a function

4|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Sum10Num().
Enter n1 >> 12
Enter n2 >> 43
Sample Output 1 Enter n3 >> 21
Enter n4 >> -1
Sum = 76.00
Enter n1 >> 12
Enter n2 >> 2
Enter n3 >> 0
Enter n4 >> 13
Enter n5 >> 5
Sample Output 2 Enter n6 >> 3
Enter n7 >> 54
Enter n8 >> 2
Enter n9 >> 1
Enter n10 >> 4
Sum = 96.00

Answer:

#include <stdio.h> int Sum10Num() { int sum = 0; int number; int count = 0; while (count < 10) { printf("Enter y

TASK 11.3: Password Protected [1 point]


Write a program that asks user to enter the 6-digit password and if the
password is correct, it displays your name otherwise asks user to enter
the password again. For defining password, use const unsigned int
variable. Use break statement. Make a function Password().
Enter the password >> 645289
Sample Output 1
Congratulations Ms. Alina, your password is correct.
Enter the password >> 347581
You entered the wrong password! Try again.
Sample Output 2 Enter the password >> 645289
Congratulations Ms. Alina, your password is correct.

Answer:

#include <stdio.h> void Password(const unsigned int pass) { const unsigned int password = 341400; int enter_password

5|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

If you are using nested loops, the break statement will stop the execution of the innermost loop and start
executing the next line of code after the block.

continue Statement

The continue statement in C programming works somewhat like the break


statement. Instead of forcing termination, it forces the next iteration of the
loop to take place, skipping any code in between.

For the for loop, continue statement causes the conditional test and increment
portions of the loop to execute. For the while and do...while loops, continue
statement causes the program control to pass to the conditional tests.

continue;
Syntax of continue Statement

Following examples shows a use of break statement in while loop.

Example 11.3: continue statement in C


/* Example_11_3.c: continue statement in C
---------------------------------------------------------------------------
This program demonstrates the use of continue statement in C. It takes a
number as input form user and displays values on screen from 0 to given
number - 1 and always skips value 3.
---------------------------------------------------------------------------
Written by Shujat Ali ([email protected]) on 5-Oct-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>

void print_loop_control_variable(int num) {


for (int i = 0; i < num; i++) {
if (i == 3) {
continue;
}

printf("The value of loop control variable is %d\n", i);


}
}

int main() {
int num = 0;

printf("Enter a number >> ");


scanf("%d", &num);

6|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

// Call the print_loop_control_variable function


print_loop_control_variable(num);

return 0;
}
// End of program
Enter a number >> 3
The value of loop control variable is 0
Program Output 1
The value of loop control variable is 1
The value of loop control variable is 2
Enter a number >> 5
The value of loop control variable is 0
Program Output 2 The value of loop control variable is 1
The value of loop control variable is 2
The value of loop control variable is 4

TASK 11.4: Sum the Odds [1 point]


Write a program that will ask user to enter any 6 numbers one by one
and returns the sum of odd numbers only. Use continue statement to skip
the loop iteration for even numbers. Make a function SumOddNum().
Enter the odd number >> 9
Enter the odd number >> 5
Enter the odd number >> 7
Sample Output Enter the odd number >> 13
Enter the odd number >> 21
Enter the odd number >> 4
Sum of odd numbers entered is 55

Answer:

#include <stdio.h> int Sumoddnum() { int oddsum = 0; int number; for (int i = 0; i < 6; i++) { printf("Enter your nu

TASK 11.5: Print Star Triangle [1 point]


Write a program that asks user to enter a number and prints a triangle
of * with number of base stars equal to the number. You are not allowed
to use nested loops. Make a function StarsTriangle().
Enter the number >> 5
*
**
Sample Output
***
****
*****

7|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Answer:

#include <stdio.h> void printStars(int n, int current) { if (current > n) { return; } for (int i = 0; i < current; i++) {

goto Statement

A goto statement in C programming provides an unconditional jump from the


‘goto’ to a labeled statement in the same function.

NOTE: Use of goto statement is highly discouraged in any programming


language because it makes difficult to trace the control flow of a program,
making the program hard to understand and hard to modify. Any program
that uses a goto can be rewritten to avoid them.

goto label;
...
...
label: statement;
Syntax of goto Statement

Here label can be any plain text except C keyword, and it can be set anywhere in the C program above or
below to goto statement.

Example 11.4: goto statement in C


/* Example_11_4.c: goto statement in C
---------------------------------------------------------------------------
This program demonstrates the use of goto statement in C.
It prints a triangle of asterisks to the console. It does this using a goto statement to
jump back to the beginning of the loop each time the loop finishes iterating. The loop
iterates until the variable i is equal to 10.
---------------------------------------------------------------------------
Written by Shujat Ali ([email protected]) on 6-Oct-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>
void print_triangle(int num) {
int i = 0, j = 0;
// goto statement
goto PRINT;

NEXT_LINE:
for (j = 0; j <=i; j++) {
printf("*");
}

8|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

printf("\n");
i++;

// goto statement
PRINT: if (i < num) {
goto NEXT_LINE;
}
}
int main() {

int n = 0;
printf("Enter a number >> ");
scanf("%d", &n);

print_triangle(n);
// Call the print_triangle function
return 0;
}

// End of program
Enter a number >> 5
*
**
Program Output 1
***
****
*****
Enter a number >> 3
*
Program Output 2
**
***

Here are some of the purposes of the goto statement:

To implement loops and conditional statements. The goto statement can be used to implement loops and
conditional statements in a way that is more efficient than using other control flow statements, such as the
for loop and the if statement. However, this can make the code more difficult to read and maintain.

To break out of nested loops and conditional statements. The goto statement can be used to break out of
nested loops and conditional statements without having to use multiple break statements. This can make the
code more concise and readable.

To implement error handling. The goto statement can be used to implement error handling by jumping to
a labeled statement where the error can be handled. This can make the code more efficient and robust.

9|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Example 11.5: goto statement in C


/* Example_11_5.c: goto statement in C
---------------------------------------------------------------------------
Here is an example of how the goto statement can be used to implement a loop. Following
program prints the numbers from 0 to user specified number.
---------------------------------------------------------------------------
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>

void print_numbers(int num)


{
int i=0;
label: if (i < num)
{
printf("%d\n", i);
i++;
goto label;
}
}

int main()
{
int num = 0;
printf("Enter a number: ");
scanf("%d", &num);

print_numbers(num);
return 0;
}

// End of program
Enter a number: 6
0
1
Program Output 1 2
3
4
5
Enter the number of times to print the numbers: 3
0
Program Output 2
1
2

Example 11.6: goto statement in C


/* Example_11_6.c: goto statement in C

10 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

---------------------------------------------------------------------------
Here is an example of how the goto statement can be used to implement a conditional
statement. Following code will prompt the user to enter a number and then print whether
the number is positive, negative, or zero. The goto statement is used to jump to the
appropriate labeled statement based on the value of the number.
---------------------------------------------------------------------------
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>

void print_number_type(int num) {


// Check the value of the number and jump to the appropriate labeled statement
if (num > 0) {
goto POSITIVE;
} else if (num < 0) {
goto NEGATIVE;
} else {
goto ZERO;
}

POSITIVE:
printf("The number is positive.\n");
goto END;

NEGATIVE:
printf("The number is negative.\n");
goto END;

ZERO:
printf("The number is zero.\n");

END:
return;
}

int main() {
int num = 0;

printf("Enter a number: ");


scanf("%d", &num);

// Call the print_number_type function


print_number_type(num);

return 0;
}

11 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

// End of program
Enter a number: 0
Program Output 1
The number is zero.
Enter a number: -2
Program Output 2
The number is negative.

Example 11.7: goto statement in C


/* Example_11_7.c: goto statement in C
---------------------------------------------------------------------------
Here is an example of how the goto statement can be used to implement error handling:
Following code will prompt the user to enter a number and then print an error message if
the number is zero. The goto statement is used to jump to the error handling code if the
number is zero.
---------------------------------------------------------------------------
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>

int check_number_is_zero(int num)


{
if (num == 0)
{
goto error;
}
goto end;

error:
printf("The number cannot be zero.\n");
return 1;
end:
printf("the entered number is %d\n",num);
return 0;
}

int main() {
int num = 0;

printf("Enter a number: ");


scanf("%d", &num);

// Call the check_number_is_zero function


check_number_is_zero(num);
return 0;
}
// End of program
Program Output 1 Enter a number: 6

12 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

the entered number is 6


Enter a number: 0
Program Output 2
The number cannot be zero.

It is important to note that the goto statement should be used with caution. It can make code difficult to read
and maintain, and it can lead to spaghetti code. However, it can be useful in some cases to improve the
performance or efficiency of a program.

TASK 11.6: Rewrite Example 11.4 (avoid goto statement) [1 point]


Since, use of goto statement is highly discouraged in any programming language because it makes
difficult to trace the control flow of a program, making the program hard to understand and hard to
modify. Rewrite example 11.4 avoiding goto statement.

Enter a number >> 5


*
**
Program Output 1
***
****
*****
Enter a number >> 3
*
Program Output 2
**
***
Answer:

#include <stdio.h> void Print_triangle(int num); int main() { int num = 0; printf("Enter the number of stars:"); scanf("%

TASK 11.7: Rewrite Example 11.6 (avoid goto statement) [1 point]


Since, use of goto statement is highly discouraged in any programming language because it makes
difficult to trace the control flow of a program, making the program hard to understand and hard to
modify. Rewrite example 11.6 avoiding goto statement.

Enter a number: 0
Program Output 1
The number is zero.
Enter a number: -2
Program Output 2
The number is negative.
Answer:

#include <stdio.h> void Print_number_type(int num); int main() { int num = 0; printf("Enter your number:"); scanf("%

TASK 11.8: Natural Numbers [1 point]

13 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Write a program that will ask user to enter a number and display all
the natural numbers up to the number entered. You are not allowed to
use any loop. Make a function NaturalNums().
Enter a number: 7
Sample Output 1
1 2 3 4 5 6 7
Enter a number: 19
1 2 3 4 5 6 7
Sample Output 2
8 9 10 11 12 13 14
15 16 17 18 19

Answer:

#include <stdio.h> void print_natural_numbers(int num); int main() { int num = 0; printf("Enter number:"); scanf("%d

The infinite Loop

A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for
this purpose. Since none of the three expressions that form the ‘for’ loop are required, you can make an
endless loop by leaving the conditional expression empty.

Example 11.8: infinite loop in C


/* Example_11_8.c: infinite loop in C
---------------------------------------------------------------------------
This program demonstrates the use of infinite loop in C. It runs infinitely
and doesn't stop. Press Ctrl+C to exit the program.
---------------------------------------------------------------------------
Written by Shujat Ali ([email protected]) on 6-Oct-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>

void print_infinite_loop() {
unsigned long int i = 1;
for (;;) {
printf("%ld This is an infinite loop!\n", i++);
}
}

int main() {
// Call the print_infinite_loop function
print_infinite_loop();

return 0;
}

14 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

// End of program

When the conditional expression is absent, it is assumed to be true. You may have an initialization and
increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite
loop.

NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.


TASK 11.9: Infinite Loop using while [1 point]
Write a program to implement infinite loop by using while loop. This
loop must print “This is infinite loop” with line number infinitely.
1 This is an infinite while loop!
2 This is an infinite while loop!
3 This is an infinite while loop!
Sample Output
4 This is an infinite while loop!
5 This is an infinite while loop!

Answer:

#include <stdio.h> void Print_infinite_loop(int num); int main() { int num; // call the function Print_infinite_loop(num);

Students are advised to fill the manual and submit it before the upcoming lab. Kindly rename the file as
‘MCT-242L_CP1_2022_LM11_XX’, where XX is your roll number. After completing the manual, turn it in Google Classroom.

15 | P a g e Computer Programming-I Lab

You might also like