Major Module 2 + Questions
Major Module 2 + Questions
An operator in C can be defined as the symbol that helps us to perform some specific
mathematical, relational, bitwise, conditional, or logical computations on values and variables.
The values and variables used with operators are called operands. So we can say that the
operators are the symbols that perform operations on operands.
Types of Operators in C
1. Arithmetic Operations in C
Operator Description
S. No. Symbol
+ Plus Adds two numeric values.
1
– Minus Subtracts right operand from left operand.
2
* Multiply Multiply two numeric values.
3
/ Divide Divide two numeric values.
4
Returns the remainder after diving the left operand
% Modulus with the right operand.
5
#include <stdio.h>
int main()
int a = 25, b = 5;
return 0;
2. Relational Operators in C
The relational operators in C are used for the comparison of the two operands. All these
operators are binary operators that return true or false values as the result of comparison.
Operator Description
S. No. Symbol
Returns true if the left operand is less than the
< Less than
right operand. Else false
1
Returns true if the left operand is greater than the
> Greater than
right operand. Else false
2
Less than or Returns true if the left operand is less than or equal
<= equal to to the right operand. Else false
3
Greater than or Returns true if the left operand is greater than or
>= equal to equal to right operand. Else false
4
== Equal to Returns true if both the operands are equal.
5
!= Not equal to Returns true if both the operands are NOT equal.
6
Example of C Relational Operators
#include <stdio.h>
int main()
Logical Operators are used to combine two or more conditions/constraints or to complement the
evaluation of the original condition in consideration. The result of the operation of a logical
operator is a Boolean value either true or false.
Operator Description
S. No. Symbol Syntax
Returns true if both the
&& Logical AND a && b
operands are true.
1
Returns true if both or any of
|| Logical OR a || b
the operand is true.
2
Returns true if the operand is
! Logical NOT !a
false.
3
In C programming, any non-zero and non-null values are considered true, with zero being the only
false value.
#include <stdio.h>
int main()
{ Output
printf("a || b : %d\n", a || b); (25 and 5 are non –zero values (True), so
&& and || give True output, ! give false
printf("!a: %d\n", !a);
output)
return 0;
4. Bitwise Operators in C
The Bitwise operators are used to perform bit-level operations on the operands. The operators
are first converted to bit-level and then the calculation is performed on the operands.
Operator Description
S. No. Symbol Syntax
Performs bit-by-bit AND operation
& Bitwise AND a & b
and returns the result.
1
Performs bit-by-bit OR operation and
| Bitwise OR a | b
returns the result.
2
Performs bit-by-bit XOR operation
^ Bitwise XOR a ^ b
and returns the result.
3
Bitwise First Flips all the set and unset bits on the
~ ~a
Complement number.
4
Shifts the number in binary form by
Bitwise
<< one place in the operation and returns a << b
Leftshift
the result.
5
Shifts the number in binary form by
Bitwise
>> one place in the operation and returns a >> b
Rightshilft
the result.
6
Example of Bitwise Operators
#include <stdio.h>
Output
int main()
a & b: 1
{
a | b: 29
int a = 25, b = 5;
a ^ b: 28
// using operators and printing results
~a: -26
printf("a & b: %d\n", a & b);
a >> b: 0
printf("a | b: %d\n", a | b);
a << b: 800
printf("a ^ b: %d\n", a ^ b);
return 0;
5. Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator is a
value. The value on the right side must be of the same data type as the variable on the left side
otherwise the compiler will raise an error.
The assignment operators can be combined with some other operators in C to provide multiple
operations using single operator. These operators are called compound operators.
Operator Description
S. No. Symbol Syntax
Assign the value of the right
= Simple Assignment a = b
operand to the left operand.
1
Add the right operand and left
+= Plus and assign operand and assign this value a += b
to the left operand.
2
Subtract the right operand and
-= Minus and assign left operand and assign this a -= b
value to the left operand.
3
Multiply the right operand and
*= Multiply and assign left operand and assign this a *= b
value to the left operand.
4
Divide the left operand with
/= Divide and assign the right operand and assign a /= b
this value to the left operand.
5
Assign the remainder in the
%= Modulus and assign division of left operand with a %= b
6 the right operand to the left
int main() a = b: 5
{ a += b: 10
int a = 25, b = 5; a -= b: 5
a <<= b: 0
Praveen Kumar P K, UIT Kollam
printf("a %%= b: %d\n", a %= b);
return 0;
6. Other Operators
It is a compile-time unary operator which can be used to compute the size of its operand.
The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
Basically, the sizeof the operator is used to compute the size of the variable or datatype.
Syntax
sizeof (operand)
Syntax
Member operators are used to reference individual members of classes, structures, and unions.
structure_variable . member;
Position of the In for loop, all the In while and do while loop, they are placed in
statements: three statements are different position.
placed in one position
1. Initialization
2. test-expression
3. update-
for while(test-expression) do
{
( initialization-exp; {
test-expression(s); body-of-the-loop;
body-of-the-loop;
update-expression(s) ) update-expression(s);
Syntax of Loops update-expression(s);
}
{ }while (test-
expression);
body-of-the-loop ;
Both loops i.e. for loop and while loop are entry do while loop is an exit
controlled loop, means condition is checked controlled loop, means
Which one is Entry
first and if the condition is true then the body means that condition
Controlled Loop and
of the loop will executes. is placed after the
Which one is Exit
body of the loop and
Controlled Loop ?
is evaluated before
exiting from the loop.
We can also have nested for loops, i.e one for loop inside another for loop. nesting is often used
for handling multidimensional arrays.
Syntax:
Example:
#include<stdio.h>
#include<conio.h>
void main( )
int i,j;
for(i=1;i<5;i++)
printf("\n");
for(j=i;j>0;j--)
printf("%d ",j);
getch();
21
321
4321
54321
Break Continue
break statement takes the control to the continue statement takes the control to the
ouside of the loop beginning of the loop..
it is also used in switch statement. This can be used only in loop statements.
Always associated with if condition in loops. This is also associated with if condition.
Formatted I/O functions are used to take various inputs from the user and display multiple
outputs to the user. These types of I/O functions can help to display the output to the user in
different formats using the format specifiers. These I/O supports all data types like int, float,
char, and many more.
These functions are called formatted I/O functions because we can use format specifiers in
these functions and hence, we can format these functions according to our needs.
S Format
Type Description
NO. Specifier
5 %ld long int Used for I/O long signed integer value
1. printf()
2. scanf()
3. sprintf()
4. sscanf()
printf()
printf() function is used in a C program to display any value like float, integer, character, string,
etc on the console screen. It is a pre-defined function that is already declared in the
stdio.h(header file).
Example
int a=20;
printf("%d", a);
Syntax 2:
scanf():
scanf() function is used in the C program for reading or taking any value from the keyboard by
the user, these values can be of any data type like integer, float, character, string, and many
more. This function is declared in stdio.h(header file), that’s why it is also a pre-defined
function. In scanf() function we use &(address-of operator) which is used to store the variable
value on the memory location of that variable.
Syntax:
Example
int num1;
scanf("%d", &num1);
Unformatted I/O functions are used only for character data type or character array/string
and cannot be used for any other datatype. These functions are used to read single input from
the user at the console and it allows to display the value at the console.
These functions are called unformatted I/O functions because we cannot use format specifiers
in these functions and hence, cannot format these functions according to our needs.
1. getch()
2. getche()
Praveen Kumar P K, UIT Kollam
3. getchar()
4. putchar()
5. gets()
6. puts()
7. putch()
getch()
getch() function reads a single character from the keyboard by the user but doesn’t display
that character on the console screen and immediately returned without pressing enter key. This
function is declared in conio.h(header file). getch() is also used for hold the screen.
Syntax:
getch();
or
variable-name = getch();
Example:
char c;
c=getch();
getche()
getche() function reads a single character from the keyboard by the user and displays it on the
console screen and immediately returns without pressing the enter key. This function is
declared in conio.h(header file).
Syntax
getche();
or
variable_name = getche();
Example:
char c;
c=getch();
getchar()
Syntax:
Variable-name = getchar();
Example:
#include <conio.h>
#include <stdio.h>
int main()
char ch;
ch = getchar();
printf("%c", ch);
return 0;
Output:
putchar()
The putchar() function is used to display a single character at a time by passing that character
directly to it or by passing a variable that has already stored a character. This function is
declared in stdio.h(header file)
putchar(variable_name);
Example:
#include <conio.h>
#include <stdio.h>
int main()
char ch;
// Reads a character
ch = getchar();
putchar(ch);
return 0;
Output:
gets()
gets() function reads a group of characters or strings from the keyboard by the user and these
characters get stored in a character array. This function allows us to write space-separated
texts or strings. This function is declared in stdio.h(header file).
Syntax:
char str[length of string in number]; //Declare a char type variable of any length
gets(str);
#include <conio.h>
#include <stdio.h>
int main()
char name[50];
gets(name);
return 0;
Output:
puts()
Syntax:
puts(identifier_name );
Example:
#include <stdio.h>
int main()
{
Praveen Kumar P K, UIT Kollam
char name[50];
gets(name);
// Displays string
puts(name);
return 0;
Output:
putch()
putch() function is used to display a single character which is given by the user and that
character prints at the current cursor location. This function is declared in conio.h(header file)
Syntax:
putch(variable_name);
Example:
#include <conio.h>
#include <stdio.h>
int main()
char ch;
ch = getch();
putch(ch);
return 0;
Output:
These functions allow us to take input These functions do not allow to take
1 or display output in the user’s desired input or display output in user desired
format. format.
These are used for storing data more These functions are not more user-
3
user friendly friendly.
printf(), scanf, sprintf() and sscanf() getch(), getche(), gets() and puts(), are
5
are examples of these functions. some examples of these functions.
There are two types of arrays based on the number of dimensions it has. They are as follows:
The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have only one
dimension.
Syntax of 1D Array in C
array_name [size];
Example of 1D Array in C
#include <stdio.h>
int main()
arr[i] = i * i - 2 * i + 1;
for (int i = 0; i < 5; i++) { // printing 1d array by traversing using for loop
return 0;
Output
Elements of Array: 1 0 1 4 9
#include <stdio.h>
int main()
char arr[10] = { 'U', 'I', 'T', 'K', 'o', 'l', 'l', 'a', 'm', '\0' };// creating array of
character
while (arr[i]) {
printf("%c", arr[i++]);
return 0;
In this program, we will use scanf() and print() function to take input and print output for the
array.
#include <stdio.h>
int main()
for (int i = 0; i < 5; i++) { // taking input to array elements one by one
scanf("%d", &arr[i]);
return 0;
Example 2
#include <stdio.h>
int main()
scanf("%d", &arr[i]);
max = arr[0];
max = arr[i];
return 0;
Properties of Arrays in C
It is very important to understand the properties of the C array so that we can avoid bugs while
using it. The following are the main properties of an array in C:
1. Fixed Size
The array in C is a fixed-size collection of elements. The size of the array must be known at the
compile time and it cannot be changed once it is declared.
We can only store one type of element in an array. There is no restriction on the number of
elements but the type of all of these elements must be the same.
3. Indexing in Array
The array index always starts with 0 in C language. It means that the index of the first element
of the array will be 0 and the last element will be N – 1.
4. Dimensions of an Array
A dimension of an array is the number of indexes required to refer to an element in the array.
It is the number of directions in which you can grow the array size.
5. Contiguous Storage
All the elements in the array are stored continuously one after another in the memory. It is one
of the defining properties of the array in C which is also the reason why random access is
possible in the array.
6. Random Access
The array in C provides random access to its element i.e we can get to a random element at any
index of the array in constant time complexity just by using its index number.
There is no index out-of-bounds checking in C/C++, for example, the following program compiles
fine but may produce unexpected output when run.
Multidimensional Arrays
In C programming, you can create an array of arrays. These arrays are known as
multidimensional arrays. For example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array
as a table with 3 rows and each row has 4 columns.
float y[2][4][3];
#include <stdio.h>
int main()
int i, j, m, n;
int matrix[10][20];
scanf("%d", &m);
scanf("%d", &n);
scanf("%d", &matrix[i][j]);
printf("%d\t", matrix[i][j]);
printf("\n");
return 0;
#include <stdio.h>
int main() {
scanf("%d", &r);
scanf("%d", &c);
scanf("%d", &a[i][j]);
scanf("%d", &b[i][j]);
printf("\n");
return 0;
Output
-2 8 7
10 8 6
#include<stdio.h>
#include<conio.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
clrscr();
scanf("%d",&r);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&b[i][j]);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
mul[i][j]=0;
for(k=0;k<c;k++)
mul[i][j]+=a[i][k]*b[k][j];
for(i=0;i<r;i++)
for(j=0;j<c;j++)
printf("%d\t",mul[i][j]);
printf("\n");
return 0;
Output:
111
222
333
111
222
333
666
12 12 12
18 18 18
C supports a derived data type known as array that can be used to handle large amounts of data
(multiple values) at a time.
Definition:
Or
An array is a collection of data that holds fixed number of values of same type.
Or
Array is a collection or group of elements (data). All the elements of array are
homogeneous (similar). It has contiguous memory location.
Or
An array is a data structured that can store a fixed size sequential collection of elements
of same data type.
Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So
it will be typical and hard to manage. For example we can not access the value of these variables
with only 1 or 2 lines of code.
Another way to do this is array. By using array, we can access the elements easily. Only few
lines of code is required to access the elements of array.
Advantage of C Array
2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array
easily.
3) Easy to sort data: To sort the elements of array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of Array
Declaration of an Array
The C arrays are static in nature, i.e., they are allocated memory at the compile time.
Example
C Array Initialization
Initialization in C is the process to assign some initial value to the variable. When the array is
declared or allocated memory, the elements of the array contain some garbage value. So, we
need to initialize the array to some meaningful value. There are multiple ways in which we can
initialize an array in C.
In this method, we initialize the array along with its declaration. We use an initializer list to
initialize multiple elements of the array. An initializer list is the list of values enclosed within
braces { } separated by a comma.
Example
If we initialize an array using an initializer list, we can skip declaring the size of the array as
the compiler can automatically deduce the size of the array in these cases. The size of the
array in these cases is equal to the number of elements present in the initializer list as the
compiler can automatically deduce the size of the array.
Example
The size of the above arrays is 5 which is automatically deduced by the compiler.
We initialize the array after the declaration by assigning the initial value to each element
individually. We can use for loop, while loop, or do-while loop to assign the value to each element
of the array.
array_name[i] = valuei;
Example
#include <stdio.h>
int main()
int arr1[] = { 1, 2, 3, 4, 5 };
float arr2[5];
return 0;
We can access any element of an array in C using the array subscript operator [ ] and the index
value i of the element.
array_name [index];
One thing to note is that the indexing in the array always starts with 0, i.e., the first element is
at index 0 and the last element is at N – 1 where N is the number of elements in the array.
Example
int arr[5] = { 15, 25, 35, 45, 55 }; // array declaration and initialization
printf("Element at arr[2]: %d\n", arr[2]); // accessing element at index 2 i.e 3rd element
printf("Element at arr[0]: %d", arr[0]); // accessing element at index 0 i.e first element
We can update the value of an element at the given index i in a similar way to accessing an
element by using the array subscript operator [ ] and assignment operator =.
array_name[i] = new_value;
Example
int arr[5] = { 15, 25, 35, 45, 55 }; // array declaration and initialization
C Array Traversal
Traversal is the process in which we visit every element of the data structure. For C array
traversal, we use loops to iterate through each element of the array.
array_name[i];
Example
int arr[5] = { 10, 20, 30, 40, 50 }; // array declaration and initialization
Output
switch(expression){
case value1:
//code to be executed;
break;//optional
case value2:
//code to be executed;
break;//optional
......
default:
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. The break statement is
optional. If omitted, execution will continue on into the next case. The flow of control will
fall through to subsequent cases until a break is reached.
Step 2: The evaluated value is matched against all the present cases.
Step 3A: If the matching case value is found, the associated code is executed.
Praveen Kumar P K, UIT Kollam
Step 3B: If the matching code is not found, then the default case is executed if present.
Step 4A: If the break keyword is present in the case, then program control breaks out of
the switch statement.
Step 4B: If the break keyword is not present, then all the cases after the matching case
are executed.
Example
#include<stdio.h>
int main()
int number;
printf("enter a number:");
scanf("%d",&number);
switch(number)
case 50:
case 100:
default:
return0;
Output
enter a number:10
number is equal to 10
number is equal to 50
Output
enter a number:50
number is equal to 50
Example 2: C Program to print the day of the week using a switch case.
#include <stdio.h>
int main()
scanf(“%d”,&day);
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("Invalid Input");
return 0;
The conditional statements (also known as decision control structures) such as if, if else,
switch, etc. are used for decision-making purposes in C programs.
They are also known as Decision-Making Statements and are used to evaluate one or more
conditions and make the decision whether to execute a set of statements or not.
• if Statement
• if-else Statement
• Nested if Statement
• if-else-if Ladder
• switch Statement
• Conditional Operator
• Jump Statements:
o break
o continue
o goto
o return
The if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is
true then a block of statements is executed otherwise not.
Syntax of if Statement
if(condition)
// Statements to execute if
// condition is true
Here, the condition after evaluation will be either true or false. C if statement accepts boolean
values – if the value is true then it will execute the block of statements below it otherwise not.
If we do not provide the curly braces ‘{‘ and ‘}’ after if(condition) then by default if statement
will consider the first immediately below statement to be inside its block.
Flowchart of if Statement
Example of if in C
#include<stdio.h>
int main(){
int number=0;
scanf("%d",&number);
if(number%2==0){
return 0;
if-else Statement
The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t. But what if we want to do something else when the
condition is false? Here comes the C else statement. We can use the else statement with the if
statement to execute a block of code when the condition is false. The if-else statement
consists of two blocks, one for false expression and one for true expression.
// condition is true
else
// condition is false
Example of if-else
#include<stdio.h>
int main(){
int number=0;
scanf("%d",&number);
if(number%2==0){
else{
return 0;
if (condition1)
if (condition_2)
// statement 1
else
// Statement 2
// statement 3
else
// Statement 4
#include <stdio.h>
int main() {
// outer if statement
// inner if...else
else
else {
// inner if...else
else
return 0;
if-else-if Ladder
The if else if statements are used when the user has to decide among multiple options. The C if
statements are executed from the top down. As soon as one of the conditions controlling the if
is true, the statement associated with that if is executed, and the rest of the C else-if ladder
is bypassed. If none of the conditions is true, then the final else statement will be executed. if-
else-if ladder is similar to the switch statement.
if (condition)
statement;
else if (condition)
statement;
else
statement;
#include <stdio.h>
int main() {
else
return 0;
2-MARK QUESTIONS
int a = 4, b = 2, c;
c = a * b + 6 / 2;
printf("%d", c);
A: c = 4 * 2 + 6 / 2 = 8 + 3 = 11
int x = 10, y = 5;
o Arithmetic Expression
o Relational Expression
o Logical Expression
A:
o Arithmetic: a + b
o Relational: x <= y
int a = 10, b = 5;
7-MARK QUESTIONS
1. Q: Analyze and evaluate the following C expression step-by-step using operator precedence:
printf("%d", result);
A:
• Step 1: b * c = 10 * 15 = 150
• Step 4: b - a = 10 - 5 = 5
• Output: 1
2. Q: Write a C program segment that uses arithmetic, relational, and logical operators. Then evaluate its
output.
#include <stdio.h>
int main() {
int a = 8, b = 3, c = 5;
printf("%d", result);
return 0;
A:
• Output: 1
A:
• Relational operators: compare two values (==, !=, >, <, >=, <=)
Example: a > b
int a = 4, b = 6, c = 2, d = 3;
A:
• Step 1: b * c = 6 * 2 = 12
• Step 2: a + 12 = 4 + 12 = 16
• Step 4: d == 3 → true
• Final result = 1
#include <stdio.h>
int main() {
int a = 2, b = 3, c = 4;
int result1 = a + b * c;
int result2 = (a + b) * c;
return 0;
A:
• result1 = a + b * c = 2 + 3 * 4 = 2 + 12 = 14
• result2 = (a + b) * c = (2 + 3) * 4 = 5 * 4 = 20
• Output: 14 20
1-MARK QUESTIONS
5. Identify which loop checks the condition after executing the body once.
➤ do-while loop
int i = 0;
while (i < 1) {
printf("Hi");
i++;
➤ Output: Hi
do {
// body
} while(condition);
2-MARK QUESTIONS
1. Explain the difference between while and do-while loops with examples.
➤ while checks the condition first, then executes.
➤ do-while executes once before checking the condition.
Example:
printf("Positive");
else
printf("Negative");
int i = 0;
while (i < 3) {
printf("%d", i);
i++;
int i = 0;
while (i < 3) {
if (i == 1) continue;
printf("%d", i);
i++;
if (i == 3) break;
// Output: 1 2
switch(x) {
default: printf("Other");
1. Write a program in C using for loop to print the multiplication table of a number entered by the user.
Answer:
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
return 0;
2. Analyze the following code and predict its output. Explain how control statements are used:
int i = 0;
while (i < 5) {
if (i == 3) {
i++;
continue;
i++;
Answer:
• Output: 0 1 2 4
3. Evaluate the use of switch vs if-else for menu-driven programs. When should one be preferred over the other?
Answer:
• switch is cleaner and more readable when dealing with multiple fixed options (like menu choices).
• Prefer switch for discrete, constant choices. Use if-else for range or logical comparisons.
4. Write a program using a do-while loop that takes numbers as input and adds them until the user enters 0. Then,
display the sum.
Answer:
#include <stdio.h>
int main() {
do {
scanf("%d", &num);
sum += num;
return 0;
5. Analyze the flow of the following nested loop and explain the use of break:
if (j == 2)
break;
Answer:
• Output:
11
21
31
6. Design a menu-driven calculator using switch and loop it until the user chooses to exit.
Answer:
#include <stdio.h>
int main() {
int choice, a, b;
do {
scanf("%d", &choice);
if (choice == 5) break;
printf("Enter two numbers: ");
switch (choice) {
case 4:
break;
} while (1);
return 0;
}
1 Mark Questions
Answer:
Unformatted I/O refers to basic input/output operations like getchar(), putchar(), gets(), and puts() that do not allow
formatting of data.
Answer:
Two formatted I/O functions are: printf() and scanf().
2 Mark Questions
Q3. Differentiate between formatted and unformatted I/O with one example of each.
Answer:
Formatted I/O allows control over data format during input/output (e.g., printf("%d", a);), whereas unformatted I/O does
not (e.g., gets(str);).
Answer:
Format specifiers are used in printf() to indicate the type of data to be printed, such as %d for integers, %f for floats, %s
for strings, allowing precise formatting of output.
7 Mark Question
Answer:
#include <stdio.h>
int main() {
char name[50];
int roll;
float marks;
// Unformatted I/O
gets(name); // unformatted
return 0;
Analysis:
• gets() takes input without formatting but can lead to buffer overflow.
• scanf() and printf() allow specific format controls like decimal precision.
1 Mark Questions
Answer:
An array is a collection of elements of the same data type stored in contiguous memory locations.
Answer:
1. One-dimensional array
2 Mark Questions
Answer:
• A two-dimensional array stores elements in rows and columns (e.g., int matrix[2][3];).
Example:
int arr[3] = {1, 2, 3};
int matrix[2][2] = {{1, 2}, {3, 4}};
Answer:
An array can be initialized during declaration by providing values in curly braces.
Example:
7 Mark Question
Q5. Write a C program to input 5 student marks into a one-dimensional array, calculate the average, and analyze how
arrays simplify the process.
Answer:
#include <stdio.h>
int main() {
int marks[5], i;
// Input marks
scanf("%d", &marks[i]);
sum += marks[i];
average = sum / 5;
// Output average
return 0;
Analysis:
• Using arrays allows us to handle multiple values with a single variable name (marks[]) and loop through them
efficiently.
• It avoids repetitive code and simplifies operations like summing and averaging.
• Without arrays, we would need separate variables (mark1, mark2, ...) and more lines of code, making the
program less readable and maintainable.
1 Mark Questions
Answer:
A multi-dimensional array is an array of arrays, such as a 2D array with rows and columns.
1. Traversal
2. Searching
2 Mark Questions
Q5. Explain how array elements are stored in memory.
Answer:
Array elements are stored in contiguous memory locations, with the first element at the base address and subsequent
elements stored sequentially.
7 Mark Questions
Q9. Write a program to find the largest number in a one-dimensional array of 6 integers.
Answer:
#include <stdio.h>
int main() {
// Input
scanf("%d", &arr[i]);
max = arr[0];
max = arr[i];
return 0;
Q10. Write a C program to store and print a 3x3 matrix. Then analyze how multi-dimensional arrays simplify working
with tabular data.
Answer:
#include <stdio.h>
int main() {
int matrix[3][3], i, j;
// Input
scanf("%d", &matrix[i][j]);
// Output
printf("Matrix is:\n");
printf("\n");
return 0;
Analysis:
• Multi-dimensional arrays allow storing tabular data (rows & columns) logically.
• They reduce complexity by providing a structure that maps directly to tables or grids.
Answer:
• Cannot use dynamic memory allocation or resizing like in dynamic structures (e.g., linked lists).
1 MARK QUESTIONS
6 Recall the purpose of \0 in strings. (Recall) It marks the end of the string.
2 MARK QUESTIONS
Explain the difference between character and A character stores one symbol (e.g., 'A'), while a string is an
1
string data types in C. (Explain) array of characters ending with \0.
Differentiate between gets() and scanf() for strings. gets() reads a line with spaces; scanf() stops at space or
2
(Differentiate) newline.
4 Describe the use of strlen() function. (Describe) It returns the length of the string excluding the null character.
7 MARK QUESTIONS
Q1. Write a C program to input a string and count the number of vowels in it.
Answer:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int i, vowels = 0;
gets(str);
for(i = 0; str[i] != '\0'; i++) {
char c = str[i];
vowels++;
return 0;
Q2. Write a program to concatenate two strings without using strcat() and analyze the difference between manual
concatenation and using the library function.
Answer:
#include <stdio.h>
int main() {
int i = 0, j = 0;
gets(str1);
gets(str2);
while(str2[j] != '\0') {
str1[i] = str2[j];
i++; j++;
}
str1[i] = '\0';
return 0;
Analysis:
• Manual concatenation gives control but is prone to buffer overflow if array size is insufficient.
• strcat() automatically handles appending but also doesn’t check array bounds.
• Library functions are safer when used properly, but developers must manage memory size.
#include <stdio.h>
#include <string.h>
int main() {
strcpy(str1, str2);
strcat(str1, "All");
printf("%s\n", str1);
return 0;
• No overflow here, but if strings were longer, it could cause memory corruption.
• Output: ThereAll
Q4. Write a C program that compares two strings using strcmp() and also manually, and then analyze the difference.
Answer:
#include <stdio.h>
#include <string.h>
int main() {
int i, flag = 0;
gets(str1);
gets(str2);
// Manual comparison
if(str1[i] != str2[i]) {
flag = 1;
break;
if(flag == 0)
else
// Using strcmp()
if(strcmp(str1, str2) == 0)
else
return 0;
Analysis:
• strcmp() simplifies code and is optimized, but developers must know how it returns values.
Loops in programming are used to repeat a block of code until the specified condition is met. A
loop statement allows programmers to execute a statement or group of statements multiple times
without repetition of code.
1. Entry Controlled loops: In Entry controlled loops the test condition is checked before
entering the main body of the loop. For Loop and While Loop is Entry-controlled loops.
2. Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the end
of the loop body. The loop body will execute at least once, irrespective of whether the
condition is true or false. do-while Loop is Exit Controlled loop.
• Loops allow the user to execute the same set of statements repeatedly without writing the
same code multiple times.
• It saves time and effort and increases the efficiency.
• It reduces the chance of getting errors during compilation.
• Loop makes the code readable and easier to understand, especially when dealing with
complex logic or large data sets.
• It promotes code reusability.
• Loops help traverse data structures like arrays or linked lists
Types of Loop in C
1. for loop
2. while loop
Praveen Kumar P K, UIT Kollam
3. do while loop
for loop in C
A for loop is a control structure that enables a set of instructions to get executed for a specified
number of iterations. It is an entry-controlled loop.
Syntax
//code to be executed
#include <stdio.h>
int main() {
int i;
printf("%d\n", i);
return 0;
The above code prints the numbers from 1 to 10 using a for loop in C.
• We know it will take 10 iterations to print 10 numbers so, we have used the for loop.
• i is initialized to 1.
• The condition i<=10 will be checked. It is true, therefore i i.e. 1 gets printed.
• Then i increments to 1 again the condition, i<=10 is evaluated.
While Loop
While loop does not depend upon the number of iterations. In for loop the number of iterations
was previously known to us but in the While loop, the execution is terminated on the basis of the
test condition. If the test condition will become false then it will break from the while loop else
body will be executed.
Syntax:
initialization_expression;
update_expression;
If the test condition inside the () becomes true, the body of the loop executes else loop
terminates without execution. The process repeats until the test condition becomes false.
#include <stdio.h>
int main()
int i = 1;
printf("%d\n", i);
i++;
return 0;
do-while Loop
It is an exit-controlled loop. The do-while loop is similar to a while loop but the only difference
lies in the do-while loop test condition which is tested at the end of the body. In the do-while
loop, the loop body will execute at least once irrespective of the test condition.
Syntax:
initialization_expression;
do
update_expression;
#include <stdio.h>
int main()
int i = 0;
do {
printf("%d\n", i+1);
i++;
return 0;
Loop control statements in C programming are used to change execution from its normal sequence.
• break statement the break statement is used to terminate the switch and loop
statement. It transfers the execution to the statement immediately following the loop or
switch.
• continue statement continue statement skips the remainder body and immediately
resets its condition before reiterating it.
break
break;
The break statement is almost always used with if...else statement inside the loop.
int i;
if (i == 4) {
break;
printf("%d\n", i);
continue
The continue statement skips the current iteration of the loop and continues with the next
iteration. Its syntax is:
continue;
The continue statement is almost always used with the if...else statement.
Example
int i;
if (i == 4) {
continue;
printf("%d\n", i);
The conditional operator is used to add conditional code in our program. It is similar to the if-
else statement. It is also known as the ternary operator as it works on three operands.
//C Program To Find Greatest Of Two Numbers Using Conditional Operator/Ternary Operator
#include<stdio.h>
#include<conio.h>
void main()
int a,b,c;
clrscr();
scanf("%d",&a);
Praveen Kumar P K, UIT Kollam
printf("\n Enter Second Number : ");
scanf("%d",&b);
printf("\n %d is Greater",c);
getch();
Jump Statements in C
These statements are used in C for the unconditional flow of control throughout the functions
in a program. They support four types of jump statements:
A) break
This loop control statement is used to terminate the loop. As soon as the break statement is
encountered from within a loop, the loop iterations stop there, and control returns from the
loop immediately to the first statement after the loop.
Syntax of break
break;
Basically, break statements are used in situations when we are not sure about the actual number
of iterations for the loop or we want to terminate the loop based on some condition.
if (arr[i] == key) {
(i + 1));
break;
B) continue
This loop control statement is just like the break statement. The continue statement is
opposite to that of the break statement, instead of terminating the loop, it forces to execute
the next iteration of the loop.
As the name suggests the continue statement forces the loop to continue or execute the next
iteration. When the continue statement is executed in the loop, the code inside the loop
following the continue statement will be skipped and the next iteration of the loop will begin.
Syntax of continue
continue;
Flowchart of Continue
Example of continue
continue;
else
C) goto
The goto statement in C also referred to as the unconditional jump statement can be used to
jump from one point to another within a function.
Syntax of goto
Syntax1 |
goto label;
label:
Syntax2
label:
goto label;
In the above syntax, the first line tells the compiler to go to or jump to the statement marked
as a label. Here, a label is a user-defined identifier that indicates the target statement. The
statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also
appear before the ‘goto label;’ statement in the above syntax.
int main() 1 2 3 4 5 6 7 8 9 10
int n = 1;
label:
n++;
if (n <= 10)
goto label;
return 0;
D) return
The return in C returns the flow of the execution to the function from where it is called. This
statement does not mandatorily need any conditional statements. As soon as the statement is
executed, the flow of the program stops immediately and returns the control from where it was
called. The return statement may or may not return anything for a void function, but for a non-
void function, a return value must be returned.
Syntax of return
return [expression];
Logical OR ( || )
Logical NOT ( ! )
The logical AND operator (&&) returns true only if both operands are non-zero. Otherwise, it
returns false (0). The return type of the result is int. Below is the truth table for the logical
AND operator.
Syntax
Example
#include <stdio.h>
int main()
else {
2. Logical OR Operator ( || )
The logical OR operator returns true if any one of the operands is non-zero. Otherwise, it
returns false i.e., 0 as the value. Below is the truth table for the logical OR operator.
Syntax
(operand_1 || operand_2)
Example
#include <stdio.h>
int main()
{
Output
int a = -1, b = 20;
Any one of the given value is greater than 0
if (a > 0 || b > 0) {
else {
return 0;
If the given operand is true then the logical NOT operator will make it false and vice-versa.
Below is the truth table for the logical NOT operator.
Syntax
Example
#include <stdio.h>
int main()
// it to false
else {
return 0;
The precedence of operators determines which operator is executed first if there is more than
one operator in an expression.
int x = 5 – 17 * 6;
In C, the precedence of * is higher than - and =. Hence, 17 * 6 is evaluated first. Then the
expression involving - is evaluated as the precedence of - is higher than that of =.
The following tables list the C operator precedence from highest to lowest and the associativity
for each of the operators:
Operator
Precedence Description Associativity
Parentheses (function
()
call)
Array Subscript (Square
[]
Brackets)
1 . Dot Operator Left-to-Right
Structure Pointer
->
Operator
Postfix increment,
++ , —
decrement
Prefix increment,
++ / —
decrement
+ / – Unary plus, minus
Logical NOT, Bitwise
! , ~
2 complement Right-to-Left
(type) Cast Operator
* Dereference Operator
& Addressof Operator
sizeof Determine size in bytes
Multiplication, division,
3 *,/,% Left-to-Right
modulus
4 +/- Addition, subtraction Left-to-Right
Bitwise shift left, Bitwise
5 << , >> Left-to-Right
shift right
Relational less than, less
< , <=
6 than or equal to Left-to-Right
> , >= Relational greater than,
greater than or equal to
Relational is equal to, is
7 == , != Left-to-Right
not equal to
8 & Bitwise AND Left-to-Right
9 ^ Bitwise exclusive OR Left-to-Right
10 | Bitwise inclusive OR Left-to-Right
11 && Logical AND Left-to-Right
12 || Logical OR Left-to-Right
13 ?: Ternary conditional Right-to-Left
= Assignment
Addition, subtraction
+= , -=
assignment
Multiplication, division
*= , /=
assignment
14 Modulus, bitwise AND Right-to-Left
%= , &=
assignment
Bitwise exclusive,
^= , |=
inclusive OR assignment
Bitwise shift left, right
<<=, >>=
assignment
comma (expression
15 , Left-to-Right
separator)
Operator precedence determines which operation is performed first in an expression with more
than one operator with different precedence.
10 + 20 * 30
The expression contains two operators, + (plus), and * (multiply). According to the given table,
the * has higher precedence than + so, the first evaluation will be
10 + (20 * 30)
10 + 600
610
Operator Associativity
Operator associativity is used when two operators of the same precedence appear in an
expression. Associativity can be either from Left to Right or Right to Left.
100 / 5 % 2
Both / (division) and % (Modulus) operators have the same precedence, so the order of
evaluation will be decided by associativity.
According to the given table, the associativity of the multiplicative operators is from Left to
Right. So,
(100 / 5) % 2
20 % 2
Here, we have four operators, in which the / and * operators have the same precedence
but have higher precedence than the + and – operators. So, according to the Left-to-Right
associativity of / and *, / will be evaluated first.
= 100 + 20 - 3 * 10
= 100 + 20 - 30
= 120 - 30
exp = 120 - 30
= 90
Associativity is only used when there are two or more operators of the same precedence.
All operators with the same precedence have the same associativity.
Precedence and associativity of postfix ++ and prefix ++ are different.
Comma has the least precedence among all operators.
Increment and Decrement Operators in C
The increment ( ++ ) and decrement (--) operators in C are unary operators for incrementing and
decrementing the numeric values by 1 respectively. The incrementation and decrementation are
one of the most frequently used operations in programming for looping, array traversal, pointer
arithmetic, and many more.
Increment Operator in C
As prefix
++m
As postfix
m++
Both pre-increment and post-increment increase the value of the variable but there is a little
difference in how they work.
In pre-increment, the increment operator is used as the prefix. Also known as prefix increment,
the value is incremented first according to the precedence and then the less priority operations
are done.
Example
result = ++var1;
var = var + 1;
result = var;
In post-increment, the increment operator is used as the suffix of the operand. The increment
operation is performed after all the other operations are done. It is also known as postfix
increment.
result = var1++;
result = var;
var = var + 1;
Decrement Operator in C
The decrement operator is used to decrement the value of a variable in an expression. In the
Pre-Decrement, the value is first decremented and then used inside the expression. Whereas in
the Post-Decrement, the value is first used inside the expression and then decremented.
Syntax
Just like the increment operator, the decrement operator can also be used in two ways:
As prefix
--m
As postfix
m--
1. Pre-Decrement Operator
The pre-decrement operator decreases the value of the variable immediately when
encountered. It is also known as prefix decrement as the decrement operator is used as the
prefix of the operand.
Example
result = --m;
m = m - 1;
result = m;
2. Post-Decrement Operator
The post-decrement happens when the decrement operator is used as the suffix of the
variable. In this case, the decrement operation is performed after all the other operators are
evaluated.
Example
result = m;
m = m-1;