Untitled
Untitled
UNIT – III
1
MVIT UNIT-III T106-COMPUTER PROGRAMMING
INDEX
CONTROL STATEMENTS
DECISION MAKING STATEMENTS
o SIMPLE IF STATEMENT
o IF…ELSE STATEMENT
o NESTED IF…ELSE STATEMENT
o ELSE IF LADDER
SELECTION STATEMENT (SWITCH STATEMENT)
LOOPING AND BRANCHING
o WHILE LOOP
o DO...WHILE LOOP
o FOR LOOP
o JUMPS IN LOOPS
ARRAYS
o SINGLE DIMENSIONAL ARRAY
o TWO DIMENSIONAL ARRAY
o MULTI DIMENSIONAL ARRAY
FUNCTION
o TYPES OF FUNCTIONS (PROTOTYPES)
o RECURSION
o PARAMETER PASSING METHODS
o PASSING ARRAYS TO FUNCTIONS
STORAGE CLASSES
STRINGS
o STRING LIBRARY FUNCTIONS
2
MVIT UNIT-III T106-COMPUTER PROGRAMMING
2. What is if statement?
The if statement allows to control if a program enters a section of code or not based on
whether a given condition is true or false.
Syntax
if ( condition)
{
Statements;
}
In this if statement, its test a condition. If the condition is true, the statement associated with if
is executed, otherwise the statements are not executed.
Syntax :
enum identifier { value 1,value 2, …value n } ;
enumday w_st, w_end; w_st = mon ;
w_ end = sun;
The identifier follows with keyword enum is used to declare the variable.
3
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Label ;
…………
…………
Goto label;
4
MVIT UNIT-III T106-COMPUTER PROGRAMMING
11. What is looping statements? List out with examples? [JAN-13, MAY-14, MAY-15]
Loop is defined as block of statements which are repeatedly executed for certain number of times
. In ‘C’ language there are two types of looping statements are available they are:
Conditional looping
Unconditional looping
Conditional looping:
While
Do…while
For
Unconditional looping :
Switch ( ) case
Break
Continue
goto
Syntax:
Char string_variable_name [size ];
Example:
Char city [30]; Char name[20];
15. List out the types of string handling functions. (Jan 2014, MAY/JUNE 2014, MAY 2017))
strlen() - Used to find the length of a string.
strcat() - Used to combine two strings.
strrev() - Used to reverse a string.
strcmp() - Used to compare a string with another string.
strcpy() - Used to copy a string to another string.
5
MVIT UNIT-III T106-COMPUTER PROGRAMMING
16. Declare a float array of size 5 and assign 5 values to it. (-NOV/DEC 2014)
Syntax:
float float variable[size];
Example:
float sum[5]; float sum=5.0f;
floatarray[100]={1.0f,5.0f,20.0f};
23. State the advantages of user defined functions over pre-defined functions. (Jan 2011, (May/June
2016)
• The length of the source program can be reduced by dividing into the smaller function.
• It is very easy to locate and debug an error.
• It can be used in many other programs whenever necessary.
• Reduce the length of the program.
24. What is the need for user defined functions? (Jan. 2011, 2014)
• Function definition
• Function declaration
• Function call
(or)
• It facilitates top-down modular programming.
• The length of the source program can be reduced by using functions at appropriate places.
• It is easy to locate and isolate a faulty function for further investigations.
• A function can be used by many other programs
6
MVIT UNIT-III T106-COMPUTER PROGRAMMING
27. Differentiate call by value and call by reference. (Jan 2011,MAY/JUNE 2014)
Call by value Call by reference
Different memory locations are Same memory locations are
occupied by formal actual arguments occupied by formal actual
arguments, so there is a savings of
memory location.
Only the value of the variable is The address of the variable is passed
passed as an arguments as an arguments
when a new location is created, it is The existing memory location is
very slow used through its address, it is very
fast.
There is no possibility of wrong data There is a possibility of wrong data
manipulation manipulation
30. What is meant by recursion and name two application? (,Jan 2008,09,11,2014)
Recursion means “function call itself”. This is called Recursion. Typical applications are
games and Sorting trees and lists.
7
MVIT UNIT-III T106-COMPUTER PROGRAMMING
36. What is an array? What are the classifications of an array? (Jun 2010, (May/June 2016,
MAY-2015)
Array means sequence of elements that share a common name with similar data types.
This is known as Array.
Types:
One-dimensional array.
Two-dimensional array and,
Multi-dimensional array.
8
MVIT UNIT-III T106-COMPUTER PROGRAMMING
39. Write example code to declare two dimensional array? (Jan-2011,MAY/JUNE 2014)
An array with two subscripts is termed as two-dimensional array. A two dimensional array
enables us to store multiple rows of elements.
Example:
int a[10][10];
42. What is the value of b[0] in the following program? (Jan 2012)
main()
{
int a[5]={1,3,6,7,0};
int *b; b=&a[2];
}
Output: 6.
Example:
int a[8];
The first element of the array is a[0]. Likewise, for a multidimensional array, the minimum
index of each dimension starts at 0(zero).
48. Declare a character array of size 5 and assign vowels to it. (Nov/Dec 2015)
Array Declaration with Initialization
type array_name[size] = {value_list};
For example:
char vowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};
Strcat()
char s1[10] = "Hello"; char s2[10] = "World"; strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
Strcpy()
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m gonna copied into s1";
strcpy(s1,s2);
printf("String s1 is: %s", s1);
Recursion can be used to replace complex nesting code by dividing the problem into same
problem of its sub-type
The length of a string can be stored implicitly by using a special terminating character; often
this is the null character (NUL), which has all bits zero, a convention used and perpetuated by the
popular C programming language. Hence, this representation is commonly referred to as a C string
A global variable is one whose existence is known throughout a c program. Such variables are
declared outside the main() and other functions of c. Typically, global declaration takes place after the
pre-processor statements in c.
Syntax:
int m=5,n=10; //global variables void main()
{
int x,y; //local variables
}
53. State the advantages of the use of functions. (MAY-2012, JAN 2010)
Reusability: A function, once written for solving a specific task, can be used again and again.
We need not rewrite it rather reuse it.
Build own library: User can build his/her own library of the most commonly used functions.
This reduces the time and space complexity. It also promotes the portability.
Debugging is easier: since each function is a small module, it is easier to locate the errors
and correct them
54. What is the difference between functions declaration and function definitions?
Function declaration: or Function Prototype
Like the normal variables in a program, the function can be declared before they defined and
invoked.
SYNTAX :
return type function name (argument list);
Eg:
1. Void add (intn1,intn2);
2. Int area (int a);
3. Void display();
Function definition:
The function definition contains the code for the function.
11
MVIT UNIT-III T106-COMPUTER PROGRAMMING
It is the process of specifying and establishing the user defined function by specifying all of
its elements and characteristics. If the function definition appears before the main() function ,then the
function declaration is not necessary.
SYNTAX:
return type functionname(argument list)
{
local variable declaration; stmt1;
stmt2;
.
.
stmt;
return;
}
55. How the actual arguments match with formal arguments? (JAN 2013)
Actual parameters – These are the parameters transferred from the calling program (main program)
to the called program (function)
Formal parameters- These are the parameters, transferred into the calling function (main program)
from the called program (function)
PART-B
DECISION MAKING, BRANCHING & LOOPING.
(JAN 2012, JAN 2011, JAN 2010, JAN 2009,JAN-2014, (AU – NOV/DEC 2015))
CONTROL STATEMENTS
The statements which are helpful in controlling the flow of execution are known as control
statements. Control statements are mainly classified into two types. They are
Unconditional Control statement
Conditional Control statement.
GOTO Statement
GOTO statement is used to transfer the control from one part of the program to other ,with
the use of label.
The syntax is given below:
goto label;
where label is an identifier.
12
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Example program
#include<stdio.h>
void main() Output:
{
int age; I/P and O/P
clrscr(); Enter the Age: 18
printf(“Enter the Age :”); You are Eligible to vote
scanf(“%d”,&age);
if(age>=18) I/P and O/P
{ Enter the Age : 10
goto m;
You are not Eligible to vote
}
else
{
printf(“\n You are not Eligible to vote:”);
exit();
}
BRANCHING STATEMENTS
This statement executes the given condition based on the logical test. It performs two
actions based on the result. The final result of the statement may be true or false. Some of the
conditional execution statements are given below:.
Simple IF statement
IF…ELSE statement
Nested IF…ELSE statement
IF ELSE IF LADDER statement
Switch statement
SIMPLE IF STATEMENT
It is otherwise known as One-way decisions. It is used to control the flow of execution of the
statements. The decision is based on a ‘test expression or condition’ that evaluates to either true or
false.
If the test condition is true, the corresponding statement is executed.
If the test condition is false, control goes to the next executable statement.
13
MVIT UNIT-III T106-COMPUTER PROGRAMMING
IF ELSE STATEMENT
It is otherwise known as Two-way decisions. It is handled with if-else statements. The
decision is based on a ‘test expression or condition’ that evaluates to either true or false.
If the test condition is true, the true block will be executed then control goes to the
next executable statement.
If the test condition is false, the false block will be executed control goes to the next
executable statement.
if(condition)
{ True Condition False
true statements;
}
else
{
false statements;
}
True Stmt
statement-x; False Stmt
Statement-x
#include < stdio.h > //include the stdio.h header file in your program
void main ( ) // Start of the main
{
int num; // declare variable num as integer
printf (“Enter the number”); //message to the user
scanf (“%d”, &num); // read the input number from keyboard
if (num < 0) // check whether number is less than zero.
printf (“The number is negative”) // If it is less than zero then it is negative.
else // else statement.
printf (“The number is positive”); //If it is more than zero then it is +ve.
}
if(condition1)
Cond1
{
if(condition2)
true Cond2
{
statement1;
}
Stmt3 Stmt2 Stmt1
else
{
false
true
statement2;
} Stmt-x
}
else Next Stmt
{
Statements3;
}
statement-x;
//Nested – If..Else
#include<stdio.h>
#include<conio.h>
void main()
{
float a,b,c;
clrscr();
printf(“Enter a Value”);
scanf(“%f”,&a);
printf(“Enter b Value”);
15
MVIT UNIT-III T106-COMPUTER PROGRAMMING
sanf(“%f”,&b);
printf(“Enter c Value”);
scanf(“%f”,&c);
if(a>b)
{
if(a>c)
printf(“%f\n”,a);
else
printf(“%f\n”,c);
}
else
{
if(c>b)
printf(“%f\n”,c);
else
printf(“%f\n”,b);
}
getch();
}
IF ELSE IF LADDER
It is otherwise known as Multi-way decisions. Each and every else block will have if statement.
Last else block cannot have if block. Last else will have default statement.
If multiple decisions are involved in if statement elseif ladder is used. Here condition1 is
checked first. If it is true statement1 will be executed. Otherwise it checks for condition2.
If condition2 is true statement2 will be executed. Otherwise it checks for condition-n and
statement n will be executed.
If all of the given condition becomes false then statement-x will be executed. The General form
of elseif statement is as follows.
if(condition1)
statement1;
elseif (condition2) Cond1
statement2;
elseif (conditon3)
Stmt1 Cond2
statement3;
………………… Stmt2 Cond3
elseif (condition n)
statement-n; Condn
else Stmt3
statement-x; Stmt-n Stmt-x
Next stmt
Next stmt
Exit
16
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Example:
#include<stdio.h>
void main()
{
int day;
clrscr();
printf(“Enter a number between 1 to 7\n”);
scanf(“%d”,&day);
if(day= =1)
printf(“Monday\n”);
else if(day= =2)
printf(“Tuesday\n”);
else if(day= =3)
printf(“Wednesday\n”);
else if(day= =4)
printf(“Thursday\n”);
else if(day= =5)
printf(“Friday\n”);
else if(day= =6)
printf(“Saturday\n”);
else if(day= =7)
printf(“Sunday\n”);
else
printf(“Enter a Correct Number\n”);
getch();
}
17
MVIT UNIT-III T106-COMPUTER PROGRAMMING
//switch statement – add, sub, mul, div
#include<stdio.h>
void main()
{
int a,b,choice;
clrscr();
printf(“Enter two numbers : ”);
scanf(“%d%d”,&a,&b);
printf(“\n Enter 1 for addition :”);
printf(“\n Enter 2 for subtraction :”);
printf(“\n Enter3 for multiplication :”);
printf(“\n Enter 4 for division :”);
printf (“\n Enter your choice :”);
scanf(“%d”,&choice :”);
switch (choice)
{
case1:
printf(“Sum is %d”,a+b );
break;
case2:
printf(“difference is %d”,a-b);
break;
case3:
printf(“Product is %d”,a*b);
break;
case4:
printf(“Quotient is %d”,a/b);
break;
default:
printf(“Invalid choice”);
}
getch();
}
18
MVIT UNIT-III T106-COMPUTER PROGRAMMING
The process of executing a statement (or) group of statement repeatedly until a particular
condition is satisfied is called Looping. A loop can either be a pre-test loop or be a post-test loop i.e.
entry controlled loop or exit controlled loop.
The following steps are should need to construct the looping concept in a program.
Initialization of a counter variable
o It is a variable used in the loop
Test condition
Body of the loop
o Block of statements depends on the test condition
Updating the counter variable
Example: Increment/Decrement
WHILE LOOP
It is an entry control loop statement. The test condition is evaluated and if it is true, the body of
the loop is executed.
The process of execution of the body will continue till the test condition becomes true. The
control is transferred out of the loop if the test condition becomes false.
19
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Example program for generating ‘N’ Natural numbers using while loop:
# include<stdio.h > //include the stdio.h file
#include<conio.h>
void main() // Start of your program
{
int n, i=1; //Declare and initialize the variables
clrscr();
printf(“Enter the upper limit number”); //Message to the user
scanf(“%d”, &n); //read and store the number
while(i < = n) // While statement with condition
{ // Body of the loop
printf(“%d\t”,i); // print the value of i
i++; increment I to the next natural number.
}
getch();
}
Output 1: Output 2:
Enter the upper limit number 5 Enter the upper limit number -5
1 2 3 4 5
(NO OUTPUT)
DO..WHILE LOOP
In do..while loop , statement is executed first then the condition is checked.
If the given condition is not true at-least one statement will be definitely executed.
do
{
statement;
}
while(expression);
do-While loop is also called exit-controlled loop. Entry-controlled loop also known as post-test.
Example program for generating ‘N’ Natural numbers using do-while loop:
# include<stdio.h > //include the stdio.h file
#include<conio.h>
void main() // Start of your program
{
int n, i=1; //Declare and initialize the variables
clrscr();
printf(“Enter the upper limit number”); //Message to the user
scanf(“%d”, &n); //read and store the number
do // do statement without condition
{ // Body of the loop
20
MVIT UNIT-III T106-COMPUTER PROGRAMMING
printf(“%d\t”,i); // print the value of i
i++; increment I to the next natural number.
} while(i < = n); // post test of condition
getch(); }
Output 1: Output 2:
Enter the upper limit number 5 Enter the upper limit number -5
1 2 3 4 5 1
FOR LOOP
The for loop is an Entry Controlled Loop. It is a pre test.
The syntax of FOR loop is shown below:
for(initialization; test-condition; Increment/decrement)
{
program statement(s);
}
Flow Diagram
21
MVIT UNIT-III T106-COMPUTER PROGRAMMING
sum+=i; //add the value of I and store it to sum
sumsqr+=i*i; //find the square value and add it to sumsqr
} //end of for loop
printf(“Sum of first 15 positive even numbers=%d\n”,sum); //Print sum
printf(“Sum of their squares=%d\n”,sumsqr); //print sumsqr
getch();
}
//Pascaline Triangle
#include<stdio.h> Output:
#include<conio.h> *
void main( ) **
{ ***
int i,j; ****
clrscr(); *****
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“*”);
}
printf(“\n”);
}
getch();
}
BREAK STATEMENT
Break statement is used to terminate the control from one place to another in a program. Break
statement exits only single loop. Hence it is used together with the statements wherever
necessary.
It is also used to exit from a loop. A break causes the innermost enclosing loop or switch to be
exited immediately.
It is also used together with while, dowhile, for and switch statement.
Syntax: break;
22
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Program:
#include<stdio.h> #include<conio.h> main()
{
int i; for(i=1;i<=10;i++)
{
if(i==6) break; printf(“%d”,i);
}
}
Output:
12345
CONTINUE STATEMENT
It is used to continue the process. Here keywords continue is used together within a statement.
This statement is specified after the condition.
The continue statement causes the loop to be continued with the next iteration after skipping
any statement in between.
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int i,n,sum==0;
for(i=1;i<=5;i++)
{
print(“Enter any number…\n”);
scanf(“%d”,&n);
if(n<0)
continue;
else
sum=sum+n;
}
printf(“sum is…%d”,sum);
}
23
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Output:
Enter any number…10
Enter any number…15
Enter any number…25
Enter any number…10
Enter any number…50
Sum is …100
TYPE CONVERSION
Type Conversion is mainly of two types. They are
( i ) Implicit type conversion ( ii ) Explicit type conversion
C Language automatically converts values to the proper type. If the operands are of different
types the lower type is automatically converted to the higher type before the operation proceeds.
The result is of higher type.
Explicit Conversion
Explicit conversion used to force a data type to convert into another data type.
The general form is
(type_name) expression;
Example:
Ratio = femstud / malstud
Here femstud and mastud are declared as integers, the decimal part will be rounded off. This
problem can be solved by converting one of the variables to the floating point.
24
MVIT UNIT-III T106-COMPUTER PROGRAMMING
#include<stdio.h>
void main()
{
int x,y;
float z;
clrscr();
printf(“\n Enter the value of x:”);
scanf(“%d”,&x);
printf(“\n Enter the value of y :”);
scanf(“%d”,&y);
z=(float)((x+y)/(x-y));
printf(“\n The result of the expression z is %f”,z);
getch();
}
Goto statement
It is used to transfer control unconditionally from one place to another place.
A goto statement can cause program control almost anywhere in the program
unconditionally.
It requires a label to identify the place to move the execution.
A label is a valid variable name and must be ended with colon (:).
Program:
#include<stdio.h>
main()
{
int a,b;
printf(“Enter the numbers”);
scanf(“%%d”,&a,&b);
if(a==b)
goto equal;
else
{
printf(“\n A and B are not equal”);
exit(0);
}
equal:
printf(“A and B are equal”);
}
25
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Output:
1. Enter the numbers 3 3
A and B are equal
2. Enter the numbers 3 4
A and B are not equal
ARRAY
Array is a group of elements of the same data type that share a common name. Each array
element is specified by array name with one or more subscripts. Subscripts are enclosed within square
brackets [ ].The subscript value of an array always starts from 0. Individual values in an array are
called elements.
(or)
Array is a sequenced collection of related data items that share a common name and same
data type. Each array element is specified by array name with index or subscripts in brackets after
array name. The subscript value of an array always starts from 0.
(or)
Array is a collection of identical data objects which are stored in consecutive memory
locations in a common variable name. The subscript value of an array always starts from 0.
Individual values in an array are called elements.
ARRAY DECLARATION
In general, array is declared with the following syntax:
datatype arrayname[size]; or
datatype arrayname[subscript];
Data-type refers to a valid data type. Size refers to the maximum number of elements an array
can hold at the maximum. Array must be declared before being used in the C program.
Example
float height[50];
26
MVIT UNIT-III T106-COMPUTER PROGRAMMING
PROPERTIES OF AN ARRAY
All the elements of an array share the same name and they are distinguished from
one another with the help of an element number.
The element number in an array plays major role for calling each element.
The type of an array is the data type of its elements.
The array elements are stored in continuous memory locations.
The location of an array is the location of its first element.
The length of an array is the no. of data elements in the array.
The size of an array is the length of the array times the size of an elements.
TYPES OF ARRAY
(i) One dimensional array
(ii) Two dimensional array
(iii) Multi dimensional array
DIMENSIONING ARRAY
Declaring the name, type of the array and setting the number of elements in the array is
known as dimensioning the array.
Array declaration helps to define the type of the array, name of the array, number of
subscripts in an array and the total number of memory locations to be allocated.
DECLARATION OF ARRAYS
The One Dimensional Array is generally declared as follows.
data-type variablename[size];
The type specifies the type of element, such as int, float, or char.
The size indicates the maximum number of elements that can be stored inside the array.
27
MVIT UNIT-III T106-COMPUTER PROGRAMMING
avg=(float)sum/10.0;
printf(“\n sum of 10 number is : %7.2d”,sum);
printf(“\n average of 10 number is : %5.3f”,avg);
getch();
}
Example:
int rollno[3] = {26,32,12};
We can use the word ‘static’ before type declaration. This declares the variable as a
static variable.
Example
int number[3]={0,0,0};
int counter[]={1,1,1,1};
char month1[ ]={‘j’,’a’,’n’,’u’,’a’,’r’,’y’};
28
MVIT UNIT-III T106-COMPUTER PROGRAMMING
//Program to read subject name using string initialization
#include<stdio.h>
#include<conio.h>
void main()
{
char SubName[5][20]={”Electron”,”Robotic”,”Mechanic”,”DOS”,”CAD”};
int i; clrscr();
printf(“Name of the Subject is:\n”);
for(i=0;i<5;i++)
{
printf(“\t SubName[%d]=%s\n”,i,SubName[i]);
}
getch();
}
29
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Unsized Array.
If the size of the Array is unknown then it is said to be unsized Array. It is denoted by data-
type followed by the array name and square braces. Here value is specified within square braces. The
syntax is
30
MVIT UNIT-III T106-COMPUTER PROGRAMMING
data-type arrayname[ ] = { value 1, value 2,………………value n };
Here data-type refers to a valid C data type. Array name refers to name of the array. It refers
to the maximum number of elements an array can hold at the maximum. Each value in an array are
separated by commas and terminated by semicolon.
Initializing Character
/* Character is initialized within single quotes.*/
#include<stdio.h>
#include<conio.h>
void main()
{
char vow[5]={‘a’,’e’,’i'’,’o’,’u’};
31
MVIT UNIT-III T106-COMPUTER PROGRAMMING
int i; clrscr();
printf(“Vowels are:\n”);
for(i=0;i<5;i++)
{
printf(“\t Vow[%d]=%c\n”,i,vow[i]);
}
getch();
}
SORTING AN ARRAY
Sorting is the process of arranging the set of data items in an order. Sorting may be carried
out in Ascending or Descending order. Sorting helps to increase the efficiency of a program.
//Sort number in ascending order (Bubble sort)
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,num[5],temp;
clrscr();
printf(“enter five numbers:\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,&num[i]);
}
printf(“\n THE ORIGINAL LIST IS:\n”);
for(i=0;i<5;i++)
{
printf(“%d\t”,num[i]);
}
for(i=0;i<4;i++)
{
for(j=i+1;j<5;j++)
{
if num[i]>num[j]
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
32
MVIT UNIT-III T106-COMPUTER PROGRAMMING
}
}
}
printf(“\n the sorted numbers are:\n”);
for(i=0;i<5;i++)
{
printf(“%d\t”,num[i]);
}getch();
}
sort(int num[])
{
int i,j,temp;
for(i=0;i<4;i++)
{
for(j=i+1;j<5;j++)
if(n[i]>n[j])
{
temp=n[i];
n[i]=n[j];
n[j]=temp;
}
}
33
MVIT UNIT-III T106-COMPUTER PROGRAMMING
return;
}
It contains two subscripts. First subscript is represented as ‘r’ which stands for the total number
of rows and the Second subscript ‘c’ stands for number of columns.
Here r stands for number of rows and c stands for number of columns. Data-type refers to a
valid C data type. Array-name refers to a valid array name.
If there are 3 rows and 3 columns then total number of values will be 33 values. In general
for an array with n rows and c columns total number of values will be nc values.
/* example program to add two matrices & store the results in the 3rd matrix */
/******* MATRIX ADDITION ****/
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,m,n;
int l[5][5],m[5][5],n[5][5];
clrscr();
printf("\n\t\t\t MATRIX ADDITION \n\n");
printf("\n Enter the Order of Matrix: \n");
scanf("%d%d",&m,&n);
printf("\nEnter the Elements of 1st Matris:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&m[i][j]);
}
printf("\n");
}
printf("\n Enter the Elements of 2nd Matrix: \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&n[i][j]);
}
34
MVIT UNIT-III T106-COMPUTER PROGRAMMING
printf("\n");
}
printf("\n The Resultant Matrix is: \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
l[i][j]=m[i][j]+n[i][j];
printf("%d\t",&c[i][j]);
}
printf("\n\n");
}
getch();
}
Data-type refers to a valid C data type. Array-name refers to a valid array name. Here r stands
for number of rows and c stands for number of columns. Each value in an array are separated by
commas and terminated by semicolon.
There are two types of array initialization, they are given below.
Types:
a) Compile time initialization.
b) Run time initialization.
Example:
int a[2][3]={1,1,1,3,3,3};
(or) int a[2][3]={
{1,1,1},
{3,3,3}
};
This statement will initialize the elements of first row to 1 and second row to 3.
int a[2][]={1,1,1,3,3,3};
int a[][]={1,1,1,3,3,3};
The above two examples will never work. To make the above two initialization in better
manner means we must mention the column size then only the compiler knows where the first row
ends.
The row size is optional if we initialize the array in the declaration part itself.
35
MVIT UNIT-III T106-COMPUTER PROGRAMMING
b) Run time initialization.
An array can be explicitly initialized at run time by using scanf() function.
Example:
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&a[i][j]);
}
}
It may be three, four, five, six and so on. A Multi dimensional Array in general takes the
following form.
data-type array-name[s1][s2]……………[sn];
Data-type refers to a valid C data type. Array-name refers to a valid array name. s1,s2,s3, ……… are
sub scripts.
Example
#include<stdio.h>
void main()
{
int mark[2][4][3],i,j,k;
int totmark,semsum,papsum;
clrscr();
for(i=0;i<2;i++)
{
printf(“For the %d semester \n”,i+1);
for(j=0;j<4;j++)
{
printf(“\n Enter 3 marks for paper %d\n”,,j+1);
for(k=0;k<3;k++)
scanf(“%d”,&mark[i][j][k]);
}
}
totmark=0;
for(i=0;i<2;i++)
{
semsum=0;
printf(“\n Semester %d\n”,i+1);
printf(“Paper marks \ n”);
for(j=0;j<4;j++)
{
papsum=0;
36
MVIT UNIT-III T106-COMPUTER PROGRAMMING
for(k=0;k<3;k++)
papsum+=mark[i][j][k];
printf(“%d %d\n”,j+1,papsum);
semsum+=papsum;
}
printf(“Total marks in %d semester = %d \n”,i+1,semsum);
totmark+=semsum;
}
printf(“\n Grand total = %d”,totmark);
getch();
}
It may be three, four, five, six and so on. A Multi dimensional Array can be also initialized. The
general form is
data-type array-name[s1][s2]…[sn] = { value1, value2, … valuen};
Example
int num[2][3][2] = { 0,1,2,3,4,5,6,7,8,9,10,11};
Now here
num[0][0][0]=0;num[0][0][1]=1;num[0][1][0]=2;num[0][1][1]=3;num[0][2][0]=4;
num[0][2][1]=5;num[1][0][0]=6;num[1][0][1]=7;num[1][1][0]=8;num[1][1][1]=9;
num[1][2][0]=10;num[1][2][1]=11;
Example:
int table[2][3]={0,0,0,1,1,1}; ( or ) int table[2][3]={{0,0,0},{1,1,1}}
int survey[3][5][12]; float table[5][4][5][3];
Advantages of arrays
It is capable of storing many elements at a time.
It allows random access of elements.
Disadvantages of arrays
The elements in the array must be same data type.
Predetermining the size of array is must.
Memory wastage will be there, if the array of large size is defined.
To delete an element of an array we need to traverse throughout array.
FUNCTIONS
DEFINITIONS OF FUNCTIONS:
Self-contained program segment that is placed separately from the main program to perform
some specific well defined task is called function.
Function is a small segment of program that carries out some specific and well-defined task.
37
MVIT UNIT-III T106-COMPUTER PROGRAMMING
A program segment that is placed separately from the main program is called function.
Functions are the building blocks of a C program.
Advantages:
FUNCTION CLASSIFICATION
Function in C Language is mainly classified into two types. They are as follows.
User defined functions are designed and developed by the user while writing and compiling a
C program. (Example: Main function)
Library functions
Library functions are also known as Built-in functions. The Library functions available in C
language are
(i) Input/output functions.
(ii) Boolean functions.
(iii) Conversion functions.
(iv) Memory functions.
(v) String functions.
(vi) Miscellaneous functions.
(vii) Math or Arithmetic functions and
(viii) Time functions.
A MULTI-FUNCTION PROGRAM
A function is a self contained block of code that performs a particular task. Once a function has
been designed and packed, it can be treated as a ‘black box’ that takes some data from the main
program and returns a value.
38
MVIT UNIT-III T106-COMPUTER PROGRAMMING
The inner details of operation are invisible to the rest of the program. Every C program can be
designed using a collection of these black boxes know as functions.
This above set of statements defines a function called display, which could print a line of 20-character
length. This function can be used in a program as follows:
Example 1:
main()
{
display();
printf(“Computer programming\n”);
display();
}
void display(void)
{
int i;
for(i=1;i<20;i++)
printf(“-”);
printf(“\n”);
}
Output:
-----------------------------
Computer Programming
-----------------------------
The main function calls the user defined function “display” two times and library function
“printf” once. “Display” function itself calls the library function 19 times repeatedly.
Any function can call any other function, In fact it can call itself. A “called function” can also
call another function. A function can also be called more than once.
39
MVIT UNIT-III T106-COMPUTER PROGRAMMING
o In order to use this we need to invoke it at a required place in the program. This is known
as function call. The program that calls the function is referred to as the calling program
or calling function.
o The calling program should declare any function that is to be used in the program. This is
known as function declaration.
i) FUNCTION DEFINITION
A function definition, also known as function implementation shall include the following
elements.
1. Function name
2. Function type Function Header ….. may be int, float, double
3. List of parameters
4. Local variable declarations
5. Function statements Function body
6. Return statement
If the return type is not explicitly specified, C will assume that it is an integer. If the function is
not returning anything, then we need to specify the return type as void.
Function name
It is any valid C identifier that must follow the same rules of formation as other variable names in
C. The name should be appropriate to the task performed by the function.
List of parameters
The parameter list declares the variables that will receive the data sent by the calling program.
They serve as the input data to the function to carry out the specified task.
Since they represent actual input values, they are often referred to as formal parameters. These
parameters can also be used to send values to the calling programs.
40
MVIT UNIT-III T106-COMPUTER PROGRAMMING
The parameter list contains the declaration variables separated by commas and surrounded by
parenthesis.
Examples:
int circle();{------} // No argument
int area(int p,int r);{------} // Two argument
int rectangle(int h, int b, int w);{---} // Three argument.
float quadratic( int a, int b, int c);{-----} // Three argument
FUNCTION BODY
Function body contains declaration and statements necessary for that function. It contains
compound statements. Function is called by its name together with list of arguments.
When the function is invoked Formal Parameters are initialized to Actual Parameters. Function
body contains declaration and statements necessary for that function.
1. Local declaration
It is used to specify the variables necessary for a function. Variables declared inside the main
function is called as Local variables and Variables declared outside the main function is called
Global variables.
2.Function statement
Function statement is used to perform task for the function.
3.Return statement
‘Return’ statement is used to return the processed value to the main function.
If a function does not return any value to the calling function, we can omit the return statement,
then its return type is ‘void’.
If a function does not receive any value from the sub function then there is no need of ‘return’
statement.
Parameters are also known as Arguments.
while it is possible to pass to the called function any number of values, the called function can
only return one value per call.
It is used to return a value to the calling program (or) function call. It is used to terminate a
function and return a value to the calling program.
The return statement may or may not contain an expression. The return statement can take one of
the following forms
41
MVIT UNIT-III T106-COMPUTER PROGRAMMING
return;
or
return(expression);
Example:
int mul(int x, int y)
{
int p;
p=x*y;
return(p);
}
returns the value of p which is the product of the values of x and y. The last two statements can be
combined into one statement as follows
return(x*y);
A function may have more than one return statements.
42
MVIT UNIT-III T106-COMPUTER PROGRAMMING
syntax:
datatype function name (argument list);
This is very similar to the function header line except he terminating semicolon.
Examples:
double sqroot(int num);
void prod(int a, int b);
int mul(int m, int n);
In general, a function based on whether the Argument is present or not, whether the value is
returned or not is classified into five types. They are
(i) Functions with Arguments and with return values.
(ii) Functions with Arguments and without return values.
(iii) Functions without Arguments and with return values.
(iv) Functions without Arguments and without return values.
When a function has argument it receives data from calling function and does some process and
return value to the called function. Here main function has control over the function.
Whenever function is called, Actual argument values are copied and assigned to the Formal
arguments.
Now from the values in the formal arguments sub-function is processed and value is returned to
the main function.
Input
Calling Called
Function Function
Output
Example
#include<stdio.h>
#include<conio.h>
void main()
{
float x,y;
clrscr();
float add(int x, int y); // function declaration
double sub(int x,int y); //function declaration or function prototype
x=12.345;
y=9.82;
43
MVIT UNIT-III T106-COMPUTER PROGRAMMING
printf(“x=%f\n” add(x,y)); // function call – x,y are actual arguments
printf(“y=%lf\n”sub(x,y); /* function call*/
getch();
}
float add(a,b) // function declaration – a,b formal arguments
float a,b;
{
return(a+b);
}
double sub(p,q)
double p,q;
{
return(p-q);
}
When a function has Argument it receives data from the calling function and the value is used
inside the sub-function.
Whenever a function call is made, a copy of the values in Actual argument are sent to the Formal
argument by using the called function.
The Actual arguments and Formal arguments must be the same in number, order and type. The
values used in actual arguments must be assigned values before the function call is made.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void largest (a,b);
clrscr();
printf(“Enter the two numbers”);
scanf(“%d%d”,&a,&b);
largest(a,b) ;
getch();
}
/*Function to find the largest of two numbers*/
void largest(int a, int b)
{
if(a>b)
printf(“Largest element=%d”,a);
44
MVIT UNIT-III T106-COMPUTER PROGRAMMING
else
printf(“Smallest element=%d”,b);
}
When a function has no arguments it does not receive any data from calling function. But in
called function some process takes place and value is returned to calling portion of main program.
To return value to the main function return statement is used. Hence there is data transfer
between calling function and called function.
No Input
Calling Called
Output
Function Function
#include<stdio.h>
#include<conio.h>
void main()
{
int h;
void add();
clrscr();
h=add();
printf(“The sum of Numbers is:%d”,h);
getch();
}
int add()
{
int j,k,l;
printf(“Enter the value of j:”);
scanf(“%d”,&j);
printf(“Enter the value of k:”);
scanf(“%d”,&k);
l=j+k;
return(l);
}
There is no data transfer between calling function and called function. A function that does not
return any value cannot be used in an expression.
No Input
Calling Called
No Output
Function Function
45
MVIT UNIT-III T106-COMPUTER PROGRAMMING
46
MVIT UNIT-III T106-COMPUTER PROGRAMMING
if(x<=1)
return(1);
else
return(x*fact(x-1));
}
Scope of the variable determines over what region of the program a variable is actually available
for use.
Variables inside a function are classified into two types. They are
Local variable
Variables declared inside the main function are called Local variables. The value of the Local
variable is valid within the function itself.
Local variable do not maintain value during the function call. Local variables are destroyed when
the function is exited.
Variable declared in one function has no relationship with another function. Same variable name
can be used in different functions. Variable name may differ for function and sub-function.
Global variable
Variables declared before main function is called Global variable. It can be used in any part of a
program. Global variable exists till the program exists.
Two global variables cannot have the same name. Global variables are declared outside the main
function block. Variable name used for function and sub function may be same.
Like the values of simple variables, it is also possible to pass the values of a array to a function.
To pass a one-dimensional array to a called function, it is sufficient to list the name of the array,
without any subscripts, and the size of the array as arguments.
For example:
The call “largest (a, n)” will pass the whole array a to the called function. The called function
expecting this call must be appropriately defined. The largest function header might look like
The function largest is defined to take two arguments, the array name and the size of the array to
specify the number of elements in the array.
47
MVIT UNIT-III T106-COMPUTER PROGRAMMING
}
int big(int x[100],int y)
{
Output :
int j,max; Enter the total number to be given as input:3
max=x[0];
Enter the number one by one
6
for(j=1;j<y;j++) 8
if(max<x[j])
23
The maximum number in the list is 23
max=x[j];
return(max);
}
Call by Value
The process of passing the actual value of variables to a function is called “ call by value ”. In
call by value, a copy of the variable is made and passed to the function as argument.
Changes made to parameters of function have no effect on variable which call the function.
(Because changes are made only inside the function).
The values from calling function are passed as arguments to the called function. when a value is
passed to a function actual argument value are copied to the called function variable.
The value of actual argument within the calling function will not be altered.
48
MVIT UNIT-III T106-COMPUTER PROGRAMMING
#include<stdio.h>
#include<conio.h> Output :
void main() Enter values of and b: 2 3
{ The value of and b inside function is :10 21
int a,b; The value of a and b after executing the
void fun(int,int); function is 2 3
clrscr();
printf(“Enter values of and b:”);
scanf(“%d%d”,&a,&b);
fun(a,b);
printf(“The value of a and b after executing the\n”);
printf(“function is %d \t %d”,a,b);
getch();
}
void fun(int d,int e)
{
d=d*5; e=e*7;
printf(“The value of and b inside function is : ”);
printf(“%d%d”,d,e);
}
STORAGE CLASSES
Variables declared in C programs are totally different from other languages. We can use the
same variable names in the C program in separate blocks.
When we declare a variable it is available only to specific part or block of the program.
Remaining block or other function cannot get access to the variable.
Scope of a variable
The area or block of the C program from where the variable can be accessed is known as the
scope of the variable. Scope of a variable is also defined as the region over which variable is
visible or valid.
The area or scope of the variable depends on its storage class, that is, where and how it is
declared.
There are four types of storage classes available in a C language. They are
1. Automatic Variables (local variable)
2. External Variables (global variable)
3. Static Variables
4. Register Variables
49
MVIT UNIT-III T106-COMPUTER PROGRAMMING
1. Automatic Variables
Variables declared inside a block and local to block in which declared are said to be Automatic
variables. These variables can be accessed by block in which they are declared. Another block
cannot access its value.
These variables created as new variable each time when function is called and destroyed
automatically when the function is exited.
Compiler treat variable declared inside block as automatic variable by default. Automatic
variables are stored in memory. All variables declared inside the function is auto by default.
Auto variables are safe that is, they cannot be accessed directly by other functions.
Example
main()
{
int number;
-----------;
-----------;
}
We may also use the keyword auto to declare automatic variables explicitly.
main()
{
auto int number;
------------;
------------;
}
One important feature of automatic variables is that their value cannot be changed accidentally by
what happens in some other function in the program.
This assures that we may declare and use the same variable name in different functions in the
same program without causing any confusion to the compiler.
50
MVIT UNIT-III T106-COMPUTER PROGRAMMING
void function2(void)
{
int m=100;
function1();
printf(“%d\n”,m);
}
2.External variables
Variables that are active throughout the entire program are called as external variables (global
variables). External variables are declared outside the function body.
This storage class is created when variable is declared global. No memory is reserved for the
variable. Variable retain the value throughout the execution of a program. This storage class can
be accessed by any function in same or different program file and change its value.
For example , the external declaration of integer number and float length might appear as
int number;
float length=6.2;
main()
{
-------;
-------;
}
function1()
{
-------;
-------;
}
function2()
{
---------;
---------;
}
The variables number and length are available for use in all the three functions.
51
MVIT UNIT-III T106-COMPUTER PROGRAMMING
fun1(void)
{
x=x+10;
}
int fun2(void)
{ OUTPUT :
int x ; /*LOCAL declaration*/ x=10
x=1 ;
return(x) ; x=20
} x=1
fun3(void)
x=30
{
x=x+10;
}
Once a variable has been declared as global, any function can use it and change its value. Then
subsequent functions can reference only that new value.
One other aspect of a global variable is that is available only from the point of declaration to the end
of the program. Consider the program segment shown below
main()
{
y=5;
--------;
---------;
}
int y; /*Global Declaration*/
func1()
{
y=y+1;
}
We have a problem here. As far as main is concerned, y is not defined. So the compiler will
issue an error message.
External Declaration
In the above program, the main cannot access the variable y as it has been declared after the main
function. This problem can be solved by declaring the variable with the storage class named as
“extern”
3. Static Variables
When a variable is declared as static its garbage value is removed and initialized to NULL
value. The contents stored in these variables remains constant throughout the program
execution. Static variable can be initialized only once. Variable can be declared using the
keyword static.
Static variable may be either an internal type or an external type depending on the place of
declaration. Static variables declared within individual block.
They are local to the block in which declared. It exists until the end of the program.
52
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Global and Local variable can be declared static. Static variables are initialized only once when
they are compiled in a program.
4. Register Variables
Register is a special storage area in a Central Processing Unit (CPU). There are 8 registers
available inside a Computer. Register variable can be accessed only by block in which it is
declared. It cannot be accessed by any other function.
Both Local variable and formal parameter can be declared as a register. Register is used to
increase the execution speed.
Only integer or char variables are declared as register in most of the compilers but ANSI C
supports all the data types.
STRINGS
53
MVIT UNIT-III T106-COMPUTER PROGRAMMING
In C language the group of characters, digits and symbols enclosed within quotation marks are
called as strings.
Character strings are often used to build meaningful and readable programs. The common
operations performed on character strings include
C does not support strings as a data type. But it allows us to represent strings as character
arrays.
char string_name[size];
Size determines the number of characters in the string_name. Some examples are
char city[10];
char name[20];
When the Compiler assigns a character string to a character array, it automatically supplies a null
character (‘\0’) at the end of the string. Therefore the size should be equal to the maximum
number of characters in the string plus one.
Character arrays are initialized when they are declared. C permits a character array to be
initialized in either of the following two forms.
C also permits us to initialize a character array without specifying the number of elements. In
such cases the size of the array will be determined automatically, based on the number of
elements initialized, For example the statement
We can also declare the size much larger than the string size in the initializer. For example the
statement,
char str[10]=”INDIA”;
is permitted. In this case, the computer creates a character array of size 10, places the value
“INDIA” in it, terminates with null character and initializes all other elements with the null
character.
54
MVIT UNIT-III T106-COMPUTER PROGRAMMING
The problem with the scanf function is that it terminates its input on the first white space it finds.
We can also specify the field width using the form %ws in the scanf statement for reading a
specified number of character from the input string.
For Example
scanf (“%ws”,name);
Here two things may happen,
1. The width w is equal to or greater than the number of characters typed in. The entire
string will be stored in the string variable
2. The width w is less that the number of character in the string. The excess character will
be truncated and left un read
Example1:
H A I \0 ? ? ? ? ? ?
0 1 2 3 4 5 6 7 89
Example 2:
The input string “WELCOME” will be stored as
W E L C O \0 ? ? ? ?
0 1 2 3 4 5 6 7 89
Scanf with %s or %ws can read only strings without white spaces. That is they cannot be used
for reading a text containing more than one word.
However, C supports a format specification known as the edit set conversion code % […] that
can be used to read a line containing a variety of characters, including white spaces.
55
MVIT UNIT-III T106-COMPUTER PROGRAMMING
We can use this function repeatedly to read successive single characters from the input and place them
into a character array. Thus an entire line of text can be read and stored in an array.
The reading is terminated when the newline character(‘\n’)is entered and the null character is inserted
at the end of the string.
Another and more convenient method of reading a string of text containing white spaces is to use the
library function gets. This is a simple function with one string parameter and called as
gets(str);
str is a string variable declared properly. It reads character into str through keyboard until a new-line
character is encountered and then appends a null character to the string. It does not skip white spaces.
For example:
char line [80];
gets(line);
printf(“%s”, line);
reads a line of text from the keyboard and displays it on the screen.
Printf function with %s format to print strings to the screen. The format %s can be used to
display an array of character that is terminated by the null character. For example the statement
printf(“%s”, name);
The function putchar requires one parameter. The statement is equal to printf(“%c”,ch);
We can use this function repeatedly to output a string of character stored in an array as like the
following example.
char name[6]=”HAI”
for (i=0;i<5;i++)
putchar (name[i]);
putchar(“\n”);
Another and more convenient way of printing string values is using the function puts
puts(str);
where str is a string variable containing a string value. This prints the value of the string
variable str and then moves the cursor to the beginning of the next line on the screen.
C compiler supports a large number of string handling library functions that can be used to carry out
many of the string manipulations.
57
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Example Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char original[20],duplicate[20]; OUTPUT:
Enter the string: Dr. APJ. Abdul Kalam
58
Original string: Dr. APJ. Abdul Kalam
Duplicate String: Dr. APJ. Abdul Kalam
MVIT UNIT-III T106-COMPUTER PROGRAMMING
clrscr();
printf(“enter the string:”);
gets(original);
strcpy(duplicate,original);
printf(“\n Original string:%s”.original);
printf(“\n Duplicate string:%s”,duplicate);
getch();
}
Example:
strcmp(name1,name2);
strcmp(name1,”john”;
strcmp(“ram”, “rom”);
Comparison Table
S.No Value Meaning
1 Less than Zero String1 is less than string2
2 Zero Strings are equal
3 Greater than Zero String1 is greater than string 2
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char str1[50],str2[50];
int n;
clrscr();
printf(“Enter the first string:”);
gets(str1);
printf(“Enter the second string:”);
gets(str2);
n=strcmp(str1,str2);
if(n==0)
printf(“Strings are equal”);
else
printf(“Strings are not equal”);
getch();
}
Output 1:
Enter the first string: computer
Enter the second string: Programming
Strings are not equal
59
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Output 2:
Enter the first string: computer
Enter the second string: computer
Strings are equal
4. strcat() Function – String Concatenation [Nov 2016, May 2016, May 2013]
This function appends the target string to the source string. Concatenation of two strings can
be done using this function. The format of this function is as follows
Syntax:
strcat(tex1,text2);
Example Program
#include<stdio.h>
#include<conio.h> OUTPUT
#include<string.h> Enter string Welcome
void main
{ Reverse string emocleW
char text[15];
clrscr();
puts(“enter string:”);
gets(text);
puts(“reverse string”);
puts(strrev(text));
}
60
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Functions Description
Strlen() Determines the length of a string
Strcpy() Copies a string from source to destination
Strncpy() Copies character of a string to another string upto specified length
Stricmp() Compares characters of two strings.
Strcmp() Compares two strings
Strncmp() Compares characters of two strings upto the specified length
Strnicmp() Compares characters of two strings upto the specified length, Ignores case
Strlwr() Converts uppercase characters of a string to lowercase
Strupr() Converts lowercase character of a string to uppercase
Strudp() Duplicates a string
Strchr() Determines the first occurrence of a given character in a string
Strrchr() Determines the last occurrence of a given character in a string
Strstr() Determines the first occurrence of a given string in another string
Strcat() Appends source string to destination string
Strncat() Appends source string to destination string upto the specified length
Strrev() Reverses all character of a string
Strset() Sets all character of a string with a given argument or symbol
Strnset() Sets specified numbers of characters of a string with a given argument or
symbol
Strspn() Finds upto what length two strings are identical
Strpbrk() Searches the first occurrence of the character in a given string and then
displays the string starting from that character
1. strncpy()function
This function performs the same task as strcpy(). The only difference between them is that
the former function copies a specified length of character from source to destination string. Whereas
this function copies the whole source to the destination string.
61
MVIT UNIT-III T106-COMPUTER PROGRAMMING
printf(“enter Destination string:”);
gets(str2);
printf(“enter the number of character to replace in the destination :”);
scanf(“%d”,&n);
strncpy(str2, str1, n);
printf(“source string:%s, str1);
printf(“destination string:%s”, str2);
}
2. stricmp() function
This function compares two strings. The character of the strings may be in lower case or
upper case. The function does not discriminate between them, that is, this function compares two
strings without case. If the strings are same it returns to zero otherwise a non-zero value.
Example Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main
{ OUTPUT:
char str1[15],str2[15]; Enter string1 : WELCOME
int diff;
clrscr(); Enter string2 : welcome
printf(“enter string1:”); The two strings are identical
gets(str1);
printf(“enter string2:”);
gets(str2);
diff=stricmp(str1, str2);
if(diff==0)
puts(“the two strings are identical”);
else
puts(“the two strings are not identical”);
getche();
}
3. strncmp() function
A comparison of two strings can be made upto certain specified length. The function used for
this is strncmp(). This function is the same as strcmp() but it compares the character of the string to
a specified length.
The format of tehis function is as follows.
strncmp(source,target, argument)
Example Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main OUTPUT
{
char str1[15],str2[15]; Enter string1: WELCOME
int n, diff; Enter string2: WELLDONE
clrscr();
Enter length up to which comparison is to be
printf(“enter string1:”);
made: 3
62 The two strings are identical up to 3 characters
MVIT UNIT-III T106-COMPUTER PROGRAMMING
gets(str1);
printf(“enter string2:”);
gets(str2);
printf(“\n Enter length up to which comparison is to be made”);
scanf(“%d”,&n);
diff=strncmp(str1,str2,n);
printf(“the two strings are identical up to %d character”,n);
else
puts(“the two strings are differenct”);
getch();
}
4.strnicmp () function
We can also use strnicmp() function instead of strncmp(). The only difference between
them is that the strncmp() discriminates between small and capital letter whereas the strnicmp() does
not. The output of the above program with strnicmp() in place of strncmp() will be as follows.
OUTPUT:
Enter string1: WELCOME
Enter string2: welldone
Enter length up to which comparison is to be made: 3
The two strings are identical up to 3 characters
6. strudp () function
This function is used for duplicating a given string at the allocated memory which is pointed
by a pointer variable. The format of this function is as follows
text2=strudp(text1);
where text1 is a string
text2 is a pointer
63
MVIT UNIT-III T106-COMPUTER PROGRAMMING
7. strchr() Function
This function returns the pointer to the first occurrence of a given character in the string. The
format of this function is as follows
chp=strchr(string,ch);
where string is a character array, ch is character variable, chp is a pointer which collects the address
returned by strchr() function The format of this function is strchr(string,character)
Example Program/ Program to find the occurrence of a given character in the string
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main
{
char string[30], ch, *chp;
OUTPUT
clrscr();
printf(“enter text:”); Enter text: Have a nice day
gets(string); Character to find: n
printf(“\n character to find”);
ch=getchar(); Character n found in string
chp=strchr(string,ch);
if(chp)
printf(“character %c found in string”,ch);
else
printf(“character %c not found instring”,ch);
}
8. strrchr() Function
In place of strchr() one can use strrchar(). The difference between them is that the strchr()
searches for occurrence of character from the beginning of the string whereas strrchr() searches
occurrence of character from the end.
9. strstr() Function
64
MVIT UNIT-III T106-COMPUTER PROGRAMMING
This function finds the second string in the first string. It returns the pointer location from
where the second string starts in the first string. In case the first occurrence in the string is not
observed, the function returns a NULL character. The format of this function is
strstr(string1,string2);
Example Program/ Program to find the occurrence of a second string in first string
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main
{
OUTPUT
char line1[35],line2[35], *chp;
clrscr(); Enter line1 : Have a nice day
puts(“enter line1:”); Enter lin2 : day
gets(line1);
puts(“enter line2:”); ‘day’ string is present in the given
gets(line2);
chp=strstr(line1,line2);
if(chp)
printf(“’%s’string is present in given string”,line2);
else
printf(“’%s’ string is not present in given string”,line2);
}
10. strncat() Function
This function is the same as that of strcat(). The difference between them is that the former
does the concatenation of the strings with another up to a specified length. The syntaxof this function
is
strncat(text1,text2,n);
65
MVIT UNIT-III T106-COMPUTER PROGRAMMING
This function replaces every character of a string with the symbol given by the programmer,
that is the elements of the strings are replaced with the arguments given by the programmer. The
format of this function is
strset(string, symbol)
Example Program
#include<stdio.h>
#include<conio.h>
#include<string.h> OUTPUT
void main Enter string : Computer
{
char text[15];
Enter symbol for replacement: X
char symbol; Before strset(): Computer
clrscr();
After strset(): XXXXXXX
puts(“enter string:”);
gets(text);
puts(“enter symbol for replacement:”);
scanf(“%c”, &symbol);
printf(“Before strset():%s\n”, text);
strset(text, symbol);
printf(“After strset(); %s\n”, text);
}
12. strnset() Function
This function is the same as that of strset(). Here the specified length is provided. The
format of this function is
strnset(string, symbol, n);
where n is the number of characters to be replaced.
Example Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main
{
OUTPUT
char text[15]; Enter string : Computer
char symbol;
Enter symbol for replacement: x
int n;
clrscr(); How many string characters to be replaced: 4
puts(“enter string:”); Before strset(): Computer
gets(text);
puts(“enter symbol for replacement:”);After strset(): XXXXuter
scanf(“%c”, &symbol);
puts(“how many string character to be replaced”);
scanf(“%d”,&n);
printf(“Before strset():%s\n”, text);
strset(text, symbol,n);
printf(“After strset(); %s\n”, text);
}
66
MVIT UNIT-III T106-COMPUTER PROGRAMMING
strspn(string1, string2);
Example Program: Indicate after what character the lengths of the two strings have no match
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main
{
char text1[30], text2[30]; OUTPUT
int length;
Enter text1 : GOOD MORNING
clrscr();
puts(“enter text1”); Enter text2 : GOOD BYE
gets(text1); After 5 characters there is no match
puts(“enter text2”);
gets(text2);
length= strspn(text1,text2);
printf(“After %d character there is no match\n”, length);
}
14. strpbrk() Function
This function searches the first occurrence of a character in the given string and then it
displays the string starting from that character. This function returns the pointer position to the first
occurrence of the character text2[2] string in the string text1[20].
1. BUBBLE SORT (Example for One – dimensional array)(AU Jan 2005, 2011, 2013,2014,2015,
May/June 2016)
#include<stdio.h>
void main()
{
int a[20], n, temp, i, j;
67
MVIT UNIT-III T106-COMPUTER PROGRAMMING
printf("Enter the number of terms: ");
scanf("%d",&n);
printf("Enter the elements of the array:");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
for(i=0; i<n; i++)
{
for(j=0; j<n-i-1; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf("After Sorting:\n");
for(i=0; i<n; i++)
{
printf("%d\t", a[i]);
}
}
Output
Enter the number of terms: 5
Enter the elements of the array:
12 0 -14 5 16
After Sorting:
-14 0 5 12 16
68
MVIT UNIT-III T106-COMPUTER PROGRAMMING
a[j]=val;
}
printf("\nAfter sorting\n");
for(i = 0; i < n; i++)
{
printf("%d\t", a[i]);
}
}
Output
Enter the value of n: 5
Enter 5 values:
12 0 -14 5 16
After Sorting:
-14 0 5 12 16
Output
69
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Enter the value of n: 5
Enter 5 values:
12 0 -14 5 16
Before Sorting:
12 0 -14 5 16
After Sorting:
-14 0 5 12 16
4. LINEAR SEARCH (or) SEQUENTIAL SEARCH (Example for One – dimensional array)
(APR/MAY 2015,2014)
#include<stdio.h>
#inlcude<conio.h>
main()
{
int i,n,a[30],key,flag=100;
clrscr();
printf(“Enter the no. of terms:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i];
}
printf(“Enter the search element:”);
scanf(“%d”,&key);
for(i=0;i<n;i++)
{
if(key==a[i])
{
printf(“The searching element is %d present in location %d”,key,i);
flag=i;
}
}
if(flag==i)
printf(“The searching element is not present”);
getch();
}
Output 1
Enter the no. of terms:5
10 12 14 16 18
Enter the search element:18
The searching element is 18 present in location 5
Output 1
Enter the no. of terms:5
10 12 14 16 18
Enter the search element:22
The searching element is not present”);
5. BINARY SEARCH (Example for One – dimensional array)
#include<stdio.h>
#inlcude<conio.h>
main()
{
int i,n,a[30],key,low,high,mid;
clrscr();
printf(“Enter the no. of terms:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
70
MVIT UNIT-III T106-COMPUTER PROGRAMMING
scanf(“%d”,&a[i];
}
printf(“Enter the search element:”);
scanf(“%d”,&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key<a[mid])
high=mid-1;
else if(key>a[mid])
low=mid+1;
else
{
printf(“The searching element is %d present in location
%d”,key,mid);
break;
}
}
getch();
}
Output
Enter the no. of terms:5
10 12 14 16 18
Enter the search element:18
The searching element is 18 present in location 5
Output
71
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Enter no. of terms: 5
12 15 2 16 85
Largest element in array is 85
Smallest element in array is 2
7. MATRIX ADDITION (Example for two – dimensional array)( May 2017, May 2016(addition
and substraction)
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,a[3][3],b[3][3],c[3][3];
clrscr();
printf("Enter the First Matrix");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the Second Matrix");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("Display Addition Matrix");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
printf("%d \t",c[i][j]);
}
printf("\n");
}
getch();
}
Output
Enter the First Matrix
123
212
311
72
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Output
Enter the First Matrix
123
456
73
MVIT UNIT-III T106-COMPUTER PROGRAMMING
789
Enter the second Matrix
241
674
357
Matrix Multiplication
23 33 30
56 81 66
89 129 102
Output
Enter the First Matrix
123
234
587
Transpose Matrix
125
238
247
74
MVIT UNIT-III T106-COMPUTER PROGRAMMING
char str1[25], str2[25];
clrscr();
printf("Enter the first string:");
gets(str1);
printf("Enter the second string:");
gets(str2);
while(str1[i] != '\0' && str2[i] != '\0')
{
if(str1[i] != str2[i])
{
break;
}
i++;
}
if(str1[i] == '\0' && str2[i] == '\0')
{
printf("The strings are equal");
}
else
{
printf("The strings are NOT equal");
}
getch( );
}
Output 1
Enter the first string: Hai
Enter the second string: Hai
The strings are equal
Output 2
Enter the first string: Hai
Enter the Second string: Hello
The strings are NOT equal
75
MVIT UNIT-III T106-COMPUTER PROGRAMMING
}
str3[j] = '\0';
printf("The concatenated string is %s", str3);
getch( );
}
Output
Enter the first string: Hai
Enter the second string: Hello
The concatenated string is HaiHello
Output
Enter the string: success
The copied string is success
Output
Enter the string: success
The length of the string success is 7
76
MVIT UNIT-III T106-COMPUTER PROGRAMMING
#include<stdio.h>
#include<conio.h>
main()
{
int v=0,c=0,i=0;
char str[25];
clrscr();
printf("Enter the string:");
gets(str);
while(str[i] != '\0')
{
switch(str[i])
{
case 'a':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'e':
case 'i':
case 'o':
case 'u':
v++;
break;
default:
c++;
}
i++;
}
printf("The number of vowels are %d\n",v);
printf("The number of consonants are %d",c);
getch( );
}
Output
Enter the string: success
The number of vowels are 2
The number of consonants are 5
77
MVIT UNIT-III T106-COMPUTER PROGRAMMING
}
revstr[j] = '\0';
for(i = 0; i < length; i++)
{
if(str[i] == revstr[i])
c++;
}
if(c == length)
{
printf("The string %s is palindrome", str);
}
else
{
printf("The string %s is not a palindrome", str);
}
getch( );
}
Output 1
Enter the string: success
The string success is palindrome
Output 2
Enter the string: liril
The string liril is palindrome
Output
Enter the string: success
The reverse string:sseccus
17. Convert the given string from lower case characters to uppercase and upper case to
lowercase. Eg: (HellO = hELLo)
#include<stdio.h>
#include<conio.h>
78
MVIT UNIT-III T106-COMPUTER PROGRAMMING
#include<string.h>
main()
{
char str[30];
int i=0;
clrscr();
printf(“Enter any string:”);
gets(str);
while(str[i]!=`\0`)
{
if(islower(str[i])
putchar(toupper(str[i]);
else
putchar(tolower(str[i]);
i++;
}
getch();
}
Output
Enter any string: sUccEsS
SuCCeSs
18.Write a C program for finding the largest element and smallest element in matrix.(Nov/Dec
2015)
#include <stdio.h>
int main()
{
int arr[100];
int i, max, min, size;
printf("Enter size of the array: ");
scanf("%d", &size);
printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
max = arr[0];
min = arr[0];
for(i=1; i<size; i++)
{
if(arr[i]>max)
{
max = arr[i];
}
if(arr[i]<min)
{
min = arr[i];
}
}
printf("Maximum element = %d\n", max);
printf("Minimum element = %d", min);
return 0;
}
Output
Enter size of the array: 10 Enter elements in the array: -10 10 0 20 -2 50 100 20 -1 10 Maximum
element = 100 Minimum element = -10
79
MVIT UNIT-III T106-COMPUTER PROGRAMMING
Part-B
1. Write a C Program to count the letter in sequence of characters.(May-2017)
2. Explain recursion by finding factorial of 5 using recursion.(May-2017,Apr/May-2016,May-2019)
3. Write a Fibonacci numbers program(Nov-2016)
4. Write a Program to concatenate two strings and output the resulting string(Nov-2016,Apr/May-
2016)
5. Write a Program to sort a given set of numbers in ascending orders(Apr/May-2016,Jan-2013)
6.Write a C Program to find the addition and subtraction of two matrix (Apr/May-2016)
7. Discuss about the different looping statement used in C.(Jan-2016)
8. Write a Program to find the sum of n numbers using recursion(Jan-2016,May-2015)
9. Explain in detail about the break, continue and goto statements with an example program(Jan-2016)
10. Write a C Program to find whether a given number is odd or even.(May-2015)
11. Write a C program to print the sum of digits of the given numbers(May-2015)
12. Write a C Program to check whether the given string is palindrome or not(May-2015)
13. Discuss the different storage classes by identifying its scope and life time of variables(Jan-
2015,Jan-2013,May-2019)
14. Explain about passing an array to function (Apr/may-2014 )
15. Write a C Program to determine whether a given numbers is Prime number or not(Apr/May-2014)
16. Explain the string library functions with an example.(Apr/May-2014,2018,Jan-2014)
17. Write in detail about jumps in loops with neat example.(Jan-2014)
18. Write in short about multidimensional Array.(jan-2014)
19. Define array .explain the types of array in C with example Program.(May-2013)
20. Write C Program to join two strings directly (May-2013)
81