0% found this document useful (0 votes)
178 views34 pages

MKR

The document provides study material for the Programming in C course offered by the Department of Computer Science and Engineering at Sriram Engineering College. It contains 16 multiple choice questions covering topics like external storage class, preprocessor directives, string handling functions, arrays, loops, functions, variables and more. Each question is followed by the answer or code snippet explaining the concept. The document also includes 2 part questions, with Part A focusing on operator types in C and providing examples, and Part B asking to explain the different operator types used in C programming.

Uploaded by

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

MKR

The document provides study material for the Programming in C course offered by the Department of Computer Science and Engineering at Sriram Engineering College. It contains 16 multiple choice questions covering topics like external storage class, preprocessor directives, string handling functions, arrays, loops, functions, variables and more. Each question is followed by the answer or code snippet explaining the concept. The document also includes 2 part questions, with Part A focusing on operator types in C and providing examples, and Part B asking to explain the different operator types used in C programming.

Uploaded by

Vani Rajasekhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

SRIRAM ENGINEERING COLLEGE

(A unit of Sriram Educational Trust)

Approved by AICTE, New Delhi &Affiliated to Anna University, Chennai

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Year/ Sem/Branch: I/II/CSE Date:

CS8251 - PROGRAMMING IN C

QUESTION BANK STUDY MATERIAL – I

PART – A

Q:1. What is external storage class?


Variables of this storage class are “Global variables”.
Global Variables are declared outside the function and are accessible to all functions
in the program.
Generally , External variables are declared again in the function using keyword
extern.
In order to Explicit declaration of variable use ‘extern’ keyword.
extern int num1 ; // Explicit Declaration

Q:2. How does preprocessor works?


A Preprocessor is a system software (a computer program that is designed to run on
computer’s hardware and application programs). It performs preprocessing of the High Level
Language(HLL). Preprocessing is the first step of the language processing system. Language
processing system translates the high level language to machine level language or absolute
machine code(i.e. to the form that can be understood by machine).

Q:3. Differentiate between formatted and unformatted input statements. Give an


example for each.

Formatted I/O functions Unformatted I/O functions


a. Formatted data requires more space than a. Unformatted input/output is usually the
unformatted to represent the same most compact way to store data.
information. b. Unformatted input/output is the least
b. Formatted input/output is very portable. portable form of input/output.
c. It is a simple process to move formatted c. Unformatted data files can only be moved
data files to various computers, even easily to and from computers that share
computers running different operating the same internal data representation.
systems, as long as they all use the
ASCII character set.

Q:4. What is the use of preprocessor directives?


Preprocessor directives are the commands used in preprocessor and they begin with “#”
symbol. Before a C program is compiled in a compiler, source code is processed by a
program called preprocessor. This process is called preprocessing.
Macro Syntax: #define
This macro defines constant value and can be any of the basic data types.
Header file Syntax: #include <file_name>
inclusion The source code of the file “file_name” is included in the main program at
the specified place.
Conditional Syntax: #ifdef, #endif, #if, #else, #ifndef
compilation Set of commands are included or excluded in source program before
compilation with respect to the condition.
Unconditional Syntax: #undef, #pragma
compilation #undef is used to undefine a defined macro variable. #Pragma is used to call
a function before and after main function in a C program.

Q:5. What are the various type of C operators?

C language is rich in built-in operators and provides following type of operators


a. Arithmetic Operators d. Bitwise Operators
b. Relational Operators e. Assignment Operators
c. Logical Operators f. Misc Operators
Q:6. Write a loop statement to print numbers from 10 to 1.

// While Loop

n=10; //Initialize
while(n>=1) // Condition
{
printf(" %d",n);
n--; // Decrement
}
Q:7. Name any two library functions used for string handling.

strcat - concatenate two strings.


strchr - string scanning operation.
strcmp - compare two strings.
strcpy - copy a string.
strlen - get string length.
Q:8. What is the need for functions?

a) To improve the readability of code.


b) Improves the reusability of the code, same function can be used in any program
rather than writing the same code from scratch.
c) Debugging of the code would be easier if you use functions, as errors are easy to
be traced.

Q:9. Give an example for ternary operator.

int a = 10, b = 20, c;


if (a < b) {
c = a;
}
else {
c = b;
}
printf("%d", c);
Q:10. What are variables? Give an example.

A variable is an entity whose value can vary during the execution of a program.
A variable can be assigned different data items that at various places within the
program. A variable is a data name used for storing a data value. It can be assigned
different values at different times during program execution. Ex: a=3, b=5.

Q:11. Define an array.

An array is a collection of data items, all of the same type, accessed using a common
name. A one-dimensional array is like a list; A two dimensional array is like a table;
The C language places no limits on the number of dimensions in an array, though specific
implementations may.
Q:12. How a character string is declared in C?
The general syntax for declaring a variable as a string is as follows,
char string_variable_name [array_size];
Q:13. Write a c function to compare two strings.

The general syntax for comparing two strings is as follows,


int strcmp (const char* str1, const char* str2);

Q:14. Write the syntax for multidimensional array and explain it.

Multidimensional arrays in simple words as array of arrays. Data in multidimensional


arrays are stored in tabular form.

data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array.
Here data_type is valid C/C++ data type
array_name: Name of the array
size1, size2,... ,sizeN: Sizes of the dimensions

Q:15. Declare a two dimensional array with size of 5.

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

Q:16. Write a c program to get 10 inputs for an array.

#include<stdio.h>
main()
{
int a[10],i,sum=0;
printf("enter array\n");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("sum of array =%d",sum);
}
Q:17. List the different methods for reading and writing a string.

Read string in C using gets() and fgets() functions.

Read string in C using scanf()

Q:18. List the difference between array and pointer.

Array Pointer

An array is a collection of the same type of A pointer is a variable that stores the
elements at contiguous memory locations. address of another variable.

The lowest address in an array corresponds When memory is allocated to a variable,


to the first element while highest address pointer points to the memory address of the
corresponds to the last element. variable

Array index starts with zero(0) and ends Unary operator ( * ) is used to declare a
with the size of array minus one(array size - pointer variable.
1).

Syntax: type array_name[array_size ]; Syntax: datatype *variable_name;

Q:19. What is linear search?

Linear search in C to find whether a number is present in an array. If it's present, then
at what location it occurs. It is also known as a sequential search. It is straightforward and
works as follows: we compare each element with the element to search until we find it or the
list ends. Linear search for multiple occurrences and using a function

Q:20. What are the main elements of an array declaration?

In order to declare an array, you need to specify:

 The data type of the array’s elements. It could be int, float, char, etc.
 The name of the array.
 A fixed number of elements that array may contain. The number of elements is placed
inside square brackets followed the array name.

PART-B

1.(i) Explain the different types of operators used in C with necessary program.(8)

Arithmetic Operators
Increment and Decrement Operators
Assignment Operators
Relational Operators
Logical Operators
Conditional Operators
Bitwise Operators
Special Operators
Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction and
multiplication on numerical values (constants and variables).

Operator Meaning of Operator


+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% Re/mainder after division( modulo division)

Increment and decrement operators


C programming has two operators increment ++ and decrement -- to change the value of an
operand (constant or variable) by 1.Increment ++ increases the value by 1 whereas decrement
-- decreases the value by 1. These two operators are unary operators, meaning they only
operate on a single operand.

Assignment Operators
An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =
Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b

Relational Operators
A relational operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision-making and loops.

Operator Meaning of Operator Example

== Equal to 5 == 3 returns 0

> Greater than 5 > 3 returns 1

< Less than 5 < 3 returns 0

!= Not equal to 5 != 3 returns 1

>= Greater than or equal to 5 >= 3 returns 1

<= Less than or equal to 5 <= 3 return 0


Logical Operators
An expression containing logical operator returns either 0 or 1 depending upon whether
expression results true or false. Logical operators are commonly used in decision making in C
programming.
Operator Meaning of Operator Example

Logial AND. True only if all If c = 5 and d = 2 then, expression ((c == 5)


&&
operands are true && (d > 5)) equals to 0.

Logical OR. True only if either If c = 5 and d = 2 then, expression ((c == 5) ||


||
one operand is true (d > 5)) equals to 1.

Logical NOT. True only if the If c = 5 then, expression ! (c == 5) equals to


!
operand is 0 0.

Bitwise Operators
During computation, mathematical operations like: addition, subtraction, addition and
division are converted to bit-level which makes processing faster and saves power.

Bitwise operators are used in C programming to perform bit-level operations.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Ternary Operator (?:)


A conditional operator is a ternary operator, that is, it works on 3 operands.

Conditional Operator Syntax


conditionalExpression ? expression1 : expression2

The conditional operator works as follows:

 The first expression conditionalExpression is evaluated first. This expression


