Control Statements in C: Types & Examples
Control Statements in C: Types & Examples
Mention all the Control Statements available in C (Explain every statements styles) and
its flow chart, example, syntax. (8m)
Control statements in C are used to alter the normal sequential flow of execution of a
program. They can be broadly categorized into three types:
Flow
Statement Syntax Explanation Chart Example
Concept
These statements execute a block of code repeatedly until a specific condition is met.
Flow
Statement Syntax Explanation Chart Example
Concept
These statements cause an unconditional jump from one part of a function to another.
#include <stdio.h>
int main() {
scanf("%d", &num1);
scanf("%d", &num2);
} else { // This block executes if num1 is NOT greater than num2 (i.e., num2 >= num1)
return 0;
The primary use of the break statement within a switch is to terminate the execution of the
switch block after a matching case has been executed.
Prevents Fall-Through: Without break, after a matching case block executes, the
program would continue to execute the code for all subsequent case labels until the
end of the switch block or until a break is encountered. This unintended behavior is
called "fall-through."
Ensures Correct Logic: The break ensures that only the code associated with the
correct, matching case is run, maintaining the intended control flow logic.
4. What is use of goto statement & write the general syntax of goto statement. (2m)
The goto statement in C is a jump statement that provides an unconditional jump from the
point where it is used to a specified label anywhere within the same function.
Use: It's primarily used to transfer control to another point in the program.
Historically, it was sometimes used for breaking out of deeply nested loops or
handling errors by jumping to cleanup code, but it's generally discouraged in modern
programming because it makes the code flow hard to trace.
General Syntax:
// Forward Jump
goto label_name;
// ... statements
label_name:
// statement(s) to execute
// OR
// Backward Jump
label_name:
// statement(s) to execute
// ... statements
goto label_name;
An array is a collection of elements of the same data type stored at contiguous memory
locations.
A. General Syntax for Declaring an Array
data_type array_name[array_size];
array_size: The number of elements the array will hold, specified within square
brackets [].
Example: int scores[50]; (Declares an integer array named scores that can hold 50 elements.)
1. Initialization at Declaration:
Example: char vowels[] = {'a', 'e', 'i', 'o', 'u'}; (The size will be automatically set to 5.)
Advantages of Arrays
Code Optimization: Less code is needed because you can handle a large set of data
using a single variable name and loops, eliminating the need to declare many
individual variables.
Random Access: Accessing any element is very fast and efficient because elements
are stored in contiguous memory locations. The address of any element can be
calculated directly using its index (e.g., arr[i]).
Ease of Sorting/Searching: Algorithms like Bubble Sort, Binary Search, etc., are easily
implemented on arrays.
Memory Efficiency: Arrays utilize memory efficiently as they store elements back-to-
back.
Disadvantages of Arrays
Fixed Size: The size of an array must be specified at the time of declaration and
cannot be changed during program execution. This leads to wastage of memory if
the array is too large, or potential overflow/data loss if it's too small.
Difficult Insertion and Deletion: Inserting a new element or deleting an existing one
requires shifting all subsequent elements, which can be computationally expensive
(time-consuming).
Homogeneous Data Type: An array can only store elements of the same data type.
You cannot store an integer, a float, and a character in the same array (though you
can in a structure).
char str1[12] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0'};
char str2[] = "Hello World"; // Compiler automatically adds '\0' and sets size to 12
Converts an uppercase
letter to its
corresponding char c = 'A'; char
tolower() lowercase equivalent. lower = tolower(c); a
If the character is not printf("%c", lower);
an uppercase letter, it
is returned unchanged.
Converts a lowercase
letter to its
corresponding char c = 'b'; char
toupper() uppercase equivalent. upper = toupper(c); B
If the character is not a printf("%c", upper);
lowercase letter, it is
returned unchanged.
10. Write a program to read a string from terminal using scanf function.
While scanf with the %s format specifier is simple, it has a major limitation: it stops
reading when it encounters the first whitespace (space, newline, or tab).
#include <stdio.h>
int main() {
char name[50];
// NOTE: It is safer to use a width specifier like %49s to prevent buffer overflow.
scanf("%49s", name);
return 0;
Better alternative for strings with spaces: To read a string that includes spaces, the
fgets() function is typically preferred: fgets(name, 50, stdin);.
These functions are used for case conversion of characters and are part of the
<ctype.h> header.
Strings in C are arrays of characters, and common operations are typically performed
using the functions available in the <string.h> header file.
Function
Operation Description
(Example)
Definition of a Function
1. Function Declaration (Prototype): Informs the compiler about the function's name,
return type, and parameters.
3. Function Definition: The actual body of the function, which contains the executable
code.
Example
C
// 1. Function Declaration (Prototype)
int main() {
int x = 5, y = 3;
// 2. Function Call
return 0;
// 3. Function Definition
These are two different ways to pass arguments to a function in C, which determine
whether changes made inside the function affect the original variables in the calling
function.
Mechanism: When you pass arguments by value, the function receives a copy of the
actual values of the variables.
Effect: Changes made to the parameters inside the function have no effect on the
original variables in the calling function.
void modify_value(int a) {
a = a * 2; // Changes ONLY the local copy of 'a'
// In main():
modify_value(num);
Mechanism: When you pass arguments by reference, the function receives the
memory addresses (pointers) of the actual variables, not copies of their values.
Effect: Using the address, the function can directly access and modify the content of
the original variables. Changes made inside the function DO affect the original
variables in the calling function.
*ptr_a = *ptr_a * 2; // Changes the value at the address (the original variable)
// In main():
Example:
#include <stdio.h>
printf("\n");
int main() {
print_array(numbers, n);
return 0;
Variable Length Arguments (or Variable Argument Lists) allow a function to accept a
varying number of arguments at the time of the function call. This is commonly seen
in functions like printf() and scanf().
va_list: A type used to declare a variable that will hold the arguments.
va_start(ap, last_fixed_arg): A macro that initializes the va_list variable (ap). The
second argument is the name of the last fixed (non-variable) argument.
va_arg(ap, type): A macro that retrieves the next argument from the list. The type
specifies the data type of the expected argument.
Example
#include <stdio.h>
#include <stdarg.h>
va_list args;
int sum = 0;
va_start(args, count);
va_end(args);
return sum;
int main() {
return 0;
It looks like you have a continuation of C programming and algorithm questions! Here
are the answers with explanations for the questions provided in the image.
A structure and a union are both user-defined data types in C that allow you to
combine different data types under a single name. The main difference lies in how
they manage memory.
A. Structure (struct)
Syntax:
struct structure_tag {
data_type member1;
data_type member2;
// ...
};
Example:
struct Student {
int roll_no;
char name[50];
float percentage;
};
s1.roll_no = 101;
B. Union (union)
Definition: A union is similar to a structure, but all its members share the same
memory location. The size of the union is equal to the size of its largest member. You
can only use one member of the union at any given time.
Syntax:
union union_tag {
data_type member1;
data_type member2;
// ...
};
Example:
union Data {
int i;
float f;
char c;
};
Separate memory is
2. Memory Shared memory is allocated
allocated for each
Allocation for all members.
member.
19. How can a structure be declared with an another structure explain with an
example.
A structure can contain another structure as its member. This is known as nested
structures.
Explanation: You define the inner structure first, and then use its name as a data
type when defining the outer (or containing) structure. This is essential for grouping
related data hierarchically.
#include <stdio.h>
// 1. Inner Structure Definition
struct Date {
int day;
int month;
int year;
};
struct Employee {
int emp_id;
char name[50];
};
int main() {
emp1.emp_id = 1001;
emp1.date_of_joining.day = 15;
emp1.date_of_joining.month = 6;
emp1.date_of_joining.year = 2024;
emp1.date_of_joining.day,
emp1.date_of_joining.month,
emp1.date_of_joining.year);
return 0;
20. What is a pointer? Write the general format of declaring a pointer. (2m)
What is a Pointer?
Instead of holding an actual value (like an int or char), it holds the location where
that value is stored in the computer's memory.
Pointers are essential in C for tasks like dynamic memory allocation, array
manipulation, and achieving "call by reference."
To declare a pointer, you must specify the data type of the variable it will point to,
followed by the asterisk operator (*) before the pointer's name.
$$\text{data\_type} \ * \ \text{pointer\_name};$$
Component Meaning
The type of the variable whose address the pointer will hold
data_type
(e.g., int, float, char).
Example:
#include <stdio.h>
int temp;
temp = *a;
// 2. Assign the value of the variable pointed to by 'b' to the address of 'a'
*a = *b;
*b = temp;
int main() {
int x = 100;
int y = 200;
printf("Before swapping:\n");
printf("\nAfter swapping:\n");
return 0;
An array of pointers is an array whose elements are all pointers to variables of the
same data type. Passing this array to a function involves passing the base address of
this array of pointers.
Explanation
1. Declaration: Declared like a normal array, but with the pointer operator (*).
$$\text{data\_type} \ * \ \text{array\_name}[\text{size}];$$
2. Use Case (Strings): The most common use is to store a list of strings (where each
string is an array of characters). Since a string name is a pointer to its first character,
an array of pointers to char stores a list of strings efficiently.
3. Passing to a Function: When passing an array of pointers to a function, you pass the
array name (the base address) and typically the size of the array. The function
receives the parameter as a pointer to a pointer (**).
Example
#include <stdio.h>
int main() {
char *names[] = {
"Alice",
"Bob",
"Charlie"
};
int count = 3;
display_strings(names, count);
return 0;
For Integers: It means finding the integers that divide the original number exactly.
Algorithm:
1. Input: A positive number N (the number whose square root is to be found) and a
desired tolerance ($\epsilon$, e.g., $0.0001$) for precision.
3. Iteration: Repeat the following steps until the desired precision is achieved:
25. Write an algorithm to compute the prime factor of an integer and find the GCD
of 2 numbers $a$ and $b$.
This involves two distinct algorithms: Prime Factorization and Greatest Common
Divisor (GCD).
Prime factorization finds the prime numbers that multiply to give the original integer
$N$.
b. Set $N = N / 2$.
3. Factor by Odd Numbers: Start a divisor $i = 3$. While $i \times i \le N$:
4. Remaining Factor: If $N > 1$ after the loop finishes, the remaining value of $N$ is the
last prime factor. Print $N$.
B. Algorithm for Greatest Common Divisor (GCD) of Two Numbers $a$ and $b$
(Euclidean Algorithm)
The Euclidean Algorithm is the most efficient method for finding the GCD.
2. Base Case: If $b$ is 0, the GCD is $a$. Stop and return $a$.
3. Recursion/Iteration: Otherwise, replace $a$ with $b$ and $b$ with the remainder of
$a$ divided by $b$ ($a \ \text{mod} \ b$).
Example:
In the expression: c = a + b;
Control statements are used to alter the flow of program execution and are
categorized into three main types:
o if
o if-else
o else-if ladder
o switch
o for loop
o while loop
o do-while loop
3. Jump Statements:
o break
o continue
o goto
o return
When one function uses or executes another function, they are referred to as the
calling and called functions, respectively.
Calling Function (Caller): This is the function that initiates the execution of another
function. For instance, the main() function is often the calling function for user-
defined functions.
Called Function (Callee): This is the function that is executed upon request from the
calling function. After completing its task, the called function returns control (and
optionally a value) back to the calling function.
Example:
Increases
the int a = 5; a is now
++ Increment
operand's a++; 6
value by 1.
Decreases
the int b = 8; b is now
-- Decrement
operand's b--; 7
value by 1.
bytes) of a
variable or 4
data type.
Reverses
the logical
! Logical NOT !(5 > 3) 0 (False)
state of the
operand.
Returns the
value stored
at the
The value
address
* Dereference *ptr pointed
contained in
to by ptr
the operand
(used with
pointers).
Structure: It requires two indices for accessing an element: the first index specifies
the row number, and the second index specifies the column number.
Declaration Syntax:
$$\text{data\_type} \ \text{array\_name}[\text{rows}][\text{columns}];$$
Example: Declaring a $3 \times 4$ integer array (3 rows, 4 columns) and initializing it.
int matrix[3][4] = {
{1, 2, 3, 4}, // Row 0
};
Both union and struct are used to group variables of different data types, but they
differ fundamentally in memory management.
You can use the if-else control statement to compare two numbers and print the
larger one.
#include <stdio.h>
int main() {
scanf("%d", &num1);
scanf("%d", &num2);
else {
return 0;
}
32. Write an Euclid’s Algorithm to find the GCD of two numbers $a$ and $b$.
The Euclidean Algorithm is an efficient method for computing the greatest common
divisor (GCD) of two integers. It relies on the principle that $\text{GCD}(a, b) = \
text{GCD}(b, a \ \text{mod} \ b)$.
Algorithm Steps:
b. Set $a = b$.
c. Set $b = r$.
3. Output: When the loop terminates (i.e., $b = 0$), the value of $a$ is the GCD.
#include <stdio.h>
int main() {
int original_a = a;
int original_b = b;
while (b != 0) {
remainder = a % b;
return 0;
A pointer to a function (or function pointer) is a variable that stores the memory
address of a function. This allows the function to be called dynamically, passed as an
argument to another function, or returned from a function.
1. Declaration Syntax: The declaration must match the signature (return type and
parameters) of the function it points to.
$$\text{return\_type} \ (*\text{pointer\_name})(\text{parameter\_list});$$
2. Usage: To call the function, you can use either the dereference operator (*) or simply
the function pointer's name (C allows this shorthand).
Example Program
#include <stdio.h>
return x * y;
int main() {
int result;
ptr_to_func = multiply;
return 0;
Function Definition: This is the actual body of the function where the instructions for
the specific task are written. It specifies the return type, the function name, the
parameter list, and the executable statements within curly braces.
Syntax:
Example:
// Function Definition
int add_numbers(int a, int b) { // int is the return type, a and b are parameters
int sum = a + b;
#include <stdio.h>
int main() {
// Compiler automatically adds the '\0' character. Size is 6 (for "Hello" + '\0').
return 0;
o Use: It is used to concatenate (join) two strings. It appends the second string
to the end of the first string.
o Note: The destination array (dest) must be large enough to hold both the
original string and the appended string.
o Return Value:
The Newton-Raphson method finds the square root of a number $N$ by iteratively
applying the formula:
Algorithm:
1. Input: A positive number N (the number to find the square root of) and a desired
Tolerance ($\epsilon$, e.g., $0.0001$).
3. Iteration Loop: Repeat the following steps until the desired precision is met:
$$x_{new} = (x + N / x) / 2$$
b. Check for Convergence: If the absolute difference $|x_{new} - x|$ is less than $\
epsilon$, exit the loop.
c. Update: Set $x = x_{new}$ for the next iteration.
4. Output: The final value of $x$ is the computed square root of $N$.
Requirement: A function using varargs must have at least one fixed parameter (a
named parameter) followed by an ellipsis (...) to indicate the variable argument list.
2. va_start(list, last_fixed_arg): Initialize the va_list. It tells the system where the
variable arguments begin (right after the last fixed parameter).
3. va_arg(list, type): Retrieve the next argument in the list. You must explicitly specify
the data type of the argument being retrieved.
Example
#include <stdio.h>
#include <stdarg.h>
va_list args;
int sum = 0;
va_start(args, count);
// Clean up
va_end(args);
return sum;
int main() {
return 0;
#include <stdio.h>
int temp;
temp = *a;
// 2. Change the value at the address of 'a' to the value at the address of 'b'
*a = *b;
// 3. Change the value at the address of 'b' to the saved original value
*b = temp;
int main() {
int x = 50;
int y = 100;
printf("Before swapping:\n");
printf("\nAfter swapping:\n");
return 0;
Both structures and unions are composite data types, but their memory
management is fundamentally different.
Size: The total memory allocated is the sum of the sizes of all its members.
Layout: Members are stored sequentially. However, the compiler often inserts
hidden, unused bytes called padding between members to align them to boundaries
(e.g., 4 or 8 bytes). This optimizes memory access speed, though it increases the
structure's size.
Example:
struct Example {
char c; // 1 byte
int i; // 4 bytes
};
// Actual size (with padding): Likely 8 bytes (1 byte for 'c' + 3 bytes padding + 4 bytes
for 'i').
All members (c and i) exist simultaneously and can be accessed at any time.
Size: The total memory allocated is equal to the size of the largest member.
Layout: All members start at the same memory location. The union reserves enough
space to hold its largest member.
Example:
union Example {
char c; // 1 byte
};
When you assign a value to u.i, all 4 bytes are used for the integer. If you then assign
a value to u.c, the first byte of that shared space is overwritten with the character
value, corrupting the integer u.i.
Functions in C can be broadly categorized based on whether they are defined by the
user or provided by the system, and how they handle arguments and return values.
1. Based on Source
Category Description Example
Functions can be classified based on whether they accept arguments and return a
value.
Return
Category Arguments Example (Conceptual)
Value
1. No
Function performs a task like
Argument,
No No printing a message directly.
No Return
void print_message(void)
Value
#include <stdio.h>
// Function Category: With Argument (a, b), With Return Value (int)
return a;
} else {
return b;
int main() {
return 0;