0% found this document useful (0 votes)
34 views44 pages

Control Statements in C: Types & Examples

The document outlines control statements in C, categorized into decision-making, loop control, and jump statements, detailing their syntax, flow charts, and examples. It also includes programming examples, such as finding the largest of two numbers, and explains the use of specific functions like break, goto, and character handling functions. Additionally, it discusses arrays, strings, and function definitions, along with their advantages and disadvantages.
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)
34 views44 pages

Control Statements in C: Types & Examples

The document outlines control statements in C, categorized into decision-making, loop control, and jump statements, detailing their syntax, flow charts, and examples. It also includes programming examples, such as finding the largest of two numbers, and explains the use of specific functions like break, goto, and character handling functions. Additionally, it discusses arrays, strings, and function definitions, along with their advantages and disadvantages.
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

1.

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:

A. Decision Making Statements (Selection Statements)

These statements execute a block of code based on a specific condition.

Flow
Statement Syntax Explanation Chart Example
Concept

if if (condition) { // Executes the code block only if if (x > 10) { printf("X is


Statement code } the condition is true. greater."); }

if (condition) { // Executes the first block if the if (a % 2 == 0)


if-else
true code } else { condition is true, and the else { printf("Even"); } else
Statement
// false code } block if the condition is false. { printf("Odd"); }

Checks a series of conditions


sequentially. The code block
if (cond1) { ... } if (score > 90) { grade
else-if for the first true condition
else if (cond2) = 'A'; } else if (score >
Ladder executes, and the rest are
{ ... } else { ... } 80) { grade = 'B'; }
skipped. The final else is
optional.

Evaluates an expression and


compares its value against
switch
several case labels. Executes
(expression) switch (day) { case 1:
the block of code associated
switch { case c1: ... printf("Mon"); break;
with the matching case. The
Statement break; case default:
break statement is crucial to
c2: ... break; printf("Invalid"); }
exit the switch. default is
default: ... }
optional and executes if no
case matches.

B. Loop Control Statements (Iteration Statements)

These statements execute a block of code repeatedly until a specific condition is met.
Flow
Statement Syntax Explanation Chart Example
Concept

The most commonly used loop for


for (init;
when the number of iterations is for (i = 0; i < 5; i+
condition;
for Loop known. It includes initialization, a FC +) { printf("%d",
update) { //
condition check, and an update i); }
code }
(increment/decrement) step.

Used when the number of iterations


while isn't precisely known beforehand. The
while (num > 0)
(condition) condition is checked before the loop
while Loop FC { sum += num;
{ // code; body executes (pre-test loop). If the
num--; }
update; } condition is initially false, the loop
body never runs.

Similar to the while loop, but the


do { // code; condition is checked after the loop
do { scanf("%d",
do-while update; } body executes (post-test loop). This
FC &input); } while
Loop while ensures the loop body runs at least
(input != 0);
(condition); once, even if the condition is initially
false.

C. Jump Control Statements

These statements cause an unconditional jump from one part of a function to another.

Statement Syntax Explanation

Terminates the innermost switch or loop (for, while, do-while)


break break; it is in, transferring control to the statement immediately
following the terminated construct.

Skips the rest of the current iteration of a loop and proceeds


continue continue;
with the next iteration.

Transfers control to the statement preceded by the specified


goto label; and
goto label. Its use is generally discouraged as it makes the code
label: statement;
difficult to follow (spaghetti code).

return expression; Terminates the execution of a function and returns control to


return
or return; the calling function. It can optionally return a value.
2. Write a program to find largest of 2 number using if statement.

#include <stdio.h>

int main() {

int num1, num2;

// Input the two numbers

printf("Enter the first number: ");

scanf("%d", &num1);

printf("Enter the second number: ");

scanf("%d", &num2);

// Using the if-else statement to compare

if (num1 > num2) {

printf("The largest number is: %d\n", num1);

} else { // This block executes if num1 is NOT greater than num2 (i.e., num2 >= num1)

printf("The largest number is: %d\n", num2);

return 0;

3. What is a use of break in switch (2m)

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;

5. Write the general syntax of declaring and initializing an array. (2m)

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];

 data_type: The type of elements (e.g., int, float, char).

 array_name: A valid identifier for the array.

 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.)

B. General Syntax for Initializing an Array

1. Initialization at Declaration:

data_type array_name[array_size] = {element1, element2, ..., elementN};

 Example: float prices[3] = {10.5, 20.0, 5.25};

2. Initialization without specifying size (Compiler counts elements):

data_type array_name[] = {element1, element2, ..., elementN};

 Example: char vowels[] = {'a', 'e', 'i', 'o', 'u'}; (The size will be automatically set to 5.)

6. Explain different ways of initializing a one-dimensional array (4 different ways).

Here are four common ways to initialize a one-dimensional array:


Way Explanation Example

All elements are explicitly


1. Initialization int arr[4] = {10, 20,
assigned values when the array is
at Declaration 30, 40};
created.

Only some elements are assigned


values. The uninitialized int arr[5] = {1, 2};
2. Partial
elements are automatically set to (Elements will be $\
Initialization
zero (for numeric types) or null {1, 2, 0, 0, 0\}$)
(for character/pointer types).

The size is omitted, and the


float values[] = {3.14,
3. Initialization compiler determines the size
2.71, 1.414}; (Size is
without Size based on the number of
automatically 3)
initializers provided.

The array is declared first, and


int arr[5]; for (int i=0;
then elements are assigned
4. Initialization i<5; i++) { arr[i] = i *
values later using a loop (like a
by Loop 2; } (Elements will be
for loop). This is often used for
$\{0, 2, 4, 6, 8\}$)
user input or calculated values.

7. What are the advantages and disadvantages of array?

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

8. What is a String? (2m) give an example of declaring and initializing of string.

A string in C is simply a sequence of characters stored in a one-dimensional array


and is conventionally terminated by a special character called the null character (\0).
The null character signifies the end of the string.

Example of Declaring and Initializing a String:

// 1. Array initialization (Size 12 to hold "Hello World" + '\0')

char str1[12] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0'};

// 2. String literal initialization (Most common and easiest way)

char str2[] = "Hello World"; // Compiler automatically adds '\0' and sets size to 12

9. Explain any 4 character handling functions with an example.

Character handling functions, also known as character classification and conversion


functions, are defined in the <ctype.h> header file.

Function Description Example Output

Checks if the character


passed is an char c = 'K'; if
isalpha() alphabetic letter (A-Z (isalpha(c)) Alpha
or a-z). Returns true { printf("Alpha"); }
(non-zero) or false (0).

isdigit() Checks if the character char c = '7'; if Digit


passed is a decimal (isdigit(c))
digit (0-9). Returns
Function Description Example Output

true (non-zero) or false


{ printf("Digit"); }
(0).

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() {

// Declare a character array (string)

char name[50];

// Prompt the user for input

printf("Enter your first name (no spaces): ");

// Read the string using scanf. The '%s' format specifier


// reads a string until it finds whitespace.

// NOTE: It is safer to use a width specifier like %49s to prevent buffer overflow.

scanf("%49s", name);

// Print the string read

printf("Hello, %s!\n", 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);.

11. What is the use of tolower() and toupper() function?

These functions are used for case conversion of characters and are part of the
<ctype.h> header.

 tolower(char c): Its purpose is to convert an uppercase alphabetic character (A


through Z) to its corresponding lowercase character (a through z). If the argument c
is already lowercase or is a non-alphabetic character (like a digit or symbol), it is
returned unchanged.

 toupper(char c): Its purpose is to convert a lowercase alphabetic character (a


through z) to its corresponding uppercase character (A through Z). If the argument c
is already uppercase or is a non-alphabetic character, it is returned unchanged.

12. Explain operations on string.

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)

Appends or joins the second string (str2)


strcat(str1,
Concatenation to the end of the first string (str1). str1
str2)
must have enough space.

Copies the content of the source string


strcpy(dest,
Copying (src) into the destination string (dest),
src)
including the null terminator.

Compares two strings lexicographically.


strcmp(str1, Returns 0 if they are equal, a negative
Comparison
str2) value if str1 comes before str2, and a
positive value if str1 comes after str2.

Calculates and returns the length of the


Length strlen(str) string (the number of characters,
excluding the null terminator \0).

Searches for the first occurrence of a


strchr(str, character in a string. Other search
Searching
char) functions include strstr for searching for
a substring.

13. Define a function, its definition, example, and syntax. (2m)

Definition of a Function

A function is a self-contained block of code that performs a specific, well-defined


task. It helps break down a large program into smaller, manageable, and reusable
modules, improving code organization and readability.

Function Syntax (The three components)

A function in C typically involves three parts:

1. Function Declaration (Prototype): Informs the compiler about the function's name,
return type, and parameters.

2. Function Call: The mechanism by which the function is executed.

3. Function Definition: The actual body of the function, which contains the executable
code.

Example

C
// 1. Function Declaration (Prototype)

int add_numbers(int a, int b);

int main() {

int x = 5, y = 3;

// 2. Function Call

int sum = add_numbers(x, y);

printf("The sum is: %d\n", sum);

return 0;

// 3. Function Definition

int add_numbers(int num1, int num2) {

int result = num1 + num2;

return result; // Returns the result to the caller (main)

14. Explain call by value and call by reference with an example.

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.

A. Call By Value (Pass By Value)

 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.

Example (Call By Value):

void modify_value(int a) {
a = a * 2; // Changes ONLY the local copy of 'a'

printf("Inside function, a = %d\n", a); // Output: 20

// In main():

int num = 10;

modify_value(num);

printf("Outside function, num = %d\n", num); // Output: 10 (Original value is


unchanged)

B. Call By Reference (Pass By Reference)

 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.

Example (Call By Reference):

void modify_reference(int *ptr_a) { // Receives a pointer (address)

*ptr_a = *ptr_a * 2; // Changes the value at the address (the original variable)

printf("Inside function, *ptr_a = %d\n", *ptr_a); // Output: 20

// In main():

int num = 10;

modify_reference(&num); // Passes the ADDRESS of num (&num)

printf("Outside function, num = %d\n", num); // Output: 20 (Original value IS


changed)

15. Explain passing array to function with ex


When an array is passed to a function in C, it is effectively passed by reference. This
means the function receives the base address (the address of the first element) of
the array, not a copy of the entire array.

Syntax for Passing Array to a Function:

// Function Prototype: The array is declared using square brackets

void print_array(int arr[], int size);

// OR using a pointer to the first element

void print_array(int *arr, int size);

Example:

#include <stdio.h>

// Function definition to print array elements

void print_array(int arr[], int size) {

printf("Array elements inside function: ");

for (int i = 0; i < size; i++) {

printf("%d ", arr[i]);

// Demonstration of side effect (pass by reference)

arr[i] = 0; // This modification AFFECTS the original array in main

printf("\n");

int main() {

int numbers[] = {10, 20, 30, 40, 50};

int n = sizeof(numbers) / sizeof(numbers[0]);


// Pass the array name (which acts as a pointer to the first element)

// and the size to the function

print_array(numbers, n);

// After function call, the original array is changed:

printf("Original array after function call: %d\n", numbers[0]); // Output: 0

return 0;

16. Explain variable length argument with ex

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().

To implement this, C provides tools in the <stdarg.h> header file. A variable


argument function must have at least one fixed parameter (a named parameter)
followed by an ellipsis (...).

Key Components from <stdarg.h>

 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.

 va_end(ap): A macro that performs cleanup for the argument list.

Example

#include <stdio.h>

#include <stdarg.h>

// Function to find the sum of a variable number of integers


// 'count' is the necessary fixed argument that tells the function how many

// variable arguments to expect.

int sum_all(int count, ...) {

va_list args;

int sum = 0;

// Initialize args to point to the first variable argument

va_start(args, count);

// Loop through all the 'count' arguments

for (int i = 0; i < count; i++) {

// Retrieve the next argument as an integer

sum += va_arg(args, int);

// Clean up the va_list structure

va_end(args);

return sum;

int main() {

// Calling the function with 3 arguments

int s1 = sum_all(3, 10, 20, 30);

printf("Sum 1: %d\n", s1); // Output: 60

// Calling the function with 5 arguments

int s2 = sum_all(5, 1, 2, 3, 4, 5);


printf("Sum 2: %d\n", s2); // Output: 15

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.

17. Define a Structure and Union with Definition and Example.

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)

 Definition: A structure is a collection of variables (of different data types) under a


single name. Each member of a structure is allocated its own separate memory
location.

 Syntax:

struct structure_tag {

data_type member1;

data_type member2;

// ...

};

 Example:

struct Student {

int roll_no;

char name[50];

float percentage;

};

// Variable declaration and use


struct Student s1;

s1.roll_no = 101;

printf("Roll No: %d", s1.roll_no);

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;

};

// Variable declaration and use

union Data d1;

d1.i = 10; // Use 'i'. Memory holds an integer (10).

// d1.f = 20.5; // If you uncomment this, 'd1.i' will be corrupted.

printf("Value of i: %d", d1.i);

18. Difference between Union and Structure (5m) 8 points.


Feature Structure (struct) Union (union)

1. Keyword Uses the keyword struct. Uses the keyword union.

Separate memory is
2. Memory Shared memory is allocated
allocated for each
Allocation for all members.
member.

Sum of the sizes of all its


3. Size Size of the largest member.
members (plus padding).

All members can be


4. Member Only one member can be
accessed and modified
Access used at a time.
simultaneously.

5. All members can be Only the first member can


Initialization initialized at declaration. be initialized at declaration.

Data for one member


6. Data Data for all members is
overwrites the data of
Integrity preserved.
others.

Used when you need to Used for memory


store multiple, different optimization or when data
7. Purpose
data fields for a single can be interpreted in
entity. multiple ways.

struct {char c; int i;} $\ union {char c; int i;} $\


8. Example
rightarrow$ Size is $1 + 4 = rightarrow$ Size is $\
Size
5$ (or 8 due to padding). text{sizeof(int)} = 4$ bytes.

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.

 Example: Defining a Date structure inside an Employee structure.

#include <stdio.h>
// 1. Inner Structure Definition

struct Date {

int day;

int month;

int year;

};

// 2. Outer (Containing) Structure Definition

struct Employee {

int emp_id;

char name[50];

// Nested Structure Declaration

struct Date date_of_joining;

};

int main() {

struct Employee emp1;

emp1.emp_id = 1001;

// Accessing Nested Members using the dot operator (.) twice

emp1.date_of_joining.day = 15;

emp1.date_of_joining.month = 6;

emp1.date_of_joining.year = 2024;

printf("Employee ID: %d\n", emp1.emp_id);

printf("Joined on: %d/%d/%d\n",

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?

A pointer is a variable that stores the memory address of another variable.

 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."

General Format of Declaring a Pointer

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

The dereference operator when used in an expression, but the


* (asterisk)
declaration operator when used in a declaration.

pointer_name The name of the pointer variable.

Example:

int *ptr_to_int; // Pointer to an integer

float *ptr_to_float; // Pointer to a float

21. Write a program swapping of 2 numbers of pointers. (8m)


Swapping two numbers using pointers (call by reference) ensures the original
variables in the main function are modified.

#include <stdio.h>

// Function to swap two integers using pointers (Call by Reference)

void swap_numbers(int *a, int *b) {

// *a and *b access the values at the memory addresses passed

int temp;

// 1. Store the value of the variable pointed to by 'a' in temp

temp = *a;

// 2. Assign the value of the variable pointed to by 'b' to the address of 'a'

*a = *b;

// 3. Assign the original value (stored in temp) to the address of 'b'

*b = temp;

int main() {

int x = 100;

int y = 200;

printf("Before swapping:\n");

printf("x = %d, y = %d\n", x, y);

// Call the function, passing the ADDRESSES (&) of x and y


swap_numbers(&x, &y);

printf("\nAfter swapping:\n");

printf("x = %d, y = %d\n", x, y);

return 0;

22. Explain array of pointers to a function.

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>

// Function definition accepting an array of char pointers

// Equivalent to: void display_strings(char *arr[], int count)

void display_strings(char **arr, int count) {

printf("Printing strings from function:\n");

for (int i = 0; i < count; i++) {

// arr[i] is a pointer (address of a string)


printf("String %d: %s\n", i + 1, arr[i]);

int main() {

// Array of Pointers to char (each points to a string literal)

char *names[] = {

"Alice",

"Bob",

"Charlie"

};

int count = 3;

// Passing the array of pointers to the function

display_strings(names, count);

return 0;

23. What is factoring or factorization?

Factorization (or Factoring) is the decomposition of a mathematical object (like a


number, a polynomial, or a matrix) into a product of other, simpler objects, called
factors, which when multiplied together give the original object.

 For Integers: It means finding the integers that divide the original number exactly.

o Example: The factorization of 12 is $2 \times 2 \times 3$ (prime factors).

o Factors of 12: 1, 2, 3, 4, 6, 12.

 For Polynomials: It means finding simpler polynomials (binomials or trinomials)


whose product is the original polynomial.

o Example: The factorization of $x^2 - 4$ is $(x - 2)(x + 2)$.


24. Write an algorithm to find the square root of a number using Newton method
with an example.

The Newton-Raphson method (or simply Newton's method) is an iterative algorithm


to find the roots of a real-valued function. To find the square root of a number $N$,
we seek the root of the function $f(x) = x^2 - N$.

The iterative formula is:

$$x_{k+1} = x_k - \frac{f(x_k)}{f'(x_k)}$$

Since $f(x) = x^2 - N$, the derivative is $f'(x) = 2x$.

Substituting these gives the formula for square root:

$$x_{k+1} = x_k - \frac{x_k^2 - N}{2x_k} = \frac{2x_k^2 - (x_k^2 - N)}{2x_k} = \


frac{x_k^2 + N}{2x_k}$$

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.

2. Initial Guess: Choose an initial approximation x (e.g., $x = N/2$).

3. Iteration: Repeat the following steps until the desired precision is achieved:

a. Calculate the next approximation $x_{new}$ using the formula:

$$x_{new} = \frac{x + N/x}{2}$$

b. Check for convergence: If $|x_{new} - x| < \epsilon$, stop the iteration.

c. Update: Set $x = x_{new}$ for the next iteration.

4. Output: The final value of $x$ is the square root of $N$.

Example (Find $\sqrt{25}$ with $N=25$)

| Iteration ($k$) | Current Guess ($x$) | Calculation $x_{new} = (x + 25/x) / 2$ |


Difference $|x_{new} - x|$ |

| :--- | :--- | :--- | :--- |

| 0 (Start) | $x_0 = 12.5$ (Initial Guess $25/2$) | $(12.5 + 25/12.5) / 2 = 7.25$ |


$5.25$ |

| 1 | $x_1 = 7.25$ | $(7.25 + 25/7.25) / 2 \approx 5.349$ | $1.901$ |

| 2 | $x_2 \approx 5.349$ | $(5.349 + 25/5.349) / 2 \approx 5.011$ | $0.338$ |


| 3 | $x_3 \approx 5.011$ | $(5.011 + 25/5.011) / 2 \approx 5.000012$ | $0.011$ |

| 4 | $x_4 \approx 5.000012$ | $\approx 5.000000$ | Stop (Converged to 5) |

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

A. Algorithm for Prime Factorization of an Integer $N$

Prime factorization finds the prime numbers that multiply to give the original integer
$N$.

1. Input: An integer $N > 1$.

2. Factor by 2: While $N$ is divisible by 2:

a. Print 2 (as a factor).

b. Set $N = N / 2$.

3. Factor by Odd Numbers: Start a divisor $i = 3$. While $i \times i \le N$:

a. While $N$ is divisible by $i$:

i. Print $i$ (as a factor).

ii. Set $N = N / i$.

b. Increment $i$ by 2 (since any even number $>2$ cannot be prime).

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.

1. Input: Two non-negative integers $a$ and $b$.

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$).

$$\text{GCD}(a, b) = \text{GCD}(b, a \ \text{mod} \ b)$$

4. Repeat: Go back to Step 2 until the remainder is 0.


Example: $\text{GCD}(48, 18)$

1. $\text{GCD}(48, 18) = \text{GCD}(18, 48 \ \text{mod} \ 18 = 12)$

2. $\text{GCD}(18, 12) = \text{GCD}(12, 18 \ \text{mod} \ 12 = 6)$

3. $\text{GCD}(12, 6) = \text{GCD}(6, 12 \ \text{mod} \ 6 = 0)$

4. Since $b=0$, the GCD is $a=6$. Output: 6.

26. What is Operator and Operand? With an Example.

 Operator: An operator is a symbol that tells the compiler to perform a specific


mathematical or logical manipulation. Examples include + (addition), = (assignment),
and > (greater than).

 Operand: An operand is a value or a variable on which the operator performs the


operation.

Example:

In the expression: c = a + b;

 The operators are: =, and +.

 The operands are: c, a, and b.

2. Mention all the Control Statements available in C.

Control statements are used to alter the flow of program execution and are
categorized into three main types:

1. Decision Making (Selection) Statements:

o if

o if-else

o else-if ladder

o switch

2. Loop Control (Iteration) Statements:

o for loop

o while loop

o do-while loop

3. Jump Statements:
o break

o continue

o goto

o return

27. What is meant by Calling and Called Function?

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:

In main() { int sum = add(5, 3); } where add is a separate function:

 main() is the Calling Function.

 add() is the Called Function.

28. What is Unary Operator? Explain with an Example.

A unary operator is an operator that operates on only one operand.

Operator Name Purpose Example Result

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.

sizeof Size of Returns the sizeof(int) Typically


size (in
Operator Name Purpose Example Result

bytes) of a
variable or 4
data type.

Reverses
the logical
! Logical NOT !(5 > 3) 0 (False)
state of the
operand.

Returns the The


memory address
& Address-of address of &myVar in
the memory
operand. of myVar

Returns the
value stored
at the
The value
address
* Dereference *ptr pointed
contained in
to by ptr
the operand
(used with
pointers).

29. Explain Two-Dimensional Arrays.

A two-dimensional (2D) array is an array of arrays. It is organized as a grid of rows


and columns, similar to a table or a matrix.

 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}];$$

 Memory: Elements are stored contiguously in memory, typically in row-major order


(all elements of the first row, followed by all elements of the second row, and so on).

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

{5, 6, 7, 8}, // Row 1

{9, 10, 11, 12} // Row 2

};

// Accessing the element at Row 1, Column 2 (which is 7)

int val = matrix[1][2]; // val will be 7

30. Difference between Union and Structure.

Both union and struct are used to group variables of different data types, but they
differ fundamentally in memory management.

Feature Structure (struct) Union (union)

Memory Separate memory is Shared memory is allocated


Allocation allocated for each member. for all members.

The total size is the sum of


The size is equal to the size
Size the sizes of all members
of the largest member.
(plus padding).

All members can be Only one member can be


Access accessed and modified used meaningfully at any
simultaneously. given time.

Changing one member's


Data Data for all members is
value overwrites the data of
Integrity preserved.
the other members.
31. Write a program to find largest of two numbers using if statement.

You can use the if-else control statement to compare two numbers and print the
larger one.

#include <stdio.h>

int main() {

int num1, num2;

printf("Enter the first number: ");

scanf("%d", &num1);

printf("Enter the second number: ");

scanf("%d", &num2);

// Use if-else to compare

if (num1 > num2) {

printf("The largest number is: %d\n", num1);

else if (num2 > num1) {

printf("The largest number is: %d\n", num2);

else {

printf("Both numbers are equal: %d\n", num1);

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:

1. Input: Two positive integers, $a$ and $b$.

2. Iterate: While $b$ is not equal to 0, repeat the following steps:

a. Calculate the remainder $r = a \ \text{mod} \ b$.

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.

Program Implementation (Iterative):

#include <stdio.h>

int main() {

int a, b, temp, remainder;

printf("Enter two positive integers: ");

scanf("%d %d", &a, &b);

int original_a = a;

int original_b = b;

// The Euclidean Algorithm implementation

while (b != 0) {

remainder = a % b;

a = b; // New 'a' becomes the old 'b'

b = remainder; // New 'b' becomes the remainder


}

printf("The GCD of %d and %d is: %d\n", original_a, original_b, a);

return 0;

33. Write and Explain Pointer to Function.

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.

Syntax and Explanation

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});$$

o The parentheses around *pointer_name are mandatory to distinguish it from


a function that returns a pointer.

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>

// 1. A simple function with int return and two int parameters

int multiply(int x, int y) {

return x * y;

int main() {

int result;

// 2. Declaration of a function pointer:

// It points to a function that takes (int, int) and returns int.

int (*ptr_to_func)(int, int);


// 3. Assignment: Assign the address of the 'multiply' function.

// The function name itself acts as a pointer (like an array name).

ptr_to_func = multiply;

// 4. Calling the function using the pointer (with and without *)

// Method A: Explicit dereference

result = (*ptr_to_func)(10, 5);

printf("Result (Method A): %d\n", result); // Output: 50

// Method B: Shorthand (most common)

result = ptr_to_func(20, 3);

printf("Result (Method B): %d\n", result); // Output: 60

return 0;

34. Explain a Function Definition, Example, and Syntax

A function is a self-contained, named block of code designed to perform a specific


task. Its primary purpose is to modularize code, improve reusability, and make a
program easier to manage.

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

$$\text{return\_type} \ \text{function\_name}(\text{parameter\_list}) \ \{ \\ \quad //


\text{Statements constituting the function body} \\ \quad \text{return} \ \
text{value}; \ // \text{Optional} \\ \}$$

 Example:

// Function Definition
int add_numbers(int a, int b) { // int is the return type, a and b are parameters

int sum = a + b;

return sum; // Returns an integer value

35. What is a String? Give an Example of Declaring and Initializing a String.

A string in C is a sequence of characters stored in a one-dimensional character array


that is conventionally terminated by a null character (\0). The null character signals
the end of the string to C functions.

 Example of Declaring and Initializing a String:

#include <stdio.h>

int main() {

// Declaration and Initialization using a string literal (most common)

// Compiler automatically adds the '\0' character. Size is 6 (for "Hello" + '\0').

char greeting[] = "Hello";

// Declaration and Initialization with explicit size and characters

char city[10] = {'P', 'a', 'r', 'i', 's', '\0'};

printf("String 1: %s\n", greeting);

printf("String 2: %s\n", city);

return 0;

36. What is the Use of strcat() and strcmp()?


These are standard string handling functions defined in the <string.h> header file.

 strcat() (String Concatenation):

o Use: It is used to concatenate (join) two strings. It appends the second string
to the end of the first string.

o Syntax: char *strcat(char *dest, const char *src);

o Note: The destination array (dest) must be large enough to hold both the
original string and the appended string.

 strcmp() (String Compare):

o Use: It is used to compare two strings lexicographically (based on the ASCII


values of their characters).

o Syntax: int strcmp(const char *str1, const char *str2);

o Return Value:

 0: If the strings are identical (equal).

 A negative value: If str1 comes before str2 alphabetically.

 A positive value: If str1 comes after str2 alphabetically.

4. Write an Algorithm to find the Square Root of a Number using Newton’s


Method.

The Newton-Raphson method finds the square root of a number $N$ by iteratively
applying the formula:

$$x_{k+1} = \frac{x_k + N/x_k}{2}$$

Algorithm:

1. Input: A positive number N (the number to find the square root of) and a desired
Tolerance ($\epsilon$, e.g., $0.0001$).

2. Initial Guess: Choose an initial approximation x (a common simple guess is $x =


N/2$).

3. Iteration Loop: Repeat the following steps until the desired precision is met:

a. Calculate the Next Approximation $x_{new}$:

$$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$.

37. Explain Variable Length Argument with Example.

Variable Length Arguments (Varargs) allow a function to accept an indefinite


number of arguments. The most famous example is the printf() function. This
functionality is implemented using macros defined in the <stdarg.h> header file.

 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.

Key Steps (Macros)

1. va_list: Declare a variable of type va_list to hold the list of arguments.

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.

4. va_end(list): Perform necessary cleanup.

Example

#include <stdio.h>

#include <stdarg.h>

// 'count' is the fixed parameter, indicating how many numbers to sum.

int sum_all(int count, ...) {

va_list args;

int sum = 0;

// Start processing arguments after 'count'

va_start(args, count);

for (int i = 0; i < count; i++) {


// Retrieve the next argument, treating it as an integer

sum += va_arg(args, int);

// Clean up

va_end(args);

return sum;

int main() {

// Calling with 4 numbers

int total = sum_all(4, 10, 20, 30, 40);

printf("Total sum: %d\n", total); // Output: 100

return 0;

38. Explain the Operations on String.


Operations on strings involve manipulating, inspecting, or combining character
arrays. In C, these operations are typically performed using functions from the
<string.h> library.

Operation Function Description Example

Appends the source


string (src) to the strcat(s1, s2)
strcat(dest,
Concatenation end of the joins $s_1$
src)
destination string and $s_2$.
(dest).

Copies the source


string (src) entirely strcpy(s1,
strcpy(dest, into the destination "New") sets
Copying
src) string (dest), $s_1$ to
overwriting its "New".
previous content.

Compares $s_1$ and


$s_2$. Returns $0$ if
strcmp(s1, equal, or non-zero if (strcmp(s1,
Comparison
s2) otherwise s2) == 0)
(lexicographical
order).

Returns the number


of characters in the len =
Length strlen(s)
string, excluding the strlen(s)
null terminator (\0).

Searches for the first


Searching strchr(s, occurrence of a ptr = strchr(s,
(Char) char) specified character 'a')
within the string s.

Searches for the first


ptr =
Searching occurrence of string
strstr(s1, s2) strstr(s1,
(Substr) $s_2$ within string
"sub")
$s_1$.

39. Write a Program Swapping of Two Numbers using Pointers.


Swapping two numbers using pointers requires passing the addresses of the
variables to a function, allowing the function to modify the original values (Call by
Reference).

#include <stdio.h>

// Function accepts two pointers to integers

void swap_by_pointer(int *a, int *b) {

// *a and *b are used to access the VALUE stored at the address

int temp;

// 1. Store the value of the variable pointed to by 'a'

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("x = %d, y = %d\n", x, y);

// Call the function, passing the ADDRESSES (&) of x and y


swap_by_pointer(&x, &y);

printf("\nAfter swapping:\n");

printf("x = %d, y = %d\n", x, y); // x and y are permanently swapped

return 0;

40. Explain the Memory Representation of Structure and Union.

Both structures and unions are composite data types, but their memory
management is fundamentally different.

Structure Memory Representation (struct)

 Principle: Separate storage for every member.

 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

};

// Total size (without padding): 1 + 4 = 5 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.

Union Memory Representation (union)

 Principle: Shared storage for all members.

 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

int i; // 4 bytes (Largest member)

};

// Total size: 4 bytes (size of 'i').

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.

41. Explain with Example the Categories of Functions.

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

Pre-defined functions available


Library printf(), scanf(), sqrt(),
in C's standard library (must
Functions strlen()
include a header file).

Functions created by the calculate_area(),


User-Defined
programmer to perform specific swap_numbers(),
Functions
tasks required by the program. main()

2. Based on Arguments and Return Value (Four Categories)

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

2. No Function computes a value


Argument, using internal data and
No Yes
With Return returns it. float
Value get_pi_value(void)

Function accepts data,


3. With
processes it, and performs
Argument,
Yes No an action (e.g., printing or
No Return
modifying a pointer). void
Value
display(int num)

4. With Function accepts data,


Argument, performs a calculation, and
Yes Yes
With Return returns the result. (Most
Value common)

Example (Category 4): With Argument, With Return Value

#include <stdio.h>

// Function Category: With Argument (a, b), With Return Value (int)

int find_max(int a, int b) {


if (a > b) {

return a;

} else {

return b;

int main() {

int max_val = find_max(15, 25); // Function Call

printf("Maximum is: %d\n", max_val); // Output: 25

return 0;

You might also like