C Programming · Unit 5 · 4 hrs
Control Statement
Exam-focused notes for Control Statement (C Programming, CSC115): what the TU syllabus asks and how it has actually been tested, with 15 solved past questions from this unit.
Control Statement in short
This chapter covers how a C program directs the order in which its statements execute: choosing between alternatives with conditional statements, branching with switch and goto, repeating work with loops, and altering a loop's flow with break, continue and exit.
What this unit covers
- Conditional Statements
- Decision Making and Branching
- Decision Making and Looping
- Exit function
- Break and Continue
Decision Making and Looping
2081 · 5 marks
Write a program to display first 50 prime numbers. [5]
Show solved answerHide answer
Program to Display First 50 Prime Numbers
Given Data
- Required output: first 50 prime numbers
- Marks: 5
Concept
A prime number is an integer greater than 1 whose only positive divisors are 1 and itself. To generate the first 50 primes, we test successive integers starting from 2, counting each prime until 50 are found.
Program (C)
#include<stdio.h>
#include<conio.h>
void main()
{
int num, i, count, primeCount;
clrscr();
primeCount = 0; /* number of primes found so far */
num = 2; /* start from smallest prime */
printf("First 50 Prime Numbers are:\n");
while(primeCount < 50)
{
count = 0; /* 0 = prime, 1 = not prime */
for(i = 2; i <= num/2; i++) /* check divisors up to num/2 */
{
if(num % i == 0)
{
count = 1;
break;
}
}
if(count == 0) /* num is prime */
{
printf("%d\t", num);
primeCount++;
}
num++;
}
getch();
}
Note: an inner loop written as
i < numis logically correct, it simply checks more divisors than necessary. Usingi <= num/2(ori*i <= num) is more efficient, and both give the same correct output.
Sample Output
First 50 Prime Numbers are:
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
Verification of Output
Counting the listed primes: 5 rows of 10 = 50 primes. The 50th prime is $229$, which is correct.
Explanation
| Part | Purpose |
|---|---|
primeCount < 50 | Loop continues until exactly 50 primes are found |
Inner for loop | Tests whether num has any divisor |
num % i == 0 | Marks num as composite |
count == 0 | Indicates num is prime |
primeCount++ | Records each prime found |
2081 · 5 marks
Write a program to display the following series up to 25 terms but do not print the 7th term. 2×3, 3×5, 4×7, 5×9... [5]
Show solved answerHide answer
Program to Display Series Up to 25 Terms (Skipping the 7th Term)
Given
- Series: $2\times3,; 3\times5,; 4\times7,; 5\times9,\ldots$
- Number of terms: 25
- Condition: Do not print the 7th term
Solution
Pattern Analysis
| Term ($i$) | Expression | First Factor | Second Factor |
|---|---|---|---|
| 1 | $2\times3$ | 2 | 3 |
| 2 | $3\times5$ | 3 | 5 |
| 3 | $4\times7$ | 4 | 7 |
| 4 | $5\times9$ | 5 | 9 |
- First factor $a = i + 1$
- Second factor $b = 2i + 1$
Verification for $i=4$: $a=5$, $b=9$ → $5\times9$. Correct.
C Program
#include <stdio.h>
int main()
{
int i, a, b;
printf("Series: 2x3, 3x5, 4x7, 5x9 ... up to 25 terms\n");
printf("(7th term is skipped)\n\n");
for(i = 1; i <= 25; i++)
{
if(i == 7) /* Skip the 7th term */
continue;
a = i + 1; /* First factor */
b = 2 * i + 1; /* Second factor */
printf("Term %d: %d x %d = %d\n", i, a, b, a * b);
}
return 0;
}
Sample Output
Series: 2x3, 3x5, 4x7, 5x9 ... up to 25 terms
(7th term is skipped)
Term 1: 2 x 3 = 6
Term 2: 3 x 5 = 15
Term 3: 4 x 7 = 28
Term 4: 5 x 9 = 45
Term 5: 6 x 11 = 66
Term 6: 7 x 13 = 91
Term 8: 9 x 17 = 153
Term 9: 10 x 19 = 190
...
Term 25: 26 x 51 = 1326
Verification of Skipped Term
7th term would be: $a = 8,; b = 15 \Rightarrow 8\times15 = 120$ - this is skipped by the continue statement.
Key Points
- A
forloop iterates $i = 1$ to $25$ (25 terms). if(i == 7) continue;skips only the 7th term.- Formulas: $a = i+1$, $b = 2i+1$.
The program above uses standard C in place of the non-standard Turbo C constructs (void main(), conio.h, clrscr() and getch()); the logic, formulas and output are identical.
2080 · 5 marks
Trace the output
#include <conio.h>
#include <stdio.h>
void main() {
int i = 0, k;
for (k = 5; k >= 0; k--) {
i = i + k;
}
printf("%d\t", i);
getch();
}
[5]
2079 · 10 marks
Write a program to demonstrate the following menu-driven program. The user will provide an integer and alphabet for making choice and the corresponding task has to be performed according as follow:A. Find Odd or Even B. Find Positive or Negative C. Find the Factorial value D. Exit The choice will be displayed until the user will give 'D' as a choice.[10]
2077 · 10 marks
What do you mean by looping?Explain while loop with suitable example.Compare while loop with do while loop.Write a program to find sum and average of first n natural numbers.[1+3+2+4]
Show solved answerHide answer
Looping, While Loop, Comparison with Do-While, and Sum/Average of First N Natural Numbers
1. What is Looping? [1 mark]
Looping (also called iteration) is a programming concept that allows a set of statements to be executed repeatedly as long as a given condition remains true. Instead of writing the same code multiple times, a loop executes it automatically for the required number of times.
Loops are used to:
- Repeat a block of code a fixed number of times
- Process data until a condition is met
- Reduce code length and redundancy
2. While Loop with Example [3 marks]
Definition
The while loop is an entry-controlled loop, meaning the condition is checked before executing the body of the loop. If the condition is false at the very beginning, the loop body is never executed.
Syntax
while (condition)
{
// body of the loop
// increment / decrement statement
}
How it works (Execution Steps):
- The condition is evaluated first.
- If the condition is true, the loop body executes.
- After executing the body, control goes back to step 1.
- If the condition is false, the loop terminates and control passes to the next statement after the loop.
Flowchart Description:
Start --> Check Condition --> [False] --> Exit Loop
|
[True]
|
Execute Body
|
Update Variable
|
(back to Check Condition)
Example: Print numbers 1 to 5
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 1; /* initialization */
clrscr();
while (i <= 5) /* condition */
{
printf("%d\n", i);
i++; /* increment */
}
getch();
}
Output:
1
2
3
4
5
3. Comparison: While Loop vs Do-While Loop [2 marks]
| Feature | While Loop | Do-While Loop |
|---|---|---|
| Type | Entry-controlled loop | Exit-controlled loop |
| Condition check | Checked before loop body executes | Checked after loop body executes |
| Minimum executions | 0 times (if condition is false initially) | At least 1 time (body executes before check) |
| Syntax | while(condition){ } | do{ } while(condition); |
| Semicolon | No semicolon after condition | Semicolon required after while(condition); |
| Use case | When execution depends on condition being true first | When the loop body must run at least once |
Syntax Comparison:
While Loop:
while (condition)
{
// statements
}
Do-While Loop:
do
{
// statements
} while (condition);
Key Difference Example:
If the condition is false from the start:
whileloop: body executes 0 timesdo-whileloop: body executes 1 time
4. Program to Find Sum and Average of First N Natural Numbers [4 marks]
Algorithm:
- Start
- Read the value of n
- Initialize sum = 0, i = 1
- While i <= n, do:
- sum = sum + i
- i = i + 1
- Calculate average = sum / n
- Display sum and average
- Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int i, n, sum;
float average;
clrscr();
/* Input */
printf("Enter the value of n: ");
scanf("%d", &n);
/* Initialize */
sum = 0;
i = 1;
/* While loop to calculate sum */
while (i <= n)
{
sum = sum + i;
i++;
}
/* Calculate average */
average = (float) sum / n;
/* Output */
printf("Sum of first %d natural numbers = %d\n", n, sum);
printf("Average of first %d natural numbers = %.2f\n", n, average);
getch();
}
Sample Output (for n = 5):
Enter the value of n: 5
Sum of first 5 natural numbers = 15
Average of first 5 natural numbers = 3.00
Verification (n = 5):
- Natural numbers: 1, 2, 3, 4, 5
- Sum = 1 + 2 + 3 + 4 + 5 = 15
- Average = 15 / 5 = 3.00
Note:
(float)is used to cast the integer sum to float so that the average is computed as a decimal value, not an integer.
2077 · 5 marks
Write a program to display first n prime numbers. [5]
Show solved answerHide answer
Program to Display First N Prime Numbers
Concept
A prime number is a number greater than 1 that has no divisors other than 1 and itself. To display the first N prime numbers, we use a nested loop:
- The outer loop counts how many primes have been found so far.
- The inner loop checks whether each candidate number is prime.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int n, num, i, count, primeCount;
clrscr();
printf("Enter how many prime numbers to display: ");
scanf("%d", &n);
printf("First %d prime numbers are:\n", n);
primeCount = 0; /* counts how many primes found so far */
num = 2; /* start checking from 2 (smallest prime) */
while(primeCount < n)
{
count = 0; /* count of divisors */
/* Check if num is prime */
for(i = 2; i < num; i++)
{
if(num % i == 0)
{
count++; /* num has a divisor, not prime */
break;
}
}
/* If no divisors found, it is prime */
if(count == 0)
{
printf("%d\n", num);
primeCount++;
}
num++; /* move to next candidate */
}
getch();
}
Sample Output
Enter how many prime numbers to display: 5
First 5 prime numbers are:
2
3
5
7
11
Explanation of Key Steps
| Step | Description |
|---|---|
Read n | User inputs how many primes are needed |
primeCount = 0 | Tracks how many primes have been printed |
num = 2 | Candidate number starts at 2 |
Inner for loop | Checks divisibility of num from 2 to num-1 |
count == 0 | If no divisor found, num is prime; print it and increment primeCount |
num++ | Move to the next candidate number |
Note: The nested loop structure follows the concept of nesting of loops as described in the course notes, where one loop is written inside the body of another loop.
2075 · 10 marks
What is looping statement?Discuss different looping statements with suitable example of each.[2+8]
Show solved answerHide answer
Looping Statements in C
Definition of Looping Statement [2 marks]
A looping statement (also called an iterative statement) is a control structure that allows a block of statements to be executed repeatedly as long as a given condition remains true. Looping avoids writing the same code multiple times and is used when a task needs to be performed a fixed or variable number of times.
As per the notes, iterative statements in C include:
forwhiledo...while
Types of Looping Statements [8 marks]
1. while Loop
Syntax:
while (condition)
{
// body of loop
}
How it works:
- The condition is checked before executing the body.
- If the condition is
true, the body executes. - If the condition is
falseat the start, the body is never executed. - It is called an entry-controlled loop.
Example: Print numbers 1 to 5
#include<stdio.h>
void main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
i++;
}
}
Output:
1
2
3
4
5
2. do...while Loop
Syntax:
do
{
// body of loop
} while (condition);
How it works:
- The body is executed first, then the condition is checked.
- The body executes at least once even if the condition is false.
- It is called an exit-controlled loop.
Example: Print numbers 1 to 5
#include<stdio.h>
void main()
{
int i = 1;
do
{
printf("%d\n", i);
i++;
} while (i <= 5);
}
Output:
1
2
3
4
5
Key difference from while: Even if i starts at 6, the body runs once before checking the condition.
3. for Loop
Syntax:
for (initialization; condition; increment/decrement)
{
// body of loop
}
How it works:
- Initialization: Executed once at the beginning (e.g.,
i = 1). - Condition: Checked before each iteration; if false, loop ends.
- Increment/Decrement: Executed after each iteration.
- It is also an entry-controlled loop and is preferred when the number of iterations is known in advance.
Example: Find the sum of first 10 natural numbers
#include<stdio.h>
void main()
{
int i, sum = 0;
for (i = 1; i <= 10; i++)
{
sum = sum + i;
}
printf("Sum = %d", sum);
}
Output:
Sum = 55
Comparison Table
| Feature | while | do...while | for |
|---|---|---|---|
| Type | Entry-controlled | Exit-controlled | Entry-controlled |
| Condition checked | Before body | After body | Before body |
| Minimum executions | 0 | 1 | 0 |
| Best used when | Iterations unknown | Must run at least once | Iterations known |
Summary
Looping statements are essential in C programming to perform repetitive tasks efficiently. The for loop is used when the number of iterations is known; the while loop is used when the condition is checked before execution; and the do...while loop guarantees at least one execution of the loop body.
2075 · 5 marks
Write a program to calculate sum of first 10 odd numbers. [5]
2074 · 5 marks
Write a program that computes the sum of digits of a given integer number. [5]
Exit function
2079 · 10 marks
What is the difference between exit() and exit(1)? Discuss the need of nested structure with an example. Write a program to find the value of x^y without using POW code.[10]
Break and Continue
2078 · 10 marks
What do you mean by jump statement?Explain each jump statement with example.Write a program to check whether a number entered is prime or not.[1+5+4]
2075 · 5 marks
What is break statement ? Discuss with example. How the break statement is different from continue statement? [1+0.5+3.5]
Decision Making and Branching
2078 · 5 marks
Write a program to print largest among three number entered by the user. [5]
Conditional Statements
2075 · 5 marks
Write a program to check whether a number entered is even or odd. [5]
2074 · 10 marks
Discuss different types of if statements with suitable example of each.Different if statement with switch statement.[8+2]
Make Unit 5 stick
Practice CSC115 with flashcards & quizzes