MKR
MKR
CS8251 - PROGRAMMING IN C
PART – A
// 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.
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.
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.
Q:14. Write the syntax for multidimensional array and explain it.
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
#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.
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.
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).
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
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).
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.
== Equal to 5 == 3 returns 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 OR
^ Bitwise exclusive OR
~ Bitwise complement
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;
return 0;
}
OUTPUT:
Enter an integer: 1001
1001a palindrome.
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;
--- --
----
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 :
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.
When you need to execute a block of code several number of times then you need to use
looping concept in C language.
Types of Loops.
while loop
for loop
do..while
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.
#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.
#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 we need to repeat the statement block at least 1 time then we use 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
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.
When you need to execute a block of code several number of times then you need to use
looping concept in C language.
Types of Loops.
while loop
for loop
do..while
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.
#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.
#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 we need to repeat the statement block at least 1 time then we use 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
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 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 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 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 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.
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” 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);
}
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");
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
Output Matrix:
24 29
6 25
8.(i) What are the different types of string function? Describe with their purpose.(8)
Live Demo
#include <stdio.h>
#include <string.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
#include <stdio.h>
int main() {
char line[150];
int vowels, consonant, digit, space;
vowels = consonant = digit = space = 0;
#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
#include <stdio.h>
#include <math.h>
int main()
{
int a, b, c, d;
double root1, root2;
d = b*b - 4*a*c;
return 0;
}
OUTPUT :
int main()
{
float celsius, fahrenheit;
return 0;
}
OUTPUT:
(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;
OUTPUT:
Enter radius of a circle : 1
Area of circle : 3.14
Circumference : 6.28
#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:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
int num1, num2;
char str[10];
return (0);
}
OUTPUT:
#include<stdio.h>
int main()
{
int a[2][2],i,j;
long determinant;
return 0;
}
OUTPUT:
Enter the 4 elements of matrix:
4
8
3
9
The matrix is
4 8
3 9
#include <stdio.h>
int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];
transpose[d][c] = matrix[c][d];
printf("Transpose of the matrix:\n");
printf("%d\t", transpose[c][d]);
printf("\n");
}
return 0;
}
OUTPUT:
OUTPUT:
(ii) Subtraction
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], difference[10][10];
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;
return 0;
}
OUTPUT: