0% found this document useful (0 votes)
2 views90 pages

Major Module 2 + Questions

Uploaded by

hawkeyen720
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views90 pages

Major Module 2 + Questions

Uploaded by

hawkeyen720
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C Operator

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

The arithmetic operators are used to perform arithmetic/mathematical operations on operands.


There are 9 arithmetic operators in C language:

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

Praveen Kumar P K, UIT Kollam


+ Unary Plus Used to specify the positive values.
6
– Unary Minus Flips the sign of the value.
7
++ Increment Increases the value of the operand by 1.
8
-- Decrement Decreases the value of the operand by 1.
9
Example

#include <stdio.h>

int main()

int a = 25, b = 5;

// using operators and printing results

printf("a + b = %d\n", a + b);

printf("a - b = %d\n", a - b);

printf("a * b = %d\n", a * b);

printf("a / b = %d\n", a / b);

printf("a % b = %d\n", a % b);

printf("+a = %d\n", +a);

printf("-a = %d\n", -a);

printf("a++ = %d\n", a++);

printf("a-- = %d\n", a--);

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.

Praveen Kumar P K, UIT Kollam


These are a total of 6 relational operators in C:

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

// C program to illustrate the relational operators

#include <stdio.h>

int main()

int a = 25, b = 5; Output


// using operators and printing results a<b :0
printf("a < b : %d\n", a < b); a>b :1
printf("a > b : %d\n", a > b); a <= b: 0
printf("a <= b: %d\n", a <= b); a >= b: 1
printf("a >= b: %d\n", a >= b); a == b: 0
printf("a == b: %d\n", a == b); a != b : 1
printf("a != b : %d\n", a != b); Here, 0 means false and 1 means true.
return 0;

Praveen Kumar P K, UIT Kollam


3. Logical Operator in C

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.

Example of Logical Operators in C

// C program to illustrate the logical operators

#include <stdio.h>

int main()

{ Output

int a = 25, b = 5; a && b : 1

// using operators and printing results a || b : 1

printf("a && b : %d\n", a && b); !a: 0

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.

Praveen Kumar P K, UIT Kollam


Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at
the bit level for faster processing.

There are 6 bitwise operators in C:

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

// C program to illustrate the 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);

Praveen Kumar P K, UIT Kollam


printf("~a: %d\n", ~a);

printf("a >> b: %d\n", a >> b);

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.

In C, there are 11 assignment 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

Praveen Kumar P K, UIT Kollam


operand.

Performs bitwise AND and


&= AND and assign assigns this value to the left a &= b
operand.
7
Performs bitwise OR and
|= OR and assign assigns this value to the left a |= b
operand.
8
Performs bitwise XOR and
^= XOR and assign assigns this value to the left a ^= b
operand.
9
Performs bitwise Rightshift
Rightshift and
>>= and assign this value to the a >>= b
assign
left operand.
10
Performs bitwise Leftshift and
<<= Leftshift and assign assign this value to the left a <<= b
operand.
11

Example of C Assignment Operators

// C program to illustrate the assignment operators

#include <stdio.h> Output

int main() a = b: 5

{ a += b: 10

int a = 25, b = 5; a -= b: 5

// using operators and printing results a *= b: 25

printf("a = b: %d\n", a = b); a /= b: 5

printf("a += b: %d\n", a += b); a %= b: 0

printf("a -= b: %d\n", a -= b); a &= b: 0

printf("a *= b: %d\n", a *= b); a |= b: 5

printf("a /= b: %d\n", a /= b); a >>= b: 0

a <<= b: 0
Praveen Kumar P K, UIT Kollam
printf("a %%= b: %d\n", a %= b);

printf("a &= b: %d\n", a &= b);

printf("a |= b: %d\n", a |= b);

printf("a >>= b: %d\n", a >>= b);

printf("a <<= b: %d\n", a <<= b);

return 0;

6. Other Operators

6.1 sizeof Operator

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)

6.2 Conditional Operator ( ? : )

The conditional operator is the only ternary operator in C++.

Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then


we will execute and return the result of Expression2 otherwise if the condition(Expression1) is
false then we will execute and return the result of Expression3.

We may replace the use of if..else statements with conditional operators.

Syntax

operand1 ? operand2 : operand3;

6.3 dot (.) and arrow (->) Operators

Member operators are used to reference individual members of classes, structures, and unions.

The dot operator is applied to the actual object.

The arrow operator is used with a pointer to an object.

Praveen Kumar P K, UIT Kollam


Syntax

structure_variable . member;

structure_pointer -> member;

Praveen Kumar P K, UIT Kollam


Difference between for while and do while loops

Basis of Difference For Loop While Loop Do While Loop


The for loop is The other two loops i.e. while and do while
appropriate when we loops are more suitable in the situations where
know in advance how it is not known before hand when the loop will
many times the loop terminate.
will be executed.

Where to Use for In case if the test In case if the test


Loop, while Loop and condition fails at the condition fails at the
do while Loop beginning, and you may beginning, and you may
not want to execute want to execute the
the body of the loop body of the loop
even once if it fails, atleast once even in
then the while loop the failed condition,
should be preferred. then the do while loop
should be preferred.

A for loop initially A while loop will A do while loop will


initiates a counter always evaluate the always executed the
variable (initialization- test-expression code in the do {} i.e.
expression), then it initially. It the test- body of the loop block
checks the test- expression becomes first and then
true, then the body of
expression, and evaluates the
the loop will be
executes the body of condition. In this case
How all the three executed. The update
the loop if the test also, the counter
loops works? expression should be
expression is true. variable is initialized
updated inside the
After executing the body of the while. outside the body of
body of the loop, the However, the counter the loop.
update-expression is variable is initialized
executed which outside the body of
updates the value of the loop.
counter variable.

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-

Praveen Kumar P K, UIT Kollam


expression

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.

for (int i=1; i<=10; i++) int i = 1; int i = 1;


Conversion of one {
while (i<=10) do
Loop to another Loop
printf(“%d”,i);
or Example : Print { {
numbers from 1 to 10 }
printf(“%d”,i); printf(“%d”,i);
using all the three
++i; ++i;
loops.
} } while (i<=10);

Nested for 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:

for(initialization; condition; increment/decrement)

for(initialization; condition; increment/decrement)

Praveen Kumar P K, UIT Kollam


statement ;

Example:

for (int i=0; i<=5; i++)

for (int j=0; j<=5; j++)

printf("%d, %d",i ,j);

Example : Program to print half Pyramid of numbers

#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();

Praveen Kumar P K, UIT Kollam


Output

21

321

4321

54321

Comparison between break and continue statements

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.

Praveen Kumar P K, UIT Kollam


Formatted and Unformatted Input/Output functions in C

Formatted I/O Functions

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.

List of some format specifiers

S Format
Type Description
NO. Specifier

1 %d int/signed int used for I/O signed integer value

2 %c char Used for I/O character value

3 %f float Used for I/O decimal floating-point value

4 %s string Used for I/O string/group of characters

5 %ld long int Used for I/O long signed integer value

6 %u unsigned int Used for I/O unsigned integer value

7 %i unsigned int used for the I/O integer value

8 %lf double Used for I/O fractional or floating data

9 %n prints prints nothing

Some formatted I/O functions

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

Praveen Kumar P K, UIT Kollam


Syntax 1:

To display any variable value.

printf(“Format Specifier”, var1, var2, …., varn);

Example

int a=20;

printf("%d", a);

Syntax 2:

To display any string or a message

printf(“Enter the text which you want to display”);

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:

scanf(“Format Specifier”, &var1, &var2, …., &varn);

Example

int num1;

printf("Enter a integer number: ");

scanf("%d", &num1);

Unformatted Input/Output functions

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.

Some unformatted I/O functions

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

Praveen Kumar P K, UIT Kollam


The getchar() function is used to read only a first single character from the keyboard whether
multiple characters is typed by the user and this function reads one character at one time until
and unless the enter key is pressed. This function is declared in stdio.h(header file)

Syntax:

Variable-name = getchar();

Example:

// C program to implement the getchar() function

#include <conio.h>

#include <stdio.h>

int main()

// Declaring a char type variable

char ch;

printf("Enter the character: ");

// Taking a character from keyboard

ch = getchar();

// Displays the value of ch

printf("%c", ch);

return 0;

Output:

Enter the character: a

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)

