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

C Programming Language

This document is a lab manual for a course on Mechatronics and Control Engineering at the University of Engineering and Technology Lahore, focusing on loop control statements and recursive functions in C programming. It covers various control statements such as 'continue' and 'break', provides examples of their use, and explains recursion with practical examples like calculating factorial and generating Fibonacci series. The lab aims to enhance understanding of these programming concepts through hands-on coding exercises.

Uploaded by

AHMAD ALI
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)
5 views15 pages

C Programming Language

This document is a lab manual for a course on Mechatronics and Control Engineering at the University of Engineering and Technology Lahore, focusing on loop control statements and recursive functions in C programming. It covers various control statements such as 'continue' and 'break', provides examples of their use, and explains recursion with practical examples like calculating factorial and generating Fibonacci series. The lab aims to enhance understanding of these programming concepts through hands-on coding exercises.

Uploaded by

AHMAD ALI
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

Department of Mechatronics and Control Engineering

University of Engineering and Technology Lahore

LAB 15: LOOP CONTROL STATEMENTS & RECURSIVE


FUNCTIONS IN C LANGAUGE
RIS-107L: AICT Lab
Registration No. 2025-RIS-106

OBJECTIVE:
This lab will introduce loop control and recursive functions available in C Language Program. At the end of this
lab, you should be able to:

● Understand different loop control statements.


● Understand how recursive functions work.

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:


We have studied about for loop and while loop. Loops have iterations and sometimes we wish to control the execution
of loop iterations. These loop control statements, and the respective scenarios are discussed here.

continue Statement in C:

This statement does not need any header file. This is used inside any loop. When this instruction is executed inside the
loop body, the program skips that iteration and goes to the next iteration of the loop.

Check the output of the following code to see the working of continue statement:
#include <stdio.h>

int main() {
for (int i = 1; i <= 10; i++) {
if (i == 6 || i == 9) {
continue;
}

printf("%d\t", i);
}
return 0;
}

| Page Computer Programming-I Lab


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

This is the output:

1 2 3 4 5 7 8 10
Now let’s understand the particular use of the continue statement.
#include <stdio.h> int
main() {
int dividend, divisor;
char ch = 'y';
while(ch == 'y' || ch == 'Y') {
printf("Enter dividend: ");
scanf("%d", &dividend);
printf("Enter divisor: ");
scanf("%d", &divisor);
printf("Quotient is %d, remainder is %d\n", dividend / divisor,
dividend % divisor);

printf("Do another? (y/n): ");


scanf(" %c", &ch);
}

return 0;
}

We know that devisor cannot be 0 and we want to make sure that user enters a non-zero. You should recall from
the previous lab tasks that we can use a nested while loop at the point where we are taking the divisor as input
that should keep iterating until user enters a non-zero value.

However, in this case we can simply check if the divisor is 0, then we want to skip the remaining part of the loop
body (calculation of Quotient and Remainder) and start the next iteration of the loop that will take the dividend and
divisor again. This logic is implemented in the code below:
#include <stdio.h> int
main() {
int dividend, divisor;
char ch = 'y';
while(ch == 'y' || ch == 'Y') {
printf("Enter dividend: ");
scanf("%d", &dividend);
printf("Enter divisor: ");
scanf("%d", &divisor);
if(divisor == 0) {
printf("Illegal divisor\n");
continue;
}
printf("Quotient is %d, remainder is %d\n", dividend / divisor,
dividend % divisor);
2

printf("Do another? (y/n): "); scanf(" %c", &ch);


| Page Computer Programming-I Lab
Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

return 0; }
break Statement in C:
Recall that you have used break statement inside the switch statement and the effect was skipping all other case
statements inside the switch statement. Likewise, we can use the break statement inside a loop and when executed,
it will terminate that loop i.e. the loop iterations would stop even though the loop condition is true. The continue
statement terminates the execution of one particular iteration and moves to the next iteration, but break statement
is going to terminate all iterations.

To understand this, run the following program:


#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 6; i++) {
printf("*");
}
return 0;
}

You will see 6 asterisks on the output since the for loop has 6 iterations. Now run this code:
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 6; i++) {
if (i==3){ break;
}
printf("*");
}
return 0;
}

Now you will see only two asterisks because when i gets the value 3, break statement ends the loop.

We created one program in previous lab tasks where the program generates a random number and asks the user to guess
it. The code is given here:

#include <stdio.h>
#include <stdlib.h>

| Page Computer Programming-I Lab


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

#include <time.h>

int main() {
// Generate a random number between 1 and 100
srand(time(NULL));
int secretNumber = rand() % 100 + 1;

// Initialize the guess variable


int guess;

printf("Welcome to the Number Guessing Game!\n");


printf("Try to guess the secret number between 1 and 100.\n");

// Start the game loop while


(guess != secretNumber) {
printf("Enter your guess: ");
scanf("%d", &guess);

// Check if the guess is correct


if (guess == secretNumber) {
printf("Congratulations! You guessed the correct number
(%d).\n", secretNumber);
}
else {
printf("Incorrect guess. Try again.\n");
if (guess < secretNumber) {
printf("Hint: The secret number is higher.\n");
}
else {
printf("Hint: The secret number is lower.\n");
}
}
}

return 0;
}

Why did we use a while loop in above code? Because we don’t know in how many attempts the user will guess the
number. Now suppose we want to limit the tries to a maximum of 5, meaning user cannot have the sixth try. Although
this can be achieved by an extended condition on guess being correct and number of attempts being less than 5.
However, we can do this with just one condition on number of attempts and if any attempt is correct, we can use the
break statement to end the process. The code is shown here:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

4 | Page Computer Programming-I Lab


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

int main() {
// Generate a random number between 1 and 100
srand(time(NULL));
int secretNumber = rand() % 100 + 1;

// Initialize variables
int guess, attempts = 0;
int maxAttempts = 5;

printf("Welcome to the Number Guessing Game!\n");


printf("You have %d attempts to guess the secret number between 1 and
100.\n", maxAttempts);

// Start the game loop while


(attempts < maxAttempts) {
printf("Enter your guess: ");
scanf("%d", &guess);
attempts++;

// Check if the guess is correct


if (guess == secretNumber) {
printf("Congratulations! You guessed the correct number (%d)
in %d attempts.\n", secretNumber, attempts);
break; // Exit the loop if the guess is correct
} else {
printf("Incorrect guess. Try again.\n");
if (guess < secretNumber) {
printf("Hint: The secret number is higher.\n");
} else {
printf("Hint: The secret number is lower.\n");
}
}
}

// Check if the player used all attempts without guessing the correct
number
if (attempts == maxAttempts) {
printf("Sorry, you have used all %d attempts. The secret number
was %d.\n", maxAttempts, secretNumber);
}

return 0;
}

The same is done here with a for loop:

#include <stdio.h>
#include <stdlib.h>

| Page Computer Programming-I Lab


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

5
#include <time.h>

int main() {
// Generate a random number between 1 and 100
srand(time(NULL));
int secretNumber = rand() % 100 + 1;

// Initialize variables
int guess, attempts = 0;
int maxAttempts = 5;

printf("Welcome to the Number Guessing Game!\n");


printf("You have %d attempts to guess the secret number between 1 and
100.\n", maxAttempts);

// Start the game loop


for (int i=0; i<maxAttempts; i++) {
printf("Enter your guess: ");
scanf("%d", &guess); attempts++;

// Check if the guess is correct


if (guess == secretNumber) {
printf("Congratulations! You guessed the correct number (%d)
in %d attempts.\n", secretNumber, attempts);
break; // Exit the loop if the guess is correct
} else {
printf("Incorrect guess. Try again.\n");
if (guess < secretNumber) {
printf("Hint: The secret number is higher.\n");
} else {
printf("Hint: The secret number is lower.\n");
}
}
}

// Check if the player used all attempts without guessing the correct
number
if (attempts == maxAttempts) {
printf("Sorry, you have used all %d attempts. The secret number
was %d.\n", maxAttempts, secretNumber);
}

return 0; }

TASK 15.1: Prime Number

6 | Page Computer Programming-I Lab


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

Write a program that will ask the user to enter a number (assuming a
positive integer) and will print if the number is Prime or Composite. We
did this task previously. Now think about efficient logic. Specifically
think that when we find a factor, we should not keep checking for more
factors. One factor found is enough to decide that number is composite.

Answer: #include <stdio.h>

int main() {
int num, isPrime = 1;

printf("Enter a positive integer: ");


scanf("%d", &num);

if (num < 2) {
isPrime = 0;
}

for (int i = 2; i * i <= num; i++) {


if (num % i == 0) {
isPrime = 0;
break; // One factor found — no need to check further
}
}

if (isPrime)
printf("%d is a Prime number.\n", num);
else
printf("%d is a Composite number.\n", num);

return 0;
}

Use of break statement with Infinite while loop:

In a while loop, the loop iterates as long as the given condition remains true. On the other hand, while(1) creates
an infinite loop since the condition is always true. However, within a while(1) loop, the break statement can be
employed to exit the loop.

See this simple code of a while loop:

7 | Page Computer Programming-I Lab


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

#include <stdio.h> int


main() { int count
= 0; while (count <
5) {
printf("Count: %d\n", count);
count++;
}
return 0;
}

Now the same thing is achieved with while(1) and break statement:
#include <stdio.h>
int main() {
int count = 0;
while (1) {
printf("Count: %d\n", count);
count++; if (count >=
5) { break;
}
}
return 0;
}

goto Statement in C:
A goto statement in C programming allows for an unconditional jump from the goto keyword to a labeled statement
within the same function. However, the use of goto is generally discouraged in modern programming practices due
to its potential to complicate code logic and impair readability. Therefore, we will not discus this but you are
encouraged to find the detail by yourself.

Recursion (or Recursive Functions) in C:


A function that calls itself is known as Recursive function. It means that the function will call itself and that will again
call itself and so on. A simple recursive function to display all integers starting from input value to all next integers is
given here:

8 | Page Computer Programming-I Lab


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

#include <stdio.h> void


numberSequence(int n) {
printf("%d\n", n);
numberSequence(n + 1);
}
int main() {
int x;
printf("Enter starting number: ");
scanf("%d", &x);
numberSequence(x); return 0;
}

If you run the above code, you will see that next integers will keep displaying on the screen until the final limit of self-
recursion is reached.

In recursive functions we must have some stopping criteria that will not further call itself. This is also known as the
Base Case. In above example if we want to display integers from entered number to 100 only, it can be done as:
#include <stdio.h> void
numberSequence(int n) {
printf("%d\n", n); if
(n<100){ //Recursive Case
numberSequence(n + 1);
}
//Base Case (the function will not call itself)
}
int main() {
int x;
printf("Enter starting number: ");
scanf("%d", &x);
numberSequence(x); return 0;
}

Now let's see one practical example of writing a recursive function and that is to find the factorial of input number.
Firstly, let's see if the factorial formula can be solved recursively or not. The formula of factorial of x is:

x!=x(x-1)!

9 | Page Computer Programming-I Lab


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

The formula indicates that it can be solved recursively since the formula of factorial involves another factorial. That
another factorial i.e. (x-1)! will be evaluated again using the factorial formula as:

x!=x(x-1)(x-2)!

This will continue until there is 0! and for that we don't need factorial again as 0!=1. Hence:

x!=x(x-1)(x-2)(x-3)(x-4)…(3)(2)(1)(0!) =x(x-1)(x-2)(x-3)(x-4)…(3)(2)(1)(1)

0!=1 is the Base Case for this scenario as it doesn't further need factorial. A user-defined function based on this logic
is here:
#include <stdio.h> int
fact(int num) {
// Base Case
if (num == 0) {
return 1;
}
// Recursive Case
int ans = num * fact(num - 1);
return ans;
}
int main() {
// Output the factorial of 5
printf("%d\n", fact(5)); return
0;
}

The different recursive calls to calculate the factorial of 5 are explained here:

10 | Page Computer Programming-I Lab


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

TASK 15.2: Fibonacci Series


Below is a series known as Fibonacci Series:

F(n)=0,1,1,2,3,5,8,13,21,34,55,…

Note that after first two numbers, next number is sum of previous two.
So, Fibonacci series can be described as:

F(0)=0 Base Case F(1)=1

Base Case

F(n)=F(n-1)+F(n-2) Recursive Case


Create a user define function with one input argument as n and it should
return the value of Fibonacci Number of that n. In main program take
value of n from user and use the function created to display result on
the screen

Enter the value of n: 6


Sample Output 1
Fibonacci number for n = 6 is 8
Answer: #include <stdio.h>

int fibonacci(int n) {
if (n == 0) return 0; // Base Case
if (n == 1) return 1; // Base Case
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive Case
}

int main() {
int n;

11 | Page Computer Programming-I Lab


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

printf("Enter the value of n: ");


scanf("%d", &n);
printf("Fibonacci number for n = %d is %d\n", n, fibonacci(n));
return 0;
}

TASK 15.3: Fibonacci Series


Now create a Non-Recursive user-defined function for the above task and
you will realize that recursive logic is much simpler as compared to the
non-recursive approach.

Enter the value of n: 6


Sample Output 1
Fibonacci number for n = 6 is 8
Answer: #include <stdio.h>

int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;

int prev2 = 0, prev1 = 1, current;

for (int i = 2; i <= n; i++) {


current = prev1 + prev2;
prev2 = prev1;
prev1 = current;
}
return current;
}

int main() {
int n;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Fibonacci number for n = %d is %d\n", n, fibonacci(n));
return 0;
}

If we compare the recursive and non-recursive approaches, the recursive approach is simpler to implement in many
cases since the implementation logic is quite close to the actual definition of the function. But we should also compare
the two approaches on the basis of their performance (time of execution). Recursive functions are slower.

12 | Page Computer Programming-I Lab


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

Recursion is an important concept. It is frequently used in data structure and algorithms.

Tower of Hanoi Problem:

The Tower of Hanoi puzzle is a classic game where you have three rods and a stack of different-sized disks on one rod.
The goal is to move all the disks from one rod to another, following specific rules.

Rules:

● You can only move one disk at a time.


● You can never place a larger disk on top of a smaller one.

How to Solve:

To solve the Tower of Hanoi puzzle:

● Move the top disk from one rod to another rod (following the rules).
● Repeat step 1 until all disks are on the destination rod.

Recursive Solution:

This problem can be solved recursively. If you know how to solve the Tower of Hanoi puzzle with n-1 disks, you can easily
solve it for n disks:

1. Move the top n-1 disks to the spare rod.


2. Move the largest disk to the destination rod.
3. Move the n-1 disks from the spare rod to the destination rod.

Here is the solution:

13 | Page Computer Programming-I Lab


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

#include <stdio.h>

// Function to solve Tower of Hanoi puzzle recursively and print the moves
void towerOfHanoi(int n, char source, char auxiliary, char destination) {
// Base case: If there is only one disk, move it from source to
destination if (n == 1) {
printf("Move disk from rod %c to rod %c\n", source, destination);
return;
}

// Move n-1 disks from source to auxiliary using destination as


temporary
towerOfHanoi(n - 1, source, destination, auxiliary);

// Move the remaining disk from source to destination


printf("Move disk from rod %c to rod %c\n", source, destination);

// Move n-1 disks from auxiliary to destination using source as


temporary
towerOfHanoi(n - 1, auxiliary, source, destination);
}

int main() {
int num_disks;

printf("Enter the number of disks: ");


scanf("%d", &num_disks);

// Solve Tower of Hanoi puzzle and print the moves


towerOfHanoi(num_disks, 'A', 'B', 'C');

return 0;
}

Let's see how each step of the recursive solution corresponds to the code:

1. Move the top n-1 disks to the spare rod:


This corresponds to the first recursive call within the towerOfHanoi function:

towerOfHanoi(n - 1, source, destination, auxiliary);


2. Move the largest disk to the destination rod:
This corresponds to the line immediately following the first recursive call, where we move the largest disk:

14 | Page Computer Programming-I Lab


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

printf("Move disk from rod %c to rod %c\n", source, destination);


3. Move the n-1 disks from the spare rod to the destination rod:
This corresponds to the second recursive call within the towerOfHanoi function:

towerOfHanoi(n - 1, auxiliary, source, destination);

By making these recursive calls in the correct order, the code effectively follows the recursive solution described for the
Tower of Hanoi problem, ultimately solving it for n disks.

As compared to iterative process, recursion is slower and uses more memory because every function call adds a new
frame to the stack. However, we use recursion because some problems are naturally recursive — like factorial,
Fibonacci, tree traversal, and maze solving — and forcing these into iterative loops makes the code complex, error-
prone, and hard to read. For problems like Tower of Hanoi, file system traversal, and divide-and-conquer sorting
algorithms, a clean iterative solution is nearly impossible to write without manually recreating what recursion does
automatically. So, recursion is not about speed. It is about breaking complex problems into manageable self-similar
pieces

15 | Page Computer Programming-I Lab

You might also like