evaluates to 1 if it's true and evaluates to 0 if it's false.
 If conditionalExpression is true, expression1 is evaluated.
 If conditionalExpression is false, expression2 is evaluated.

Precedence of operators

 If more than one operator are involved in an expression, C language has a predefined
rule of priority for the operators. This rule of priority of operators is called operator
precedence.
 In C, precedence of arithmetic operators( *, %, /, +, -) is higher than relational
operators(==, !=, >, <, >=, <=) and precedence of relational operator is higher than
logical operators(&&, || and !).

(ii) Write the C Program to check the integer is palindrome or not. (5)

#include <stdio.h>
int main() {
int n, reversedN = 0, remainder, originalN;
printf("Enter an integer: ");
scanf("%d", &n);
originalN = n;

// reversed integer is stored in reversedN


while (n != 0) {
remainder = n % 10;
reversedN = reversedN * 10 + remainder;
n /= 10;
}

// palindrome if orignalN and reversedN are equal


if (originalN == reversedN)
printf("%d is a palindrome.", originalN);
else
printf("%d is not a palindrome.", originalN);

return 0;
}
OUTPUT:
Enter an integer: 1001
1001a palindrome.

2. Describe the decision making statements and looping statements in C with an


Example.(13)

Decision making Statements:

If statement:–
The if statement is a powerful decision making statement & is used to control the flow of
execution of statements.
Ex:– if (test expression)
It allows the computer to evaluate the exp first and then depending on whether the value of the
exp is true or false, it transfers the control to a particular statement.
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested. The different forms are:
1. simple if statement
2. If….. else statement.
3. nested if ….else statement.
4.else if ladder
1. simple if statement :–
The general form of a simple if statement is
if (test expression)
{
Statements block;
}
Statement–X;

The statement may be a simple statement or a group of statements. If the test exp is true, the
statement block will be executed. Otherwise the statement block will be skipped & the
execution will jump to the statement x when the condition is true both the statement block &
the statement –x are executed in sequence.
Ex:– if (category = = sports)
{
Marks = marks+bonus;
}
printf (“f”, marks);
2. The if…else statement:
It is an extension of the simple if. The general form is
if(test expression)
{
true–block statements
}
else
{
False–block statements
}
Statement–x;
If the test exp. is true , then the true block statements, immediately following the if statements
are executed otherwise, the false–block statements are executed. In either case, either true–
block or false–block will be executed, not both.
In both cases, the control is transferred subsequently to the statement.
Ex:– if (cose==1)
Boy=boy+1;
Else
girl =girls+1;
--- --
----

3. nesting of if ….. else statement:–


When a series of decisions are involved, we may have to use more than one if…… else
statement in nested form as shown below.
Syntax:–
if (test condition1)
{
Statement1
}
else
{
Statement2
}
}
else
{
Statement=3;
}
Statement = x;

If the con1 is false, the statement 3 will be executed otherwise it continues to perform the 2nd
test. If the con2 is true, the statement1will evaluated & then the control is transferred to the
statement.
4.the else if ladder:
There is another way of putting if’s together when multipath decisions are involved. A
multipath decision is a chain of if’s in which the statement associated with each else is an if.
The general form is :
Syntax: if (con1)
Statement–1;
else if(con–2)
statement–2
else if(con–3)
statement–3
else if(con.n)
statement–n
else
default–statement;
statement ;

This construction is known as the else if ladder. The conditions are evaluated the top,
downward as soon as a tree con is found, the statement associated with it is executed & the
control is transferred to the statement–x (skipping the rest of the ladder). When all the n
conditions become false then the final else containing the default statement will be executed.
Ex:–
If(code==1)
Colour =”red”;
else if (code = =2)
colour=”green”;
else if (code==3)
colour=”while”;
else

colour = “yellow”;
2. The switch statement:–
C has a built–in multiway decision statement known as a switch. The switch statement tests
the value of a given variable (or exp) against a list of case values & when a match is found , a
block of statements announced with that case is executed. The general form is
Syntax: switch(expression)
{
case value–1:
block–1;
break;
case value–2:
block–2;
break;
----
---
default: default–block;
break;
}
Statement–x;
The expression is an integer expression or characters.
value–1, value–2….. are constants (or) constants expressions and are known as case labels.
Each of these values should be unique with in a switch statement.
block–1, block–2,….. are statement list & may contain 0 or more statements. There is no need
to put braces around blocks.
Note that case labels end with a colon(:)
When the switch is executed, the value of the exp is successfully compared against the values
value–1, value–2,……
If a case is found whose value matches with the value of the exp, then the block of statements
that follow the case are executed.
The break statement at the end of each block signals the end of a particular case and causes an
exit from the switch statement transforming the control to the statement x following the switch.

