5 Control Statement

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.

Control Statement: notes

Conditional Statements

By default, C executes the statements of a program sequentially, in the order they appear. The if statement is the simplest way to override that order, executing a statement, or a block of statements in braces, only when a condition is true:

if (condition)
    statement;

The if...else statement extends this to a two-way choice: if the condition is true, one statement or block runs, otherwise the other does, and, as with any C condition, any nonzero value counts as true and zero as false.

#include <stdio.h>

int main() {
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    if (n % 2 == 0)
        printf("%d is even", n);
    else
        printf("%d is odd", n);
    return 0;
}

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 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 < num is logically correct, it simply checks more divisors than necessary. Using i <= num/2 (or i*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

PartPurpose
primeCount < 50Loop continues until exactly 50 primes are found
Inner for loopTests whether num has any divisor
num % i == 0Marks num as composite
count == 0Indicates num is prime
primeCount++Records each prime found
Open this answer on its own page →

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 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$)ExpressionFirst FactorSecond Factor
1$2\times3$23
2$3\times5$35
3$4\times7$47
4$5\times9$59
  • 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 for loop 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.

Open this answer on its own page →

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]

Initial value: $i = 0$ --- The loop starts at $k = 5$, decrements by 1 each pass, and continues while $k \geq 0$. Iteration $k$ Condition $k \geq 0$ $i = i + k$ New $i$ ------------------------------------------------------------ 1 5 True $0 + 5$ 5 2 4 True $5 + 4$ 9 3 3 True $9 + 3$ 12 4 2 True ...

Open this answer on its own page →

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]

--- --- --- The menu is placed inside a do-while loop so that: - The menu is displayed at least once. - The loop continues repeating until the user enters 'D' (Exit). Each menu option is handled by a separate case block: Choice Task Performed ----------------------- A or a Checks if number is Odd...

Open this answer on its own page →

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 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):

  1. The condition is evaluated first.
  2. If the condition is true, the loop body executes.
  3. After executing the body, control goes back to step 1.
  4. 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]

FeatureWhile LoopDo-While Loop
TypeEntry-controlled loopExit-controlled loop
Condition checkChecked before loop body executesChecked after loop body executes
Minimum executions0 times (if condition is false initially)At least 1 time (body executes before check)
Syntaxwhile(condition){ }do{ } while(condition);
SemicolonNo semicolon after conditionSemicolon required after while(condition);
Use caseWhen execution depends on condition being true firstWhen 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:

  • while loop: body executes 0 times
  • do-while loop: body executes 1 time

4. Program to Find Sum and Average of First N Natural Numbers [4 marks]

Algorithm:

  1. Start
  2. Read the value of n
  3. Initialize sum = 0, i = 1
  4. While i <= n, do:
    • sum = sum + i
    • i = i + 1
  5. Calculate average = sum / n
  6. Display sum and average
  7. 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.

Open this answer on its own page →

2077 · 5 marks

Write a program to display first n prime numbers. [5]

Show solved 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

StepDescription
Read nUser inputs how many primes are needed
primeCount = 0Tracks how many primes have been printed
num = 2Candidate number starts at 2
Inner for loopChecks divisibility of num from 2 to num-1
count == 0If 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.

Open this answer on its own page →

2075 · 10 marks

What is looping statement?Discuss different looping statements with suitable example of each.[2+8]

Show solved 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:

  • for
  • while
  • do...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 false at 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

Featurewhiledo...whilefor
TypeEntry-controlledExit-controlledEntry-controlled
Condition checkedBefore bodyAfter bodyBefore body
Minimum executions010
Best used whenIterations unknownMust run at least onceIterations 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.

Open this answer on its own page →

2075 · 5 marks

Write a program to calculate sum of first 10 odd numbers. [5]

The first 10 odd numbers are: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 We use a for loop to iterate through numbers and check whether each number is odd using the condition num % 2 != 0. We keep a count of how many odd numbers have been found and add them to the sum until the count reaches 10. --- --- -...

Open this answer on its own page →

2074 · 5 marks

Write a program that computes the sum of digits of a given integer number. [5]

To find the sum of digits of an integer, we repeatedly extract the last digit using the modulus operator (% 10), add it to a sum variable, and then remove the last digit using integer division (/ 10). This continues until the number becomes 0. Example: For n = 1234 - 1234 % 10 = 4, sum = 4, n = 1...

Open this answer on its own page →

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]

--- The exit() function is defined in <stdlib.h and is used to terminate a program immediately from any point in the code, including from inside functions or loops. Feature exit(0) exit(1) --------- Meaning Normal / successful termination Abnormal / error termination Signal to OS Program complete...

Open this answer on its own page →

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]

A jump statement is a control statement that transfers the flow of program execution unconditionally from one part of the program to another. Jump statements interrupt the normal sequential or loop-based execution and cause the program to "jump" to a different location. --- C provides four jump s...

Open this answer on its own page →

2075 · 5 marks

What is break statement ? Discuss with example. How the break statement is different from continue statement? [1+0.5+3.5]

--- The break statement is a jump statement used inside loops (for, while, do...while) and switch statements. When a break statement is encountered, the execution of the entire loop or switch case is immediately terminated, and the control is transferred to the statement immediately after the loo...

Open this answer on its own page →

Decision Making and Branching

2078 · 5 marks

Write a program to print largest among three number entered by the user. [5]

The logic uses nested if-else statements to compare three numbers entered by the user and determine the largest one. --- --- Condition Result ------------------- a b and a c a is the largest a b but a <= c c is the largest a <= b and b c b is the largest a <= b and b <= c c is the largest --- ---...

Open this answer on its own page →

Conditional Statements

2075 · 5 marks

Write a program to check whether a number entered is even or odd. [5]

When a number is divided by 2: - If the remainder is 0, the number is even - If the remainder is not 0, the number is odd The modulus operator % is used to find the remainder. --- --- Line Description ------------------- include<stdio.h Header file for input/output functions like printf and scanf...

Open this answer on its own page →

2074 · 10 marks

Discuss different types of if statements with suitable example of each.Different if statement with switch statement.[8+2]

(a) Types of if Statements Selection statements (if, if...else, switch) are a category of statements in C that control the flow of execution based on conditions. --- Syntax: Description: If the condition evaluates to true (non-zero), the block of statements inside the braces is executed. If false...

Open this answer on its own page →