Praveen Kumar P K, UIT Kollam


Syntax:

putchar(variable_name);

Example:

// C program to implement the putchar() function

#include <conio.h>

#include <stdio.h>

int main()

char ch;

printf("Enter any character: ");

// Reads a character

ch = getchar();

// Displays that character

putchar(ch);

return 0;

Output:

Enter any character: Z

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

Praveen Kumar P K, UIT Kollam


Example:

// C program to implement the gets() function

#include <conio.h>

#include <stdio.h>

int main()

// Declaring a char type array of length 50 characters

char name[50];

printf("Please enter some texts: ");

// Reading a line of character or a string

gets(name);

// Displaying this line of character or a string

printf("You have entered: %s", name);

return 0;

Output:

Please enter some texts: UIT Kollam

You have entered: UIT Kollam

puts()

In C programming puts() function is used to display a group of characters or strings which is


already stored in a character array. This function is declared in stdio.h(header file).

Syntax:

puts(identifier_name );

Example:

// C program to implement the puts() function

#include <stdio.h>

int main()

{
Praveen Kumar P K, UIT Kollam
char name[50];

printf("Enter your text: ");

Reads string from user

gets(name);

printf("Your text is: ");

// Displays string

puts(name);

return 0;

Output:

Enter your text: UIT Kollam

Your text is: UIT Kollam

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:

// C program to implement the putch() functions

#include <conio.h>

#include <stdio.h>

int main()

char ch;

printf("Enter any character:\n ");

// Reads a character from the keyboard

ch = getch();

printf("\nEntered character is: ");


Praveen Kumar P K, UIT Kollam
// Displays that character on the console

putch(ch);

return 0;

Output:

Enter any character:

Entered character is: d

Formatted I/O vs Unformatted I/O

Formatted I/O Unformatted I/O


S No.
functions functions

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 functions support format These functions do not support format


2
specifiers. specifiers.

These are used for storing data more These functions are not more user-
3
user friendly friendly.

Here, we can use only character and


4 Here, we can use all data types.
string data types.

printf(), scanf, sprintf() and sscanf() getch(), getche(), gets() and puts(), are
5
are examples of these functions. some examples of these functions.

Praveen Kumar P K, UIT Kollam


Types of Array in C

There are two types of arrays based on the number of dimensions it has. They are as follows:

 One Dimensional Arrays (1D Array)


 Multidimensional Arrays

1. One Dimensional Array in C

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

// C Program to illustrate the use of 1D array

#include <stdio.h>

int main()

int arr[5]; // 1d array declaration

for (int i = 0; i < 5; i++) { // 1d array initialization using for loop

arr[i] = i * i - 2 * i + 1;

printf("Elements of Array: ");

for (int i = 0; i < 5; i++) { // printing 1d array by traversing using for loop

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

return 0;

Output

Elements of Array: 1 0 1 4 9

Array of Characters (Strings)

Praveen Kumar P K, UIT Kollam


In C, we store the words, i.e., a sequence of characters in the form of an array of characters
terminated by a NULL character. These are called strings in C language.

// C Program to illustrate strings

#include <stdio.h>

int main()

char arr[10] = { 'U', 'I', 'T', 'K', 'o', 'l', 'l', 'a', 'm', '\0' };// creating array of
character

int i = 0; // printing string

while (arr[i]) {

printf("%c", arr[i++]);

return 0;

Examples 1. C Program to perform array input and output.

In this program, we will use scanf() and print() function to take input and print output for the
array.

// C Program to perform input and output on array

#include <stdio.h>

int main()

int arr[5]; // declaring an integer array

for (int i = 0; i < 5; i++) { // taking input to array elements one by one

scanf("%d", &arr[i]);

printf("Array Elements: "); // printing array elements

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

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

Praveen Kumar P K, UIT Kollam


}

return 0;

Example 2

// C Program to find the largest number in the array.

#include <stdio.h>

int main()

int arr[10], max, i;

printf("Enter array elements");

for (i = 0; i < 5; i++) {

scanf("%d", &arr[i]);

max = arr[0];

for (int i = 1; i < 5; i++) {

if (max < arr[i]) {

max = arr[i];

printf("Largest Number in the Array: %d", max);

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.

Praveen Kumar P K, UIT Kollam


2. Homogeneous Collection

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.

7. No Index Out of Bounds Checking

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.

Praveen Kumar P K, UIT Kollam


Similarly, you can declare a three-dimensional (3d) array. For example,

float y[2][4][3];

Here, the array y can hold 24 elements.

Initializing a two-dimensional array

// Different ways to initialize two-dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[2][3] = {1, 3, 0, -1, 5, 9};

Example: Read and print a Matrix

#include <stdio.h>

int main()

int i, j, m, n;

int matrix[10][20];

printf("Enter number of rows : ");

scanf("%d", &m);

printf("Enter number of columns : ");

scanf("%d", &n);

/* Input data in matrix */

for (i = 0; i < m; i++)

for (j = 0; j < n; j++)

printf("Enter data in [%d][%d]: ", i, j);

scanf("%d", &matrix[i][j]);

Praveen Kumar P K, UIT Kollam


/* Display the matrix */

for (i = 0; i < m; i++)

for (j = 0; j < n; j++)

printf("%d\t", matrix[i][j]);

printf("\n");

return 0;

Example: Program to Add Two Matrices

#include <stdio.h>

int main() {

int r, c, a[10][10], b[10][10], sum[10][10], i, j;

printf("Enter the number of rows: ");

scanf("%d", &r);

printf("Enter the number of columns: ");

scanf("%d", &c);

printf("\nEnter elements of 1st matrix:\n");

for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j) {

printf("Enter element a%d%d: ", i + 1, j + 1);

scanf("%d", &a[i][j]);

printf("Enter elements of 2nd matrix:\n");

Praveen Kumar P K, UIT Kollam


for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j) {

printf("Enter element b%d%d: ", i + 1, j + 1);

scanf("%d", &b[i][j]);

// adding two matrices

for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j) {

sum[i][j] = a[i][j] + b[i][j];

// printing the result

printf("\nSum of two matrices: \n");

for (i = 0; i < r; ++i){

for (j = 0; j < c; ++j) {

printf("%d ", sum[i][j]);

printf("\n");

return 0;

Output

Enter the number of rows (between 1 and 100): 2

Enter the number of columns (between 1 and 100): 3

Enter elements of 1st matrix:

Praveen Kumar P K, UIT Kollam


Enter element a11: 2

Enter element a12: 3

Enter element a13: 4

Enter element a21: 5

Enter element a22: 2

Enter element a23: 3

Enter elements of 2nd matrix:

Enter element b11: -4

Enter element b12: 5

Enter element b13: 3

Enter element b21: 5

Enter element b22: 6

Enter element b23: 3

Sum of two matrices:

-2 8 7

10 8 6

Eample Matrix multiplication in C

#include<stdio.h>

#include<conio.h>

int main(){

int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;

clrscr();

printf("enter the number of row=");

scanf("%d",&r);

printf("enter the number of column=");

Praveen Kumar P K, UIT Kollam


scanf("%d",&c);

printf("enter the first matrix element=\n");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

scanf("%d",&a[i][j]);

printf("enter the second matrix element=\n");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

scanf("%d",&b[i][j]);

printf("multiply of the matrix=\n");

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

Praveen Kumar P K, UIT Kollam


}

//for printing result

for(i=0;i<r;i++)

for(j=0;j<c;j++)

printf("%d\t",mul[i][j]);

printf("\n");

return 0;

Output:

enter the number of row=3

enter the number of column=3

enter the first matrix element=

111

222

333

enter the second matrix element=

111

222

333

Praveen Kumar P K, UIT Kollam


multiply of the matrix=

666

12 12 12

18 18 18

Praveen Kumar P K, UIT Kollam


ARRAYS

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:

An array is a group (or collection) of same data types.

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.

What is the need of an array?

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.

Where arrays are used

 To store list of Employee or Student names,


 To store marks of a students,
 To store list of numbers or characters etc.

Advantage of C Array

1) Code Optimization: Less code to the access the data.

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

Praveen Kumar P K, UIT Kollam


Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the
limit. So, it doesn't grow the size dynamically like LinkedList

Declaration of an Array

The C arrays are static in nature, i.e., they are allocated memory at the compile time.

Example

int arr_int[5]; // declaring array of integers

char arr_char[5]; // declaring array of characters

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.

1. Array Initialization with Declaration

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.

data_type array_name [size] = {value1, value2, ... valueN};

Example

int Arr[5] = {2,3,8,12,16};

Praveen Kumar P K, UIT Kollam


2. Array Initialization with Declaration without Size

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.

data_type array_name[] = {value1, value2, ... valueN};

Example

int arr[] = {1,2,3,4,5};

The size of the above arrays is 5 which is automatically deduced by the compiler.

3. Array Initialization after Declaration (Using Loops)

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.

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

array_name[i] = valuei;

Example

// C Program to demonstrate array initialization

#include <stdio.h>

int main()

// array initialization using initialier list

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

Praveen Kumar P K, UIT Kollam


// array initialization using initializer list without specifying size

int arr1[] = { 1, 2, 3, 4, 5 };

// array initialization using for loop

float arr2[5];

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

arr2[i] = (float)i * 2.1;

return 0;

Access Array Elements

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

Praveen Kumar P K, UIT Kollam


printf("Element at arr[4]: %d\n", arr[4]); // accessing element at index 4 i.e last element

printf("Element at arr[0]: %d", arr[0]); // accessing element at index 0 i.e first element

Update Array 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

arr[3] = 22; //update 4th (index 3) value as 22

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 Traversal using for Loop

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

array_name[i];

Example

int arr[5] = { 10, 20, 30, 40, 50 }; // array declaration and initialization

arr[2] = 100; // modifying element at index 2

printf("Elements in Array: ");

Praveen Kumar P K, UIT Kollam


for (int i = 0; i < 5; i++) { // traversing array using for loop

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

Output

Elements in Array: 10 20 100 40 50

Praveen Kumar P K, UIT Kollam


Switch Statement

The switch statement in C is an alternate to if-else-if ladder statement which allows us to


execute multiple operations for the different possible values of a single variable called switch
variable. Here, We can define various statements in the multiple cases for the different values
of a single variable.

The syntax of switch statement in c language is given below:

switch(expression){

case value1:

//code to be executed;

break;//optional

case value2:

//code to be executed;

break;//optional

......

default:

code to be executed if all cases are not matched;

Rules for switch statement in C language

1) The switch expression must be of an integer or character type.

2) The case value must be an integer or character constant.

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.

How switch Statement Work?

The working of the switch statement in C is as follows:

Step 1: The switch variable is evaluated.

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.

Step 5: Statements after the switch statement are executed.

Flowchart of Switch Statement

Example

#include<stdio.h>

int main()

int number;

printf("enter a number:");

scanf("%d",&number);

switch(number)

Praveen Kumar P K, UIT Kollam


case 10:

printf("number is equal to10\n");

case 50:

printf("number is equal to 50\n");

case 100:

printf("number is equal to100\n");

default:

printf("number is not equal to 10, 50 or100");

return0;

Output

enter a number:10

number is equal to 10

number is equal to 50

number is equal to 100

number is not equal to 10, 50 or 100

Output

enter a number:50

number is equal to 50

number is equal to 100

number is not equal to 10, 50 or 100

Example 2: C Program to print the day of the week using a switch case.

#include <stdio.h>

int main()

Praveen Kumar P K, UIT Kollam


int day ;

printf("Enter a day ");

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");

Praveen Kumar P K, UIT Kollam


break;

return 0;

Praveen Kumar P K, UIT Kollam


Decision Making / Branching statements / Conditional Statements in C

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.

Types of Conditional Statements in C

Following are the decision-making statements available in C:

• 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

Praveen Kumar P K, UIT Kollam


if Statement

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;

Praveen Kumar P K, UIT Kollam


printf("Enter a number:");

scanf("%d",&number);

if(number%2==0){

printf("%d is even number",number);

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.

Syntax of if else in C Flowchart of if-else Statement


if (condition)

// Executes this block if

// condition is true

else

// Executes this block if

// condition is false

Example of if-else

#include<stdio.h>

int main(){

int number=0;

Praveen Kumar P K, UIT Kollam


printf("Enter a number:");

scanf("%d",&number);

if(number%2==0){

printf("%d is even number",number);

else{

printf("%d is odd number",number);

return 0;

Nested if-else Statement

A nested if in C is an if statement that is the target of another if statement. Nested if


statements mean an if statement inside another if statement. Yes, C allow us to nested if
statements within if statements, i.e, we can place an if statement inside another if statement.

Syntax of Nested if-else

if (condition1)

// Executes when condition1 is true

if (condition_2)

// statement 1

else

// Statement 2

Praveen Kumar P K, UIT Kollam


else {
Flowchart of Nested if-else
if (condition_3)

// statement 3

else

// Statement 4

Example of Nested if-else

// C program to illustrate nested-if statement

//Biggest of three numbers

#include <stdio.h>

int main() {

double n1, n2, n3;

printf("Enter three numbers: ");

scanf("%lf %lf %lf", &n1, &n2, &n3);

// outer if statement

if (n1 >= n2) {

// inner if...else

if (n1 >= n3)

printf("%.2lf is the largest number.", n1);

else

printf("%.2lf is the largest number.", n3);

Praveen Kumar P K, UIT Kollam


// outer else statement

else {

// inner if...else

if (n2 >= n3)

printf("%.2lf is the largest number.", n2);

else

printf("%.2lf is the largest number.", n3);

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.

Syntax of if-else-if Ladder

if (condition)

statement;

else if (condition)

statement;

else

statement;

Flowchart of if-else-if Ladder

Praveen Kumar P K, UIT Kollam


Example of if-else-if Ladder

#include <stdio.h>

int main() {

double n1, n2, n3;

printf("Enter three numbers: ");

scanf("%lf %lf %lf", &n1, &n2, &n3);

// if n1 is greater than both n2 and n3, n1 is the largest

if (n1 >= n2 && n1 >= n3)

printf("%.2lf is the largest number.", n1);

// if n2 is greater than both n1 and n3, n2 is the largest

else if (n2 >= n1 && n2 >= n3)

printf("%.2lf is the largest number.", n2);

// if both above conditions are false, n3 is the largest

else

printf("%.2lf is the largest number.", n3);

return 0;

Praveen Kumar P K, UIT Kollam


1 MARK QUESTIONS

1. Q: What is the purpose of the assignment operator = in C?


A: It assigns the value on the right-hand side to the variable on the left.
Example: int a = 5;

2. Q: Name any two arithmetic operators used in C.


A: + (addition), * (multiplication)

3. Q: Write the syntax of a relational expression in C.


A: a > b or x == y

4. Q: What is the logical NOT operator in C?


A: ! (It inverts a Boolean value: true becomes false, and vice versa.)

5. Q: What is the precedence of the multiplication * operator compared to addition +?


A: Multiplication (*) has higher precedence than addition (+).

6. Q: What does == mean in C?


A: It checks whether two values are equal.

7. Q: Identify the operator type: x != y


A: Relational operator

8. Q: Give an example of a logical expression in C.


A: (a > b) && (b != 0)

2-MARK QUESTIONS

1. Q: Differentiate between = and == in C with examples.


A: = is for assignment (e.g., a = 10;), == is for equality comparison (e.g., a == 10)

2. Q: Write a valid arithmetic expression using at least three arithmetic operators.


A: result = a + b * c - d;

3. Q: Evaluate the expression:

int a = 4, b = 2, c;

c = a * b + 6 / 2;

printf("%d", c);

A: c = 4 * 2 + 6 / 2 = 8 + 3 = 11

4. Q: What is the output of the following code?

int x = 10, y = 5;

printf("%d", x > y && y != 0);

A: 1 (true) because both conditions are true.

5. Q: Explain with example how operator precedence affects expression evaluation.


A: In a + b * c, multiplication has higher precedence, so b * c is evaluated first.

6. Q: Give one example each of:

o Arithmetic Expression

o Relational Expression

o Logical Expression
A:
o Arithmetic: a + b

o Relational: x <= y

o Logical: a > b && b != 0

7. Q: What is the output of the following code?

int a = 10, b = 5;

printf("%d", a < b || b == 5);

A: 1 (true), since b == 5 is true.

8. Q: Identify the operators in the expression:


x = y + 2 * 5 > 10 || z < 3;
A: Assignment (=), addition (+), multiplication (*), greater than (>), logical OR (||), less than (<)

7-MARK QUESTIONS

1. Q: Analyze and evaluate the following C expression step-by-step using operator precedence:

int a = 5, b = 10, c = 15;

int result = a + b * c > 100 && b - a < 10;

printf("%d", result);

A:

• Step 1: b * c = 10 * 15 = 150

• Step 2: a + 150 = 5 + 150 = 155

• Step 3: 155 > 100 → true (1)

• Step 4: b - a = 10 - 5 = 5

• Step 5: 5 < 10 → true (1)

• Step 6: 1 && 1 → true

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

int result = (a + b > c) && (b < c);

printf("%d", result);

return 0;

A:

• (8 + 3 > 5) → 11 > 5 → true (1)

• (3 < 5) → true (1)


• 1 && 1 → true

• Output: 1

3. Q: Compare arithmetic, relational, and logical operators in C. Provide suitable examples.

A:

• Arithmetic operators: perform mathematical operations (+, -, *, /, %)


Example: a + b * c

• Relational operators: compare two values (==, !=, >, <, >=, <=)
Example: a > b

• Logical operators: combine multiple conditions (&&, ||, !)


Example: (a > b && b != 0)

4. Q: Evaluate the following C expression step-by-step:

int a = 4, b = 6, c = 2, d = 3;

int result = a + b * c > 10 && d == 3;

A:

• Step 1: b * c = 6 * 2 = 12

• Step 2: a + 12 = 4 + 12 = 16

• Step 3: 16 > 10 → true

• Step 4: d == 3 → true

• Step 5: true && true = true

• Final result = 1

5. Q: Explain with code how parentheses affect operator precedence in C.

#include <stdio.h>

int main() {

int a = 2, b = 3, c = 4;

int result1 = a + b * c;

int result2 = (a + b) * c;

printf("%d %d", result1, result2);

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

1. Define a control structure in C.


➤ A control structure directs the flow of program execution depending on conditions or loops.
2. List any two decision-making statements in C.
➤ if, switch

3. What is the syntax of a for loop in C?


➤ for(initialization; condition; increment) { //body }

4. State the difference between break and continue.


➤ break exits the loop; continue skips to the next iteration.

5. Identify which loop checks the condition after executing the body once.
➤ do-while loop

6. What is the purpose of an if-else statement?


➤ To execute different code blocks based on a condition being true or false.

7. Mention the keyword used to jump out of a loop.


➤ break

8. Give the output of:

int i = 0;

while (i < 1) {

printf("Hi");

i++;

➤ Output: Hi

9. Write the syntax of a do-while loop.


do {

// body

} while(condition);

10. What is the role of the continue statement in a loop?


➤ It skips the rest of the loop body and jumps to the next iteration.

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:

while (i < 5) { ... }

do { ... } while (i < 5);

2. Write a for loop to print numbers from 1 to 5.

for (int i = 1; i <= 5; i++) {

printf("%d ", i);

3. Use an if-else statement to check if a number is positive or negative.


if (n > 0)

printf("Positive");

else

printf("Negative");

4. Convert the following for loop into a while loop:

for (int i = 0; i < 3; i++) { printf("%d", i); }

int i = 0;

while (i < 3) {

printf("%d", i);

i++;

5. Trace the output of the following loop:

int i = 0;

while (i < 3) {

if (i == 1) continue;

printf("%d", i);

i++;

➤ Output: Infinite loop due to continue skipping i++. Logical error.

6. Illustrate the use of break inside a loop with an example.


for (int i = 1; i <= 5; i++) {

if (i == 3) break;

printf("%d ", i);

// Output: 1 2

7. Explain the role of the switch statement with an example.


➤ Used to select one of many code blocks to be executed.

switch(x) {

case 1: printf("One"); break;

case 2: printf("Two"); break;

default: printf("Other");

8. Compare pre-test and post-test loops.


➤ Pre-test (while, for) checks condition before loop body; post-test (do-while) checks after.
7-MARK QUESTIONS

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;

printf("Enter a number: ");

scanf("%d", &n);

for (int i = 1; i <= 10; i++) {

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

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;

printf("%d ", i);

i++;

Answer:

• Skips printing when i == 3

• Output: 0 1 2 4

• continue skips the printing step for i == 3

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

• if-else is more flexible, allowing complex conditions (ranges, comparisons).

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

int num, sum = 0;

do {

printf("Enter a number (0 to stop): ");

scanf("%d", &num);

sum += num;

} while (num != 0);

printf("Sum = %d", sum);

return 0;

5. Analyze the flow of the following nested loop and explain the use of break:

for (int i = 1; i <= 3; i++) {

for (int j = 1; j <= 3; j++) {

if (j == 2)

break;

printf("%d %d\n", i, j);

Answer:

• Inner loop breaks when j == 2, so j only runs once (j == 1)

• 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 {

printf("[Link] [Link] [Link] [Link] [Link]\n");

printf("Enter your choice: ");

scanf("%d", &choice);

if (choice == 5) break;
printf("Enter two numbers: ");

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

switch (choice) {

case 1: printf("Sum = %d\n", a + b); break;

case 2: printf("Difference = %d\n", a - b); break;

case 3: printf("Product = %d\n", a * b); break;

case 4:

if (b != 0) printf("Quotient = %d\n", a / b);

else printf("Division by zero!\n");

break;

default: printf("Invalid choice!\n");

} while (1);

return 0;

}
1 Mark Questions

Q1. Define unformatted I/O in C programming.

Answer:
Unformatted I/O refers to basic input/output operations like getchar(), putchar(), gets(), and puts() that do not allow
formatting of data.

Q2. List any two formatted I/O functions in C.

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

• Example (Formatted): scanf("%d", &x);

• Example (Unformatted): getchar();

Q4. Explain the purpose of format specifiers in printf() function.

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

Q5. (Apply, Analyze)


Write a C program to input a student's name, roll number, and marks using both formatted and unformatted I/O.
Then analyze the differences in output formatting between the two methods.

Answer:

#include <stdio.h>

int main() {

char name[50];

int roll;

float marks;

// Unformatted I/O

puts("Enter name (unformatted): ");

gets(name); // unformatted

puts("Enter roll number and marks (formatted): ");

scanf("%d %f", &roll, &marks); // formatted

puts("\nOutput using formatted I/O:");


printf("Name: %s\n", name);

printf("Roll Number: %d\n", roll);

printf("Marks: %.2f\n", marks);

return 0;

Analysis:

• gets() takes input without formatting but can lead to buffer overflow.

• scanf() and printf() allow specific format controls like decimal precision.

• Formatted I/O provides better readability and structure in output.

• Unformatted I/O is simpler but less safe and flexible.

1 Mark Questions

Q1. Define an array in C.

Answer:
An array is a collection of elements of the same data type stored in contiguous memory locations.

Q2. List any two types of arrays in C.

Answer:

1. One-dimensional array

2. Multi-dimensional array (e.g., two-dimensional array)

2 Mark Questions

Q3. Differentiate between one-dimensional and two-dimensional arrays with an example.

Answer:

• A one-dimensional array stores elements in a single row (e.g., int arr[5];).

• 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}};

Q4. Explain how to initialize an array at the time of declaration.

Answer:
An array can be initialized during declaration by providing values in curly braces.
Example:

int a[3] = {10, 20, 30};

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;

float sum = 0, average;

// Input marks

for(i = 0; i < 5; i++) {

printf("Enter mark %d: ", i+1);

scanf("%d", &marks[i]);

sum += marks[i];

average = sum / 5;

// Output average

printf("Average marks: %.2f\n", 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

Q1. Define a multi-dimensional array.

Answer:
A multi-dimensional array is an array of arrays, such as a 2D array with rows and columns.

Q2. State the default value of elements in an uninitialized integer array in C.


Answer:
The elements may contain garbage values unless explicitly initialized.

Q3. List any two operations that can be performed on arrays.


Answer:

1. Traversal

2. Searching

Q4. Mention the syntax to declare a one-dimensional integer array of 10 elements.


Answer:
int arr[10];

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.

Q6. Describe the purpose of using a loop with arrays.


Answer:
Loops help traverse array elements efficiently, avoiding repetitive code and enabling bulk operations like input, output,
or processing.

Q7. Differentiate between array declaration and initialization.


Answer:

• Declaration allocates memory: int a[5];

• Initialization assigns values: int a[5] = {1, 2, 3, 4, 5};

Q8. Illustrate with syntax how to declare a 2D array of size 3x3.


Answer:
int matrix[3][3];

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

int arr[6], i, max;

// Input

for(i = 0; i < 6; i++) {

printf("Enter element %d: ", i+1);

scanf("%d", &arr[i]);

max = arr[0];

for(i = 1; i < 6; i++) {

if(arr[i] > max) {

max = arr[i];

printf("Largest number = %d\n", max);

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

printf("Enter elements of 3x3 matrix:\n");

for(i = 0; i < 3; i++) {

for(j = 0; j < 3; j++) {

scanf("%d", &matrix[i][j]);

// Output

printf("Matrix is:\n");

for(i = 0; i < 3; i++) {

for(j = 0; j < 3; j++) {

printf("%d ", matrix[i][j]);

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.

• Accessing an element at [i][j] becomes intuitive when dealing with matrices.

Q11. Analyze the limitations of using static arrays in C.

Answer:

• Fixed size: Cannot change size during runtime.

• Wasted memory if size is overestimated.

• Risk of overflow if underestimated.

• Cannot use dynamic memory allocation or resizing like in dynamic structures (e.g., linked lists).
1 MARK QUESTIONS

No. Question (Bloom’s Verb) Answer

A string is a sequence of characters terminated by a null


1 Define a string in C. (Define)
character \0.

2 List any two string handling functions in C. (List) strcpy(), strlen()

3 State the syntax to declare a character array. (State) char str[20];

Mention the header file required for string functions.


4 #include <string.h>
(Mention)

5 Write the ASCII value of the null character. (Write) 0

6 Recall the purpose of \0 in strings. (Recall) It marks the end of the string.

2 MARK QUESTIONS

No. Question (Bloom’s Verb) Answer

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.

Illustrate string initialization with an example.


3 char name[] = "John"; or char name[5] = {'J','o','h','n','\0'};
(Illustrate)

4 Describe the use of strlen() function. (Describe) It returns the length of the string excluding the null character.

Summarize the use of strcat() function.


5 Appends one string to the end of another.
(Summarize)

Identify any error in the declaration: char str[5] =


6 Error: String "Hello" needs 6 characters (5 + \0), not 5.
"Hello"; (Identify)

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;

printf("Enter a string: ");

gets(str);
for(i = 0; str[i] != '\0'; i++) {

char c = str[i];

if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||

c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {

vowels++;

printf("Number of vowels: %d\n", 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() {

char str1[100], str2[50];

int i = 0, j = 0;

printf("Enter first string: ");

gets(str1);

printf("Enter second string: ");

gets(str2);

// Move to end of str1

while(str1[i] != '\0') i++;

// Copy str2 to end of str1

while(str2[j] != '\0') {

str1[i] = str2[j];

i++; j++;

}
str1[i] = '\0';

printf("Concatenated string: %s\n", str1);

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.

Q3. Analyze the output and behavior of the following code:

#include <stdio.h>

#include <string.h>

int main() {

char str1[10] = "Hi";

char str2[10] = "There";

strcpy(str1, str2);

strcat(str1, "All");

printf("%s\n", str1);

return 0;

Bloom’s Verb: Analyze


Answer:

• str1 has only 10 bytes.

• strcpy(str1, str2) makes str1 = "There".

• strcat(str1, "All") results in str1 = "ThereAll".

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

char str1[50], str2[50];

int i, flag = 0;

printf("Enter first string: ");

gets(str1);

printf("Enter second string: ");

gets(str2);

// Manual comparison

for(i = 0; str1[i] != '\0' || str2[i] != '\0'; i++) {

if(str1[i] != str2[i]) {

flag = 1;

break;

if(flag == 0)

printf("Strings are equal (manual).\n");

else

printf("Strings are not equal (manual).\n");

// Using strcmp()

if(strcmp(str1, str2) == 0)

printf("Strings are equal (strcmp).\n");

else

printf("Strings are not equal (strcmp).\n");

return 0;

Analysis:

• Manual comparison helps understand the process.

• strcmp() simplifies code and is optimized, but developers must know how it returns values.

• Manual methods offer flexibility; library functions offer reliability.


Loop in C

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.

There are mainly two types of loops in C Programming:

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.

What is the Need for Looping Statements in C?

Here are some uses of loops in C:

• 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

Let’s get into the three types of loops used in C programming.

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

for(initialization; test condition; update expression){

//code to be executed

• Here, the initialization statement is executed first and only once.


• The test condition is checked, if false the loop terminates
• If the test condition is true, the body of the loop executes
• The update expression gets updated
• Again the test condition is evaluated
• The process repeats until the test condition becomes false.

Example: For loop in C Compiler

// Program to print numbers from 1 to 10

#include <stdio.h>

int main() {

int i;

for (i = 1; i <= 10; 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.

Praveen Kumar P K, UIT Kollam


• The process will repeat until i become 10.

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;

while (test_ condition)

// body of the while loop

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.

Example: while loop in C

// Print numbers from 1 to 10

#include <stdio.h>

int main()

int i = 1;

while (i <= 10) {

printf("%d\n", i);

i++;

return 0;

• In the above code, i is initialized to 1 before the start of the loop.


• The test condition, i<=10 is evaluated. If true, the body of the loop executes.
Praveen Kumar P K, UIT Kollam
• If the condition becomes false in the beginning itself, the program control does not even
enter the loop once.
• The loop executes until i becomes 10.

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

// body of do-while loop

update_expression;

} while (test_ condition);

• The body of the loop executes before checking the condition.


• If the test condition is true, the loop body executes again.
• Again the test condition is evaluated.
• The process repeats until the test condition becomes false.

Example: do...while loop in C

#include <stdio.h>

int main()

int i = 0;

do {

printf("%d\n", i+1);

i++;

}while (i < 10);

return 0;

Praveen Kumar P K, UIT Kollam


• The above code prints numbers from 1 to 10 using the do while loop in C.
• It prints 1 before checking if i less than 10.
• It checks the condition i<10 and executes until i becomes 10

Loop Control Statements

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

The break statement ends the loop immediately when it is encountered.

Its syntax is:

break;

The break statement is almost always used with if...else statement inside the loop.

Praveen Kumar P K, UIT Kollam


Example

int i;

for (i = 0; i < 10; i++) {

if (i == 4) {

break;

printf("%d\n", i);

This example jumps out of the for loop when i is equal to 4:

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;

Praveen Kumar P K, UIT Kollam


for (i = 0; i < 10; i++) {

if (i == 4) {

continue;

printf("%d\n", i);

This example skips the value of 4:

Praveen Kumar P K, UIT Kollam


Conditional Operator in C

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.

Syntax of Conditional Operator

(condition) ? [true_statements] : [false_statements];

Flowchart of Conditional Operator

Example of Conditional Operator

//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();

printf("\n Enter any Two numbers\n");

printf("\n Enter First Number : ");

scanf("%d",&a);
Praveen Kumar P K, UIT Kollam
printf("\n Enter Second Number : ");

scanf("%d",&b);

c=(a>b) ? a : b ; // Conditional operator

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.

Praveen Kumar P K, UIT Kollam


Example of break

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

if (arr[i] == key) {

printf("Element found at position: %d",

(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

for (int i = 1; i <= 10; i++) {


Output
Praveen Kumar P K, UIT Kollam
1 2 3 4 5 7 8 9 10
if (i == 6)

continue;

else

printf("%d ", i);

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.

Praveen Kumar P K, UIT Kollam


Examples of goto

#include <stdio.h> Output

int main() 1 2 3 4 5 6 7 8 9 10

int n = 1;

label:

printf("%d ", n);

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.

Praveen Kumar P K, UIT Kollam


Flowchart of return

Syntax of return

return [expression];

Praveen Kumar P K, UIT Kollam


C Logical Operators Example

We have 3 logical operators in the C language:

Logical AND ( && )

Logical OR ( || )

Logical NOT ( ! )

1. Logical AND Operator ( && )

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

(operand_1 && operand_2)

Example

#include <stdio.h>

int main()

int a = 10, b = 20;

if (a > 0 && b > 0) {

printf("Both values are greater than 0\n");

else {

printf("Both values are less than 0\n");


Praveen Kumar P K, UIT Kollam
}
Output
return 0;
Both values are greater than 0
}

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

printf("Any one of the given value is "

"greater than 0\n");

else {

printf("Both values are less than 0\n");

return 0;

Praveen Kumar P K, UIT Kollam


}

3. Logical NOT Operator ( ! )

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

!(operand_1 && operand_2)

Example

#include <stdio.h>

int main()

int a = 10, b = 20;

if (!(a > 0 && b > 0)) {

// condition returned true but

// logical NOT operator changed

// it to false

printf("Both values are greater than 0\n");

else {

printf("Both values are less than 0\n");

return 0;

Praveen Kumar P K, UIT Kollam


Operator Precedence and Associativity in C
Precedence of operators

The precedence of operators determines which operator is executed first if there is more than
one operator in an expression.

Let us consider an example:

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.

Example of Operator Precedence

Let’s try to evaluate the following expression,

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)

After evaluating the higher precedence operator, the expression is

10 + 600

Now, the + operator will be evaluated.

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.

Example of Operator Associativity

Let’s evaluate the following expression,

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

After evaluation, the expression will be

20 % 2

Now, the % operator will be evaluated.

Example of Operator Precedence and Associativity


In general, the concept of precedence and associativity is applied together in
expressions. So let’s consider an expression where we have operators with various precedence
and associativity

exp = 100 + 200 / 10 - 3 * 10

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.

exp = 100 + (200 / 10) - 3 * 10

= 100 + 20 - 3 * 10

After that, * will be evaluated,

exp = 100 + 20 - (3 * 10)

= 100 + 20 - 30

Now, between + and –, + will be evaluated due to Left-to-Right associativity.

exp = (100 + 20) - 30

= 120 - 30

At last, – will be evaluated.

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

The increment operator ( ++ ) is used to increment the value of a variable in an expression by 1.


It can be used on variables of the numeric type such as integer, float, character, pointers, etc.

Syntax of Increment Operator

Increment Operator can be used in two ways which are as follows:

As prefix

++m

As postfix

m++

How to use the increment operator?

Both pre-increment and post-increment increase the value of the variable but there is a little
difference in how they work.

1. Pre-Increment (As prefix)

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;

The above expression can be expanded as

var = var + 1;

result = var;

2. Post-Increment (As postfix)

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.

Praveen Kumar P K, UIT Kollam


Example

result = var1++;

The above expression is equivalent

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;

which can be expanded to

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

Praveen Kumar P K, UIT Kollam


result = m--;

The above expression can be expanded as

result = m;

m = m-1;

Praveen Kumar P K, UIT Kollam

You might also like