The default is an optional case. When present, it will be executed if the value of the exp. does
not present no action takes place if all matches fail & the control goes to the statement.
Ex:–switch(op)
{
case 1:
printf(“one”);
break;
case 2:
printf(“two”);
break;
.
.
.
default:
printf(“not entered a digit”);
}

3. The ?: operator:–

Conditional op is useful for making 2–way decisions. This op is a combination of ? and :, &
takes 3 operands. The general form is :

Syntax:– conditional exp?exp–1:exp–2

The conditional exp. is evaluated first. It the result is nonzero, exp–1 is evaluated & its value
is returned.

Ex:–
if(a>b)
big=a;
else
big=b;

can be written as

big=(a>b)?a:b

4.Goto statement :–

C supports the goto statement to branch unconditionally from one point to another in the
program.

The goto requires a label in order to identify the place where the branch is to be made. A label
is any valid variable name, & must be followed by a colon.
The label is placed immediately before the statement where the control is to be transferred. The
general forms of goto & label statements are :

The label cab be anywhere in the program either before or after the goto label; statement.

If the label: is before the statement goto label; a loop will be formed & some statements will
be executed repeatedly. Such a jump is known as a backward jump.

On the other hand, if the label: is placed after the goto label; some statements will be skipped
& the jump is known as forward jump.

Looping Statements:

Looping statement is the statements execute one or more statement repeatedly several
number of times. In C programming language there are three types of loops; while, for and
do-while.

Why use loop?

When you need to execute a block of code several number of times then you need to use
looping concept in C language.

Advantage with looping statement

 Reduce length of Code


 Take less memory space.
 Burden on the developer is reducing.
 Time consuming process to execute the program is reduced.

Types of Loops.

There are three types of Loops available in 'C' programming language.

 while loop
 for loop
 do..while

Difference between conditional and looping statement

Conditional statement executes only once in the program where as looping statements
executes repeatedly several number of time.

While loop

In while loop first check the condition if condition is true then control goes inside the loop
body otherwise goes outside the body. While loop will be repeats in clockwise direction.
Syntax

Assignment;
while(condition)
{
Statements;
......
Increment/decrements (++ or --);
}

Note: If while loop condition never false then loop becomes infinite loop.

Example of while loop

#include<stdio.h>
#include<conio.h>

void main()
{
int i;
clrscr();
i=1;
while(i<5)
{
printf("\n%d",i);
i++;
}
getch();
}

Output

1
2
3
4

For loop

for loop is a statement which allows code to be repeatedly executed. For loop contains 3
parts Initialization, Condition and Increment or Decrements.

Example of for loop

#include<stdio.h>
#include<conio.h>

void main()
{
int i;
clrscr();
for(i=1;i<5;i++)
{
printf("\n%d",i);
}
getch();
}
Output

1
2
3
4

do-while

A do-while loop is similar to a while loop, except that a do-while loop is execute at least one
time.

A do while loop is a control flow statement that executes a block of code at least once, and
then repeatedly executes the block, or not, depending on a given condition at the end of the
block (in while).

Syntax

do
{
Statements;
........
Increment/decrement (++ or --)
} while();

When use do..while Loop

When we need to repeat the statement block at least 1 time then we use do-while loop.

Example of do..while loop

#include<stdio.h>
#include<conio.h>

void main()
{
int i;
clrscr();
i=1;
do
{
printf("\n%d",i);
i++;
}
while(i<5);
getch();
}

Output

1
2
3
4
Nested loop

In Nested loop one loop is place within another loop body.

When we need to repeated loop body itself n number of times use nested loops. Nested loops
can be design upto 255 blocks.

3.Write the purpose of looping statement? Explain in detail the operation of various
looping statements in C with suitable examples.(13)

Looping statement

Looping statement is the statements execute one or more statement repeatedly several
number of times. In C programming language there are three types of loops; while, for and
do-while.

Why use loop?

When you need to execute a block of code several number of times then you need to use
looping concept in C language.

Advantage with looping statement

 Reduce length of Code


 Take less memory space.
 Burden on the developer is reducing.
 Time consuming process to execute the program is reduced.

Types of Loops.

There are three types of Loops available in 'C' programming language.

 while loop
 for loop
 do..while

Difference between conditional and looping statement

Conditional statement executes only once in the program where as looping statements
executes repeatedly several number of time.

While loop

In while loop first check the condition if condition is true then control goes inside the loop
body otherwise goes outside the body. While loop will be repeats in clockwise direction.

Syntax

Assignment;
while(condition)
{
Statements;
......
Increment/decrements (++ or --);
}
Note: If while loop condition never false then loop becomes infinite loop.

Example of while loop

#include<stdio.h>
#include<conio.h>

void main()
{
int i;
clrscr();
i=1;
while(i<5)
{
printf("\n%d",i);
i++;
}
getch();
}

Output

1
2
3
4

For loop

for loop is a statement which allows code to be repeatedly executed. For loop contains 3
parts Initialization, Condition and Increment or Decrements.

Example of for loop

#include<stdio.h>
#include<conio.h>

void main()
{
int i;
clrscr();
for(i=1;i<5;i++)
{
printf("\n%d",i);
}
getch();
}

Output

1
2
3
4

do-while
A do-while loop is similar to a while loop, except that a do-while loop is execute at least one
time.

A do while loop is a control flow statement that executes a block of code at least once, and
then repeatedly executes the block, or not, depending on a given condition at the end of the
block (in while).

Syntax

do
{
Statements;
........
Increment/decrement (++ or --)
} while();

When use do..while Loop

When we need to repeat the statement block at least 1 time then we use do-while loop.

Example of do..while loop

#include<stdio.h>
#include<conio.h>

void main()
{
int i;
clrscr();
i=1;
do
{
printf("\n%d",i);
i++;
}
while(i<5);
getch();
}

Output

1
2
3
4

Nested loop

In Nested loop one loop is place within another loop body.

When we need to repeated loop body itself n number of times use nested loops. Nested loops
can be design upto 255 blocks.
4.What is storage class? Explain the various storage classes in C along with examples.
(13)

A storage class defines the scope (visibility) and life-time of variables and/or functions within
a C Program. They precede the type that they modify. We have four different storage classes
in a C program −

 auto
 register
 static
 extern

The auto Storage Class

The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}

The example above defines two variables within the same storage class. 'auto' can only be
used within functions, i.e., local variables.

The register Storage Class

The register storage class is used to define local variables that should be stored in a register
instead of RAM. This means that the variable has a maximum size equal to the register size
(usually one word) and can't have the unary '&' operator applied to it (as it does not have a
memory location).
{
register int miles;
}

The static Storage Class

The static storage class instructs the compiler to keep a local variable in existence during the
life-time of the program instead of creating and destroying it each time it comes into and goes
out of scope. Therefore, making local variables static allows them to maintain their values
between function calls.

The extern Storage Class

The extern storage class is used to give a reference of a global variable that is visible to ALL
the program files. When you use 'extern', the variable cannot be initialized however, it points
the variable name at a storage location that has been previously defined.

When you have multiple files and you define a global variable or function, which will also be
used in other files, then extern will be used in another file to provide the reference of defined
variable or function. Just for understanding, extern is used to declare a global variable or
function in another file.
5.Explain binary search procedure. Write a c program to perform binary search and
explain. (13)

A binary search is a simplistic algorithm intended for finding the location of an item stored in
a sorted list. There are a few variations to the binary search in C program, such as testing for
equality and less-than at each step of the algorithm.

The binary search algorithm works on sorted arrays. For non-sorted arrays, the array must
first be sorted by any sorting algorithm in order to make a binary search.

The steps of binary search algorithm:

1- Select the element in the middle of the array.

2- Compare the selected element to the searched element, if it is equal to the searched
element, terminate.

3- If the searched element is larger than the selected element, repeat the search operation in
the major part of the selected element.

4- If the searched element is smaller than the selected element, repeat the search in the
smaller part of the selected element.

5- Repeat the steps until the smallest index in the search space is less than or equal to the
largest index.

Example:

#include <stdio.h>
int main()
{
int array[11] = {2,3,4,5,6,7,8,9,22,33,45};
int low = 0;
int high = 10;
int flag = 0;
int s = 4;
while(low <= high){
int index = low+(high-low)/2;
if(array[index] == s){
flag = 1;
printf("Founded: %d \n",index);
break;
}
else if(array[index] < s){
low = index+1; }
else{
high = index-1;
}}
if(flag == 0){
printf("Not Found!\n");
}
return 0;
}

6.Discuss how you can evaluate the mean, median, mode for an array of numbers with
suitable program. (13)

The mean,median,mode and range of an array


Mean, median, and mode are three kinds of “averages”. There are many “averages” in
statistics, but these are, I think, the three most common, and are certainly the three you are
most likely to encounter in your pre-statistics courses, if the topic comes up at all.

The “mean” is the “average” you’re used to, where you add up all the numbers and then
divide by the number of numbers. The “median” is the “middle” value in the list of numbers.
To find the median, your numbers have to be listed in numerical order, so you may have to
rewrite your list first. The “mode” is the value that occurs most often. If no number is
repeated, then there is no mode for the list.

The “range” is just the difference between the largest and smallest values.

Program:
#include<stdio.h>
main()
{
int i,j,a[20]={0},sum=0,n,t,b[20]={0},k=0,c=1,max=0,mode;
float x=0.0,y=0.0;
printf("\nEnter the limit\n");
scanf("%d",&n);
printf("Enter the set of numbers\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
x=(float)sum/(float)n;
printf("Mean\t= %f",x);

for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
if(n%2==0)
y=(float)(a[n/2]+a[(n-1)/2])/2;
else
y=a[(n-1)/2];
printf("\nMedian\t= %f",y);

for(i=0;i<n-1;i++)
{
mode=0;
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
mode++;

}
}
if((mode>max)&&(mode!=0))
{
k=0;
max=mode;
b[k]=a[i];
k++;
}
else if(mode==max)
{
b[k]=a[i];
k++;
}
}
for(i=0;i<n;i++)
{
if(a[i]==b[i])
c++;
}
if(c==n)
printf("\nThere is no mode");
else
{
printf("\nMode\t= ");
for(i=0;i<k;i++)
printf("%d ",b[i]);
}
}
7.Write a C program to multiply two matrices (two dimensional array) which will be
entered by a user. The user will enter the order of matrix and then its elements and
similarly input the second matrix. If the entered order of two matrices are such that
they can’t multiplied by each other, then an error message is displayed on the
screen.(13)

#include <stdio.h>
void enterData(int first[][10], int second[][10], int r1, int c1, int r2, int c2);
void multiplyMatrices(int first[][10], int second[][10], int multResult[][10], int r1, int c1, int
r2, int c2);
void display(int mult[][10], int r1, int c2);

int main() {
int first[10][10], second[10][10], mult[10][10], r1, c1, r2, c2;
printf("Enter rows and column for the first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for the second matrix: ");
scanf("%d %d", &r2, &c2);

// Taking input until columns of the first matrix is equal to the rows of the second matrix
while (c1 != r2) {
printf("Error! Enter rows and columns again.\n");
printf("Enter rows and columns for the first matrix: ");
scanf("%d%d", &r1, &c1);
printf("Enter rows and columns for the second matrix: ");
scanf("%d%d", &r2, &c2);
}

// Function to take matrices data


enterData(first, second, r1, c1, r2, c2);

// Function to multiply two matrices.


multiplyMatrices(first, second, mult, r1, c1, r2, c2);

// Function to display resultant matrix after multiplication.


display(mult, r1, c2);

return 0;
}

void enterData(int first[][10], int second[][10], int r1, int c1, int r2, int c2) {
printf("\nEnter elements of matrix 1:\n");

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


for (int j = 0; j < c1; ++j) {
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%d", &first[i][j]);
}
}
printf("\nEnter elements of matrix 2:\n");

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


for (int j = 0; j < c2; ++j) {
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%d", &second[i][j]);
}
}
}
void multiplyMatrices(int first[][10], int second[][10], int mult[][10], int r1, int c1, int r2, int
c2) {

// Initializing elements of matrix mult to 0.


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

for (int j = 0; j < c2; ++j) {


mult[i][j] = 0;
}
}

// Multiplying first and second matrices and storing in mult.


For (int I = 0; I < r1; ++i) {
for (int j = 0; j < c2; ++j) {
for (int k = 0; k < c1; ++k) {
mult[i][j] += first[i][k] * second[k][j];
}
}
}
}

void display(int mult[][10], int r1, int c2) {

printf(“\nOutput Matrix:\n”);
for (int I = 0; I < r1; ++i) {
for (int j = 0; j < c2; ++j) {
printf(“%d “, mult[i][j]);
if (j == c2 – 1)
printf(“\n”);
}
}
}
OUTPUT:
Enter rows and column for the first matrix: 2
3
Enter rows and column for the second matrix: 3
2

Enter elements of matrix 1:


Enter a11: 3
Enter a12: -2
Enter a13: 5
Enter a21: 3
Enter a22: 0
Enter a23: 4

Enter elements of matrix 2:


Enter b11: 2
Enter b12: 3
Enter b21: -9
Enter b22: 0
Enter b31: 0
Enter b32: 4

Output Matrix:
24 29
6 25
8.(i) What are the different types of string function? Describe with their purpose.(8)

C supports a wide range of functions that manipulate null-terminated strings −

Sr.No. Function & Purpose


strcpy(s1, s2);
1
Copies string s2 into string s1.
strcat(s1, s2);
2
Concatenates string s2 onto the end of string s1.
strlen(s1);
3
Returns the length of string s1.
strcmp(s1, s2);
4
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strstr(s1, s2);
6
Returns a pointer to the first occurrence of string s2 in string s1.

The following example uses some of the above-mentioned functions −

Live Demo
#include <stdio.h>
#include <string.h>

int main () {

char str1[12] = "Hello";


char str2[12] = "World";
char str3[12];
int len ;

/* copy str1 into str3 */


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */


strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */


len = strlen(str1);
printf("strlen(str1) : %d\n", len );

return 0;
}

When the above code is compiled and executed, it produces the following result −

strcpy( str3, str1) : Hello


strcat( str1, str2): HelloWorld
strlen(str1) : 10
(ii) Write the C program to find the number of vowels, constants, digits and white space
in a string.(5)

#include <stdio.h>
int main() {
char line[150];
int vowels, consonant, digit, space;
vowels = consonant = digit = space = 0;

printf("Enter a line of string: ");


fgets(line, sizeof(line), stdin);

for (int i = 0; line[i] != '\0'; ++i) {


if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||
line[i] == 'o' || line[i] == 'u' || line[i] == 'A' ||
line[i] == 'E' || line[i] == 'I' || line[i] == 'O' ||
line[i] == 'U') {
++vowels;
} else if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z')) {
++consonant;
} else if (line[i] >= '0' && line[i] <= '9') {
++digit;
} else if (line[i] == ' ') {
++space;
}
}

printf("Vowels: %d", vowels);


printf("\nConsonants: %d", consonant);
printf("\nDigits: %d", digit);
printf("\nWhite spaces: %d", space);
return 0;
}
OUTPUT:
Enter a line of string: adfslkj34 34lkj343 34lk
Vowels: 1
Consonants: 11
Digits: 9
White spaces: 2

9.Write a C program for the following :

(i). To check whether a given year is leap or not.

#include <stdio.h>
int main()
{
int y;
printf("Enter year: ");
scanf("%d",&y);

if(y % 4 == 0)
{
//Nested if else
if( y % 100 == 0)
{
if ( y % 400 == 0)
printf("%d is a Leap Year", y);

else
printf("%d is not a Leap Year", y);
}
else
printf("%d is a Leap Year", y );
}
else
printf("%d is not a Leap Year", y);

return 0;
}
OUTPUT:
Enter year: 1991
1991 is not a Leap Year

(ii). To find the roots of a quadratic equation.(8)

#include <stdio.h>
#include <math.h>
int main()
{
int a, b, c, d;
double root1, root2;

printf("Enter a, b and c where a*x*x + b*x + c = 0\n");


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

d = b*b - 4*a*c;

if (d < 0) { //complex roots


printf("First root = %.2lf + i%.2lf\n", -b/(double)(2*a), sqrt(-d)/(2*a));
printf("Second root = %.2lf - i%.2lf\n", -b/(double)(2*a), sqrt(-d)/(2*a));
}
else { //real roots
root1 = (-b + sqrt(d))/(2*a);
root2 = (-b - sqrt(d))/(2*a);

printf("First root = %.2lf\n", root1);


printf("Second root = %.2lf\n", root2);
}

return 0;
}
OUTPUT :

(iii). To convert the temperature given in Fahrenheit to Celsius(4)

//C program to convert Fahrenheit to Celsius


#include <stdio.h>

int main()
{
float celsius, fahrenheit;

printf("Please Enter the temperature in Fahrenheit: \n");


scanf("%f", &fahrenheit);

// Convert th temperature from fahrenheit to celsius formula


celsius = (fahrenheit - 32) * 5 / 9;
//celsius = 5 * (fahrenheit - 32) / 9;
//celsius = (fahrenheit - 32) * 0.55556;

printf("\n %.2f Fahrenheit = %.2f Celsius", fahrenheit, celsius);

return 0;
}

OUTPUT:

10.Develop a C program for the following :

(i). To find the area and circumference of a circle with radius r.(4)

#include<stdio.h>

int main() {

int rad;
float PI = 3.14, area, ci;

printf("\nEnter radius of circle: ");


scanf("%d", &rad);

area = PI * rad * rad;


printf("\nArea of circle : %f ", area);
ci = 2 * PI * rad;
printf("\nCircumference : %f ", ci);
return (0);
}

OUTPUT:
Enter radius of a circle : 1
Area of circle : 3.14
Circumference : 6.28

(ii). To find the sum of first 100 integers.(6)

#include <stdio.h>
main()
{
int i, sum=0;
printf("\n\tSum of first 100 positive numbers\n");
for(i=0; i<=100; i++)
sum = sum + i;
printf("\nSum = %d", sum);
getch();
}

OUTPUT:

(iii). To reverse the digits of a number. (123 => 21).(6)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main() {
int num1, num2;
char str[10];

printf("\nEnte the Number : ");


scanf("%d", &num1);

sprintf(str, "%d", num1);


strrev(str);
num2 = atoi(str);

printf("\nReversed Number : ");


printf("%d", num2);

return (0);
}
OUTPUT:

Enter the Number : 123


Reversed Number : 321
11.Write a C program for Determinant and transpose of a matrix.(8+8)

C code for Determinant of 2X2 matrix:

#include<stdio.h>
int main()
{

int a[2][2],i,j;
long determinant;

printf("Enter the 4 elements of matrix: ");


for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);

printf("\nThe matrix is\n");


for(i=0;i<2;i++){
printf("\n");
for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
}

determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1];

printf("\nDeterminant of 2X2 matrix: %ld",determinant);

return 0;
}

OUTPUT:
Enter the 4 elements of matrix:
4
8
3
9

The matrix is

4 8
3 9

C Code for Transpose:

#include <stdio.h>

int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];

printf("Enter the number of rows and columns of a matrix\n");


scanf("%d%d", &m, &n);
printf("Enter elements of the matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &matrix[c][d]);

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


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

transpose[d][c] = matrix[c][d];
printf("Transpose of the matrix:\n");

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


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

printf("%d\t", transpose[c][d]);
printf("\n");
}
return 0;
}

OUTPUT:

12.Write a C program to perform the following matrix operations:

(i) Addition (5) (ii) subtraction (5) (iii) Scaling (6)


(i) Addition
(5)
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];

printf("Enter the number of rows and columns of matrix\n");


scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");

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


for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);

printf("Enter the elements of second matrix\n");

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


for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);

printf("Sum of entered matrices:-\n");


for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return 0;
}

OUTPUT:

(ii) Subtraction
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], difference[10][10];

printf("Enter the number of rows and columns of matrix\n");


scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");

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


for (d = 0 ; d < n; d++)
scanf("%d", &first[c][d]);

printf("Enter the elements of second matrix\n");

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


for (d = 0; d < n; d++)
scanf("%d", &second[c][d]);

printf("Difference of entered matrices:-\n");

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


for (d = 0; d < n; d++) {
difference[c][d] = first[c][d] - second[c][d];
printf("%d\t",difference[c][d]);
}
printf("\n");
}

return 0;
}
OUTPUT:

(iii) Scaling

#include <stdio.h>
#define SIZE 3 // Maximum size of the array
int main()
{
int A[SIZE][SIZE];
int num, row, col;

/* Input elements in matrix from user */


printf("Enter elements in matrix of size %dx%d: \n", SIZE, SIZE);
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
scanf("%d", &A[row][col]);
}
}

/* Input multiplier from user */


printf("Enter any number to multiply with matrix A: ");
scanf("%d", &num);

/* Perform scalar multiplication of matrix */


for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
/* (cAij) = c . Aij */
A[row][col] = num * A[row][col];
}
}

/* Print result of scalar multiplication of matrix */


printf("\nResultant matrix c.A = \n");
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
printf("%d ", A[row][col]);
}
printf("\n");
}

return 0;
}
OUTPUT:

Enter elements in matrix of size 3x3:


123
456
789
Enter any number to multiply with matrix A: 2
Resultant matrix c.A =
2 4 6
8 10 12
14 16 18

You might also like