0% found this document useful (0 votes)
42 views81 pages

Untitled

The document discusses various topics related to control statements, decision making statements, looping, arrays, functions, recursion, storage classes and strings in C programming. It includes if-else statements, switch statements, while, do-while and for loops. It also discusses single, multi-dimensional and passing arrays to functions. Finally, it discusses storage classes, string handling functions and two mark questions with answers on these topics.

Uploaded by

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

Untitled

The document discusses various topics related to control statements, decision making statements, looping, arrays, functions, recursion, storage classes and strings in C programming. It includes if-else statements, switch statements, while, do-while and for loops. It also discusses single, multi-dimensional and passing arrays to functions. Finally, it discusses storage classes, string handling functions and two mark questions with answers on these topics.

Uploaded by

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

MVIT UNIT-III T106-COMPUTER PROGRAMMING

UNIT – III

Decision making statements – branching and looping – arrays – multidimensional arrays –


Functions – Recursion – Passing array to functions -Storage classes – Strings – String library
functions.

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

TWO MARK QUESTIONS WITH ANSWER

1. What is the control statement? Give examples?


Control statements enable us to specify the flow of program control; ie, the order in which the
instructions in a program must be executed. They make it possible to make decisions, to perform tasks
repeatedly or to jump from one section of code to another.
These are all the following conditions statements
 if statement
 if _else statement
 nested if_ else statement
 if_ else ladder

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.

3. List out the rules for writing switch statement?


 No real numbers are used in expression
 The switch can be nested
 The case keyword must be terminate with colon (:)

4. Compare switch and nested if statement?


Switch Case Nested If
It can only test constant values If can evaluate relational and logical
expressions
In switch case statement nested if In nested if statement switch 0 can
can be used be used
characters constants are
automatically converts to integer

5. What are enumerated data types?


It is a user defined data types .It is provided by “c” language.

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

6. Difference between break and continue statement? MAY 2015


Break Continue
Break statement takes the control to the Continue statement takes the control to the
outside of the loop. beginning of the loop.
It is also used in switch statement. It is used only in loop statement
It is always associated with if condition It is always associated with if condition
loops. loops.

8. Differentiate while and do while statement in C? (MAY 2017, JAN-2013)


While Do while
It is top tested loop It is bottom tested loop
The condition is first tested , if the It executes the body once , after it checks
condition is true then the block is executed the condition , if it is true the body is
until the condition becomes executed until the condition
false . become false .
Loop will not be executed if the condition is Loop will be executed atleast once
false . eventhough the condition is false .

9. Write short notes on for loop?


It is repetitive control structure. It is used to execute a set of instruction repeatedly until the
condition becomes false.
Syntax :
for( initialize counter ;test condition ; increment or decrement counter)
{
…………..
Body of the loop;
………….
}

It has three parts


 Initialize counter: used to initialize counter variables.
 Test condition: used to test the condition.
 Increment/decrement: used to increment/decrement of counter variables.

10. Write short notes on goto statement?


Goto statement is mainly used to transfer the control unconditionally from one place to another
place in the program.
It requires a label to identify the place to move the execution.
A label is a valid variable name and it must be ended with colon ( : )
Syntax:
goto label;
………..
……......
Label;

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

12. What is string? Give example.( May/June 2016)


String is the sequence of character or array of character enclosed within double quotes. That string
must terminate with null character (`\0`).
Eg. “super”.

13. How strings are represented in language C? (MAY 2016)


String is the sequence of character or array of character enclosed within double quotes.
That string must terminate with null character (`\0`).
Eg.
char str[]=”super”;
The elements of the array are
str[0]=’s’;
str[1]=’u’;
str[2]=’p’;
str[3]=’e’;
str[4]=’r’;
str[5]=’\0’;

14. How is a character string declared? (APR/MAY 2015)


Character Array is Called as ‘String’
Character Array is Declared Before Using it in Program

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

17. What is meant by function? ( NOV/DEC 2014)


The function is a block of statements that executes for a specific task. This is known as function.

18. List out the types of function prototype.


• Function with no arguments and no return values.
• Function with no arguments and return values.
• Function with arguments and no return values.
• Function with arguments and return values.

19. What is function prototyping? Why it is necessary? ( May 2011)


Function prototype is otherwise known as “function declaration”. It is necessary to declared
before they defined and invoked.

20. List out the various parameter passing method in function.


There are two types of parameter passing method, they are given below,
• Call by value
• Call by reference.

21. What is the purpose of the return statement?


The purpose of the return statement is, the return statement may or may not send back any
values to the main program (calling program). If it does, it can be done using the return statement.

22. What is meant by user defined function?


The function defined by the user according to their requirements is called user defined
function.

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

25. Define call by value. (Jan 2011)


When the value is passed directly to the function it is called call by value. In call by value
only a copy of the variable is only passed so any changes made to the variable does not reflects in the
calling function.

26. Define call by reference.


When the address of the value is passed to the function it is called call by reference. In call by
reference since the address of the value is passed any changes made to the value reflects in the calling
function.

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

28. Define a C function to exchange the content of two variables. ( Jan.2009)


void exchange(int *a, int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
}

29. What is meant by library function with example?


Library functions are also known as built-in functions or intrinsic functions. The compiler
itself evaluates these functions. This is known as library functions.
Eg.
sqrt(), log(x),exp() and so on…

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.

31. Define strlen() function. [NOV 2016,JAN 2011]


strlen(), this function is used to count and return the number of character present in a string.
Syntax:
len=strlen(string);

7
MVIT UNIT-III T106-COMPUTER PROGRAMMING

32. Define strcat() function. [NOV 2016,JAN 2011]


strcat(), this function is used to concatenate or combine two strings together then forms a new
string.
Syntax:
strcat(str1,str2);

33. Define strrev() function.


strrev(), this function is used to reverse a string. This function takes and returns only one
argument.
Syntax:
strrev(str);

34. Define strcmp() function.


strcmp(), this function which compares two strings to find whether they are same or different.
If two strings are equal means it returns a zero otherwise numeric difference between the non-
matching characters.
Syntax:
strcmp(str1,str2);

35. Define strcpy() function.


strcpy(), this is used to copy the contents of a string to another strings.
Syntax:
strcpy(str1,str2);

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.

37. Write the features of arrays. (May 2016)


An array is a derived data types. It is used to represent a collection of elements of the same
data type.
The elements can be accessed with base address and the subscript defined for the position of
the element.
The elements are stored in continuous memory location.
The starting memory location is represented by the array name and it is known as the base
address of the array.

38. Define one – dimensional array.


The collection of data item can be stored under a one variable name using only one subscript ,
such a variable is called one – dimensional array.
Example:
int a[10];

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

40. Give example for array initialization.


An array can be initialized at the time of declaration is known as compile time initialization.
Example:
int a[5]={5,8,7,4,1};

An array can be explicitly initialized at run time.


Example:
for(i=0;i<5;i++)
scanf(“%d”,&a[i]);

41. Define array. Give example. (Jan 2009,APR/MAY 2015)


Array means sequence of elements that share a common name with similar data types.
This is known as Array.
Example:
int rollno[66];
In this example we have declared an array of integer data type and named it “rollno” which
can store roll numbers of 66 students.

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.

43. Why do you need to use array?


In many cases, we need to declare a set of variables that are of the same data type. Instead of
declaring each variable separately, we can declare all variables collectively in the format of an array.
Each variable, as an element of the array, can be accessed either through the array element references
or through a pointer that references the array.

44. What is the minimum index of an array?


The minimum index of a one-dimensional array is 0(zero), which marks the first element of
the array.

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

45. List out the disadvantages of an array.


The elements in the array must be same data types.
The size of an array is fixed.
9
MVIT UNIT-III T106-COMPUTER PROGRAMMING

If we need more space at run time, it is not possible to extend array.


The insertion and deletion an operation is an array require shifting of elements which takes
time.

46. List out few characteristics of arrays.


All the elements of an array share the same name and they are distinguished from one
another with help of an element number.
The element number in an array plays major role for calling each element.
An element of an array a[] can be assigned.
The array elements are stored in continuous memory locations.

47. List out few types of sorting.


Bubble sort.
Selection sort.
Insertion sort.
Merge sort.
Heap sort.
Quick sort.

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

49. Give some examples of string functions. (Nov/Dec 2015)


Strlen( )
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));

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

50. Recursion. (MAY-13, JAN-14, JAN-15, JAN-16, JAN 2010)


Recursion is the process of calling the same function itself again and again until some
condition is satisfied. This process is used for repetitive computation in which each action is satisfied
in terms of a previous result.
Syntax:
function1()
{
function1();
}
Advantages:
• Recursion is more elegant and requires few variables which make program clean.
10
MVIT UNIT-III T106-COMPUTER PROGRAMMING

Recursion can be used to replace complex nesting code by dividing the problem into same
problem of its sub-type

51. What is a null character? What is its use in string? (JAN-16)


When declaring character arrays (strings), ‘\0’ (NULL) character is automatically added at
end. The ‘\0’ character acts as an end of character array.

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

52. What are global and local variables? (MAY-15)


A local variable is a variable whose existence is known only to a certain function or program.
Its scope is limited to a specific program block. For example, a variable declared in the main program
does not known to the function that is called in the main program.
Syntax:
void value(int a,int b)
{
int c,d; //local variables
}

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)

56. Explain parameter passing by reference? (May 2017,May-2014)


In this process, the addresses of the arguments are passed from a calling function to a called
function. Any changes made to these values in the called function, will modify the original values in
the calling function. This method is called parameter passing by reference.

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.

 UNCONDITIONAL CONTROL STATEMENT


The Execution of program can be altered by transferring the control from one place to
another in a program without specifying the condition. This statement is known as Unconditional
Control statement. GOTO is one of the Unconditional 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();
}

m: printf(“You are Eligible to vote”);


getch();
}

 CONDITIONAL CONTROL STATEMENT


Those statements, which is used to check the condition and based on the given condition,
carry out specific operations. Such type of statements is known as Conditional Control statement.
Conditional Control statement is mainly of two main types. They are
(i) Branching statements
(ii) Looping statements

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.

The If structure has the following syntax

13
MVIT UNIT-III T106-COMPUTER PROGRAMMING

Calculate the absolute value of an integer


# include < stdio.h > //Include the stdio.h file
void main ( ) // start of the program
{
int number; // Declare the variables
clrscr(); // clear the screen
printf (“Type a number:”); // message to the user
scanf (“%d”, & number); // read the number from standard input
if (number < 0) // check whether the number is a negative
number = - number; // If it is negative then convert it into positive.
printf (“The absolute value is % d \n”, number); // print the value
getch();
}

 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

// Program find whether a number is negative or positive */


14
MVIT UNIT-III T106-COMPUTER PROGRAMMING

#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.
}

 NESTED IF…ELSE STATEMENT


 It is otherwise known as Two-way with sub-way decisions.
 It is used to check with more than one Condition. If condition1 is true condition2 will be
checked and statement1 will be executed followed by statement2 will be executed.
 If condition1 is false statement3 will be executed. Otherwise default statement will be
executed. The syntax of Nested if…else statement as follows.

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

 SWITCH CASE STATEMENT


It is also known as selection statement. It helps to make decision from number of cases. The
syntax of Switch case statement is

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

Rules of using switch case


 Values for ‘case must’ be integer or character constants.
 Floating point values are not allowed as case label.
 Switch case should have one default label.(optional)
 Const Variable is allowed in switch Case Statement.
 The order of the ‘case’ statements is unimportant.
 Case Label must be unique
 Case labels must have constants / constant expression
 Case labels must end with (:) colon.
 Empty Switch case is allowed.
 Each compound statement of a switch case should contain break statement to exit
from case.
 Two or more cases may share one break statement
 Comparison operators are not accepted
 Nesting ( switch within switch ) is allowed.

18
MVIT UNIT-III T106-COMPUTER PROGRAMMING

Advantages of Using Switch statement


 Easier to debug
 Faster execution potential
 Easier to read
 Easier to understand
 Easier to maintain

LOOPING STATEMENTS (JAN 2016)

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

There are four types of Looping statements. They are


(i) while loop
(ii) do-while loop
(iii) for loop
(iv) nested for loop

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

The general form of while statement is

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.

 If the condition is true then the while loop will be executed.

The syntax of the do while loop is:

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

 Initialize counter: used to initialize counter variable


 Test condition: used to test the condition.
 Increment/decrement is used to increment/decrement the counter variable.

For loop example program:


/* The following is an example that finds sum of the first fifteen positive natural numbers*/
#include<stdio.h> //Include stdio.h file
#include<conio.h>
void main() //start main program
{
int i;
clrscr(); //declare variable
int sum=0,sumsqr=0; //declare and initialize variable.
for(i=0;i< = 30; i+=2) //for loop
{

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

 NESTED FOR LOOP


Loops containing more then one loops within itself is known as nested loop. Here outermost
loop will start to execute first but the process of outermost loop ends only when the condition of
innermost loop ends. Each loop must have a unique index variable. Each loop should be embedded
with each other. Loops can have any number of exit point but should not permit entry into it. Loops
should not overlap each other.

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

JUMPS IN LOOPS [Jan-2016, Jan-2014]


UNCONDITIONAL LOOP
(i) Break
(ii) Continue
(iii) Goto

 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

Implicit type conversion


 Implicit type conversion used to combine constants and variables of different types in an
expression. This automatic type conversion is known as implicit 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.

Rules for evaluating expressions


All short and char are automatically converted to int. Then
 If one operand is long double, the other will be converted to long double and result will be
long double.
 If one operand is double, the other will be converted to double and result will be double.
 If one operand is float, the other will be converted to float and result will be float.
 If one of the operand is unsigned long int, the other will be converted into unsigned long int
and result will be unsigned long int.
 If one operand is long int and other is unsigned int then
a. If unsigned int can be converted to long int, then unsigned int operand will be
converted as such and the result will be long int.
b. Else both operands will be converted to unsigned long int and the result will be
unsigned long int.
 If one of the operand is long int, the other will be converted to long int and the result will be
long int.
 If one operand is unsigned int the other will be converted to unsigned int and the result will be
unsigned int.

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

// Program to print the sum of N numbers


#include<stdio.h>
void main() Output:
{ enter N value 5
int i; Enter the 5 numbers
int num[] ,total=0,n; 10
printf(“enter N value”); 20
scanf(“%d”,&n); 60
printf(“Enter the %d numbers”,n); 80
for(i=0;i<n;i++) 40
{ The sum of 5 numbers is 210
scanf(“%d”,&num[i]);
total+=num[i]; /*calculate total*/
}
printf(“The sum of %d numbers is %d”,n,total);
getch();
}

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.

i) One Dimensional Array Declaration.


 An array with a single subscript is known as one dimensional array.
 It is otherwise known as single-subscribed (or) linear (or) one-dimensional arrays

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.

//Add ten numbers and find sum and average


#include<stdio.h>
#include<conio.h>
void main()
{
int i,num[10],sum=0;
float avg=0.0;
clrscr();
printf(“enter ten numbers:\n”);
for(i=0;i<10;i++)
{
scanf(“%d”,&num[i]);
sum+=num[i];
}

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

Array Initialization (Initializing an Array)


Array can be initialized in two ways. They are
a. at compile time and
b. at run time.
a)At compile time
Initialization in made at the time of declaration (in the declaration part) is known as compile
time initialization. The general form of initialization of arrays is:
Syntax:
datatype array-name[size] = {list of values};

Example:
int rollno[3] = {26,32,12};

 The value of array are enclosed in braces and separated by commas.


 The values are assigned to the array by assignment operator (=).
 If the number of values in the list is less than the number of elements, then only that
many elements will be initialized.
 The remaining elements will be set to zero automatically.

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

//Program to read marks using array initialization


#include<stdio.h>
#include<conio.h>
void main()
{
int studmark[5]={99,97,87,89,92};
int i;
clrscr();
printf(“ mark of the student is:\n”);
for(i=0;i<=4;i++)
{
printf(“\n Student Mark[%d]=%d\n”,i,studmark[i]);
}
getch();
}

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

/* Program to count the no of positive and negative numbers*/


#include< stdio.h >
#include<conio.h>
void main( )
{
int a[50],n,count_neg=0,count_pos=0,i;
clrscr();
printf(“Enter the size of the array\n”);
scanf(“%d”,&n);
printf(“Enter the elements of the array\n”);
for (i=0;i< n;i++)
scanf(“%d”,&a[i]);
for(i=0;i< n;i++)
{
if(a[i] < 0)
count_neg++;
else
count_pos++;
}
printf(“There are %d negative numbers in the array\n”,count_neg);
printf(“There are %d positive numbers in the array\n”,count_pos);
getch();
}
/*String.c string variable*/
#include < stdio.h >
#include<conio.h>
void main()
{
char month[15];
clrscr();
printf (“Enter the string”);
gets(month);
printf (“The string entered is %s”, month);
getch();
}

29
MVIT UNIT-III T106-COMPUTER PROGRAMMING

b)Run time array initialization


Array values can be initialized at run time. To initialize values at run time the n values
specified as input is being compared with the condition and each time executed.

//Input n numbers and display n numbers


#include<stdio.h>
#include<conio.h>
void main()
{
int a[100], i,n;
clrscr();
printf(“number of elements in array\n”);
scanf(“%d”,&n);
printf(“enter the elements\n”);
for(i=0;i<n-1;++i)
{
scanf(“%d”,&a[i])
}
printf(“elements in array\n”);
for(i=0;i<=n-1;++i)
{
printf(“%d\t”,a[i]);
}
getch();
}
// copy contents to another string
#include<stdio.h>
#include<conio.h>
void main()
{
char s1[10],s2[10]; int i=0;
clrscr();
printf(“enter first string:”); gets(s1);
/*copy content of s1 to s2*/
while(s1[i]!=’\0’)
{
s2[i]=s1[i];
i++;
} /*terminate second string*/
s2[i]=’\0’;
/*print the string*/
printf(“the output is :\n”);
puts(s2); puts(s1); getch();
}

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.

// Input 10 characters and print 10 characters


#include<stdio.h>
#include<conio.h>
void main()
{
char character[10];
int cnt;
clrscr();
/*read character one by one*/
printf(“enter 10 character\n”);
for(cnt=0;cnt<10;cnt++)
character[cnt]=getchar();
/*display character one by one*/
printf(“\nentered characters are :\n”);
for(cnt=0;cnt<10;cnt++)
putchar(character[cnt]);
}

//Count occurrence of desired character from a given string


#include<stdio.h>
#include<conio.h>
void main()
{
char s[80],c;
int i=0,n=0;
clrscr();
printf(“\n enter the string:”);
gets(s);
printf(“\n enter the character to search:”);
c=getchar();
for(i=0;s[i]!=’\0’;i++)
if(s[i]==c)
n++;
printf(“\n the character %c occurs %d times in %s”,c,n,s);
getch();
}

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

/*String.c string variable*/


#include < stdio.h >
void main()
{
char month[15];
clrscr();
printf (“Enter the string”);
gets (month);
printf (“The string entered is %s”, month);
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();
}

PASSING ARRAYS TO A FUNCTION


Array values are passed to a function as parameter. The name of the array is used as
Argument to a function. When an array is passed to the function, address of first array element is
passed to the function. Here array name must not be enclosed within brackets and it should not
include subscripts.
#include<stdio.h>
#include<conio.h>
Int num[5];
void main()
{
int i;
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”,num[i]);
sort(num);
printf(“\n the sorted list is:\n”);
for(i=0;i<5;i++)
printf(“\t%d”,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;
}

ii) TWO DIMENSION ARRAY


 Two dimensional array consist of (or) made up of two dimensions i.e., rows and columns.

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

 A Two Dimension Array takes the general form as follows.


data-type array-name[r] [c];

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 33 values. In general
for an array with n rows and c columns total number of values will be nc values.

Rules for Declaring Two-Dimensional Array


 For matrix addition and subtraction first matrix row, column and second matrix row, column
should be the same.
 For matrix multiplication, first matrix column and second matrix row must be equal.

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

Initializing an Two-Dimensional Array.


A Two-Dimensional Array can be also initialized. For that the array values are specified
within a Compound statement.
data-type array-name[r][c] = { value1, value2, .. .. .. , value n};

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.

a) Compile time initialization.


The two dimensional array can be initialized at the time of declaration is known as Compile
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]);
}
}

iii) MULTI-DIMENSIONAL ARRAY


 Multi-dimensional Array consists of (or) requires more than two square brackets and it may
contain any number of values specified within square brackets.

 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();
}

INITIALIZING MULTI-DIMENSIONAL ARRAY


 Multi-dimensional Array consists of (or) requires more than two square brackets and it may
contain any number of values specified within square brackets.

 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:

 It reduces the length of source program.


 Breaks the complexity of a program.
 Break small program into small program.
 It is easy to maintain, modify and understand.
 A program can be divided into smaller subprograms.
 It facilitates top down modular programming.
 The length of the source program can be reduced using functions
 Critical in microcomputers, where memory space is limited.
 Avoid rewriting the same sequence of code at two or more locations in a program.

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.

 Consider a set of statements shown below:


void display(void)
{
int i;
for(i=1;i<20;i++)
printf(“-”);
printf(“\n”);
}

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.

ELEMENTS OF USER-DEFINED FUNCTIONS

 User defined function has three elements. They are


i) Function definition
ii) Function call
iii) Function declaration

o Function definition is an independent program module that is specially written to


implement the requirements of the function.

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

 The syntax of a function definition to implement these two parts is as follows.

function-type function-name(parameter list)


{
 The first line local variable
indicates declaration;
function-type function-name (parameter list) is known as the function
header and the executable
statementsstatement1;
inside the braces constitute the function body.
executable statement2;
……………………..
FUNCTION HEADER
return statement
}
 It consists of three parts.
1. function type(return type)
2. function name
3. formal parameter list
Function Type
 It specifies the type of the value (like int, float or double) that the function is expected to return to
the program calling the function.

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

 Function body is enclosed in braces.

 Function body consists of three main parts. They are


1. Local declaration
2. Function statements
3. Return statements

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.

RETURN VALUE AND THEIR TYPES


 A function may or may not send back any value to the calling function. If it does, it is done
through the return statement.

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

ii) FUNCTION CALL


 A function can be called by simply using the function name followed by a list of actual parameter.
Example
main()
{
int y;
y=mul(8, 6);
printf(“%d\n”, y);
}
When a function is called, the control is transferred to the function mul(). This function is then
executed and a value is returned when return statement is used. This value is assigned to y. This is
illustrated below
main()
{
int y;
y=mul(8,6};
}
int mul(int x, int y)
{
int p;
p=x*y;
return(p);
}
The function calls sends two integer valued 8 and 6 to the function.

iii) FUNCTION DECLARATION


 Like variables, all functions in a C program must be declared, before they are invoked. It was
also known as Function prototype. It consists of four parts.
1. Function type ( return type )
2. Function name
3. Parameter list
4. Terminating semicolon

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

CATEGORY OF FUNCTIONS (or) FUNCTION PROTOTYPE


In general, functions can be classified into four categories depending upon the presence of the
following facts, They are
Arguments.
Return type.
TYPES OF USER DEFINED FUNCTIONS

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

 FUNCTIONS WITH ARGUMENTS AND WITH 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);
}

 FUNCTIONS WITH ARGUMENTS AND WITHOUT RETURN VALUES.

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

 A calling function sends value to arguments by means of function call.


Input
Calling Called
No output
Function 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.

Example: Program to find the largest of two numbers using function

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

 FUNCTIONS WITHOUT ARGUMENTS AND WITH RETURN VALUES.

 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

Example: No Argument and return value

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

iii) FUNCTIONS WITHOUT ARGUMENTS AND WITHOUT RETURN VALUES.


 When a function has no Argument it does not receive any data from the calling function. When a
function does not return value, calling function does not receive data from the called function.

 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

Example: Program to illustrate a function with no argument and no return values


#include<stdio.h> // Header file
#include<conio.h>
void main() // main function
{ // beginning of c program
long i, j,x=1; // variable declaration
void square(); // Function declaration or function prototype
clrscr(); // clear the screen
printf(“\n Enter a number :”); // output the text
scanf(“%ld”,&i); // read number i
for(j=1;j<=i;j++)
x=j*x;
printf(“\nThe Factorial of %ld is %ld”,i,x);
square(); // Function call
getch();
}
void square()
{
int i,n,s,d,sum=0;
printf(“Enter the range:”); scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
s=d*d; sum+=s;
printf(“Square of %d is %d”,i,s);
}
printf(“\n Sum of squares is %d”,sum);
}

RECURSION (Recursive Function)


 When a function is called repeatedly by itself until the condition is TRUE, then it is known as
Recursion. A function is called recursive if a statement within the body of a function calls the
same function.
Example:
#include<stdio.h>
#include<conio.h>
long fact(long);
void main()
{
long num, fac;
clrscr();
printf(“Enter a number : “);
scanf(“%ld”,&sum);
fac=fact(num);
printf(“The factorial of %ld is %ld”,num,fac);
getch();
}
long fact(long x)
{

46
MVIT UNIT-III T106-COMPUTER PROGRAMMING
if(x<=1)
return(1);
else
return(x*fact(x-1));
}

SCOPE OF THE VARIABLE


 The range within which the variable will be active in a program is known as the scope of a
variable. If a variable is used outside the program then the scope of the variable is limited.

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

PASSING ARRAYS TO FUNCTIONS

 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

float largest(float array[], int size)

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

 The declaration of the formal argument array is made us follows


float array[];

47
MVIT UNIT-III T106-COMPUTER PROGRAMMING

Example: To pass an array to a function, pass the array name.


// Max of n numbers
#include<stdio.h>
void main()
{
int i,m,n;
int a[100];
int big(int [ ],int);
clrscr();
printf(“\n Enter the total number to be given as input:”);
scanf(“%d”,&n);
printf(“\n Enter the number one by one\n”);
for(i=0;i<=n;i++)
scanf(“%d”,&a[i]);
m=big(a,n);
printf(“\n The maximum number in the list is %d”,m); getch();
getch();

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

PASSING ARGUMENT TO FUNCTION

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

 The storage class of a variable tells the compiler


 Storage area of the variable
 Initial value of the variable if not initialized
 Scope of the variable
 Life of the variable, that is, how long the variable would be active in the program.

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

Example1: Program to illustrate how automatic variables work


#include<stdio.h>
#include<conio.h>
void function1(void);
void function2(void);
main()
{
auto int m=2000;
function2();
Output:
printf(“%d\n”,m);
} 10
void function1(void) 100
{
int m=10; 2000
printf(“%d\n”,m);
}

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.

Example1: Program to illustrate how External variables work


#include<stdio.h>
#include<conio.h>
int fun1(void);
int fun2(void);
int fun3(void);
extern int x; /*GLOBAL declaration*/
main()
{
x=10;
printf(“x=%d\n”, x);
printf(“x=%d\n”, fun1());
printf(“x=%d\n”, fun2());
printf(“x=%d\n”, fun3());
}

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.

Example1: Program to illustrate how static variables work


#include<stdio.h>
#include<conio.h>
void start(void);
void main()
{ int i;
clrscr(); OUTPUT
for(i=1;i<3;i++)
stat(); x=1
getch(); x=2
}
void stat(void) x=3
{
static int x=0;
x=x+1;
printf(“x=%d\n”,x);
}

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.

 Register variable declared using keyword register.

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

Example: Program to illustrate how Register variables work


#include<stdio.h>
#include<conio.h>
void main()
{
register int x;
clrscr();
for(x=1;x<=10;x++)
printf(“%d”,x);
getch();
}

STRINGS

 A string is a sequence of character that is treated as single data item.

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

o Reading and writing strings


o Combining strings together
o Copying one string to another
o Comparing strings for equality
o Extracting a portion of string

 Declaration & Initialization of Strings

 C does not support strings as a data type. But it allows us to represent strings as character
arrays.

 The general form of declaration of a string variable is

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.

char city [9] = “ NEW YORK”;


char city [9] ={‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’};

 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

char string []={‘I’,’N’,’D’,’I’,’A’,’\0};


defines the string as 6 element array.

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

 Reading strings from the terminal

54
MVIT UNIT-III T106-COMPUTER PROGRAMMING

 Scanf can be used with %s format specification to read in a string of characters


For example:
char address [10];
scanf(%s”, address);

 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

Consider the Following statements:


char name[10];
scanf (“%5s”, name);

Example1:

The input string “HAI” will be stored as

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

 Reading a line of text

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

 For example consider the following program segment


char line[80];
scanf(“%[^\n],line];
printf(“%s”,line);
will read a line of input from the keyboard and display the same on the screen

55
MVIT UNIT-III T106-COMPUTER PROGRAMMING

Using getchar and gets functions


 We already discussed how to read a single character from the terminal using the function getchar.

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

 The getchar function call takes the form


char ch;
ch=getchar();

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

 Writing Strings to 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);

can be used to display the entire contents of the array name.


 We can also specify the precision with which the array is displayed. For example the
specification %10.4s indicates that the first four characters are to be printed in a field width of 10
columns.

Example Program: Display the string under various format specification


#include<stdio.h>
#include<conio.h>
main()
{
char state[15]=”Andhra Pradesh”; OUTPUT
printf(“\n\n”);
printf(“--------------------------\n”); ----------------------------
printf(“%15s\n”, state); Andhra Pradesh
printf(“%5s\n”, state); Andhra Pradesh
printf(“%15.6s\n”, state); Andhra
printf(“%-15.6s\n”, state); Andhra
printf(“%15.0s\n”, state);
And
56 Andhra Pradesh
----------------------------
MVIT UNIT-III T106-COMPUTER PROGRAMMING
printf(“%.3s\n”, state);
printf(“%s\n”, state);
printf(“--------------------------\n”);
}

Using Putchar and puts function


 Like getchar, C supports another character handling function putchar to output the values of
character variables. It takes the following form
char ch=’A’;
putchar(ch);

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.

For example consider the following program segment


char line(80);
gets(line);
puts(line);
reads a line of text from the keyboard and displays it one screen. This syntax is very simple compared
to using the scanf and printf functions

STRING LIBRARY FUNCTIONS or STRING HANDLING FUNCTIONS

 C compiler supports a large number of string handling library functions that can be used to carry out
many of the string manipulations.

 Most important string handling functions are:

57
MVIT UNIT-III T106-COMPUTER PROGRAMMING

1. strlen() Function – String Length


The process of finding the number of characters in a string with the help of strlen(). This
function counts and returns the number of characters in a given string.
n = strlen(string);
Example Program
#include<stdio.h>
#include<conio.h> OUTPUT
#include<string.h> Enter the text
main()
{
Welcome
char text[20]; Length of the string: 7
int len;
clrscr();
printf(“Enter the text:\n”);
gets(text);
len=strlen(text);
printf(“length of the string=%d”,len);
}
2. strcpy()function – String Copy
This function almost like a string-assignment operator. this function copies the contents of
one string to another. The format of strcpy() is
strcpy(string1, string2);

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

3. strcmp() function – String Comparison


It is used to compare two strings identified by the arguments and has a value 0 if they are
equal.
Syntax:
strcmp(string1,string2);

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: Joining two strings


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main
{
OUTPUT
char text1[30], text2[30];
puts(“enter text1”); Enter text1 : Have a
gets(text1); Enter text2 : nice day
puts(“enter text2”);
puts(text2); Have a nice day
strcat(text1,” “);
strcat(text1, text2);
clrscr();
printf(“%s\n”, text1);
}

5. strrev() Function – String Reverse


This function simply reverses the given string. The format of this function is
strrev(sring);

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

STRING LIBRARY FUNCTION (ADDITIONAL)

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.

The format of the function is


strncpy(destination, source, n);
Example Program
#include<stdio.h>
Output:
#include<conio.h>
#include<string.h> Enter source string : wonderful
void main Enter destination string : beautiful
{
char str1[15],str2[15]; Enter number of characters to replace in destination: 6
int n; Source string : wonderful
clrscr();
Destination string : wonderful
printf(“enter source string:”);
gets(str1);

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

5. strlwr & strupr() function


strlwr function an be used to convert any string to a lower case. When you are passing any
upper case string to this function it converts it into lower case. Strupr() function can be used convert
lower case to upper case.
The format of strlwr() function is strlwr(string);
The format of strupr() function is strupr(string);

Example Program(Upper case to lower case):


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main OUTPUT
{
Enter string in upper case: WELCOME
char str1[15];
After strlwr : welcome
clrscr();
printf(“enter string in upper case:”);
gets(str1);
printf(“after strlwr(): %s”, strlwr(str1));
}

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

Example Program: Entering the string and getting the duplicate


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main
{ OUTPUT
char text1[15], *text2;
Enter text: Have a nice day
clrscr();
printf(“enter text:”); Original string: Have a nice day
gets(text1);
Duplicate string: Have a nice day
text2=strudp(text1);
printf(“Original string=%s\n Duplicate String:%s”, text1,text2);
}

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

Example Program: Joining two strings


#include<stdio.h>
#include<conio.h>
#include<string.h> OUTPUT
void main()
Enter text1 : Have a
{
char text1[30], text2[30]; Enter text2 : nice day
int n; Enter number of characters to add: 4
puts("enter text1");
gets(text1); Have a nice
puts("enter text2");
gets(text2);
printf("enter number of characters to add:");
scanf("%d",&n);
strcat(text1," ");
strncat(text1,text2,n);
printf("%s\n",text1); }

11. strset() Function

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

13. strspn() Function


This function returns the position of the string from where the source array does not match
with target one. The format of this function is

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

The format of this function is


strpbrk(text1,text2)
Example Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main
{
char *ptr;
char text1[20], text2[2];
clrscr();
puts(“enter text1”); OUTPUT
gets(text1); Enter text1 : Have a nice day
puts(“enter character”);
gets(text2); Enter character: n
ptr=strpbrk(text1,text2); string from given character: nice day
puts(“string from given character”);
printf(ptr);
}

IMPORTANT PROGRAMS –UNIVERSITY QUESTIONS

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

2. INSERTION SORT (Example for One – dimensional array)


#include<stdio.h>
void main()
{
int a[50], n, i, val;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Enter %d values", n);
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("Before Sorting\n");
for(i = 0; i < n; i++)
{
printf("%d\t", a[i]);
}
for(i = 0; i < n; i++)
{
val=a[i];
int j=i;
while(val < a[j-1] && j > 0)
{
a[j] = a[j-1];
j--;
}

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

3. SELECTION SORT (Example for One – dimensional array)


#include <stdio.h>
main()
{
int n, i, j, x, min, a[50];
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Enter %d values", n);
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("Before Sorting\n");
for(i = 0; i < n; i++)
{
printf("%d\t", a[i]);
}
for(i = 0; i < n; i++)
{
min=i;
for(j = i+1; j < n; j++)
{
printf("\n%d==%d\n", a[min], a[j]);
if(a[min] > a[j])
{
min = j;
}
}
if(min != i)
{
x = a[min];
a[min] = a[i];
a[i] = x;
}
}
printf("\nAfter sorting\n");
for(i = 0; i < n; i++)
{
printf("%d\t", a[i]);
}
}

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

6. SMALLEST & LARGEST IN AN ARRAY


(Example for One – dimensional array)
#include<stdio.h>
#inlcude<conio.h>
main()
{
int i,n,a[30],large,small;
clrscr();
printf(“Enter the no. of terms:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i];
}
large=a[0];
small=a[0];
for(i=0;i<n;i++)
{
if(a[i]>large)
large=a[i];
else if(a[i]<small)
small=a[i];
}
printf(“Largest element in array is %d”,large);
printf(“Smallest element in array is %d”,small);
getch();
}

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

Enter the second Matrix


123
212
311

72
MVIT UNIT-III T106-COMPUTER PROGRAMMING

Display Addition matrix


246
424
622

8. MATRIX MULTIPLICATION (Example for two – dimensional array) ( Jan 2005,2006,2014,


(Nov/Dec 2015,May/June 2016)
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[2][2], b[2][2],c[2][2],i,j;
int i,j,k;
clrscr();
printf("Enter first matrix:\n" );
for( i=1;i<=3;i++)
{
for( j=1;j<=3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter second matrix:\n");
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]=0;
for(k=1;k<=3;k++)
{
c[i][j] =c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("Matrix Multiplication Is: \n");
for(i=1;i<=3;i++)
{
for (j=1;j<=3;j++)
{
printf("%d\n",c[i][j]);
}
}
getch();
}

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

9. MATRIX TRANSPOSE (Example for two – dimensional array)


#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,a[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("Transpose Matrix");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
printf("%d\t",a[j][i]);
}
printf(“\n”);
}
getch();
}

Output
Enter the First Matrix
123
234
587
Transpose Matrix
125
238
247

STRING HANDING PROGRAM WITHOUT USING STRING HANDLING FUNCTION

10. STRING COMPARE


#include<stdio.h>
#include<conio.h>
main()
{
int length1 = 0, length2 = 0, i = 0,c = 0;

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

11. STRING CONCATENATION


#include<stdio.h>
#include<conio.h>
main()
{
int i, j = 0;
char str1[25], str2[25], str3[50];
clrscr();
printf("Enter the first string:");
gets(str1);
printf("Enter the second string:");
gets(str2);
i = 0;
while(str1[i] != '\0')
{
str3[j++] = str1[i];
i++;
}
i = 0;
while(str2[i] != '\0')
{
str3[j++] = str2[i];
i++;

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

12. STRING COPY


#include<stdio.h>
#include<conio.h>
main()
{
int i=0;
char str[25], copystr[25];
clrscr();
printf("Enter the string:");
gets(str);
while(str[i] != '\0')
{
copystr[i] = str[i];
i++;
}
copystr[i] = '\0';
printf("The copied string is %s", copystr);
getch( );
}

Output
Enter the string: success
The copied string is success

13. STRING LENGTH (NOV/DEC 2014)


#include<stdio.h>
#include<conio.h>
main()
{
int length=0;
char str[25];
clrscr();
printf("Enter the string:");
gets(str);
while(str[length] != '\0')
{
length++;
}
printf("The length of the string %s is %d", str, length);
getch( );
}

Output
Enter the string: success
The length of the string success is 7

14. VOWELS & CONSONANTS (May/June 2016)

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

15. PALINDROME STRING (May/June 2016)


#include<stdio.h>
#include<conio.h>
main()
{
int length=0, i, j = 0, c = 0;
char str[25], revstr[25];
clrscr();
printf("Enter the string:");
gets(str);
while(str[length] != '\0')
{
length++;
}
for(i = length-1; i >= 0; i--)
{
revstr[j] = str[i];
j++;

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

16. REVERSE THE STRING ( Jan 2010)


#include<stdio.h>
#include<conio.h>
main()
{
int length=0, i, j = 0, c = 0;
char str[25], revstr[25];
clrscr();
printf("Enter the string:");
gets(str);
while(str[length] != '\0')
{
length++;
}
for(i = length-1; i >= 0; i--)
{
revstr[j] = str[i];
j++;
}
revstr[j] = '\0';
printf(“The reverse string:”);
puts(revstr);
getch( );
}

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

UNIVERSITY QUESTIONS – PART A

1. Define Recursion. (MAY-13, JAN-14, JAN-15, JAN-16, JAN 2010,apr/May-2018)


2. What is a null character? What is its use in string? (JAN-16)
3. What are global and local variables? (MAY-15)
4. What is meant by looping and explain its types? (JAN-13, MAY-14, MAY-15)
5. State the advantages of the use of functions. (MAY-2012, JAN 2010)
6. Differentiate do-while and while statements? (MAY 2017, JAN-2013)
7. What is the difference between functions declaration and function definitions?
8. State the difference between break and continue statement. (MAY 2015)
9. How the actual arguments match with formal arguments? (JAN 2013)
10. Explain parameter passing by reference? (May 2017,May-2014)
11. How does an array definition differ from an ordinary variable? (MAY-2012)
12. Define array and write its type. (MAY-2015)
13. Write any four features of arrays. (MAY 2016)
14. How strings are represented in C language? (MAY 2016)
15. Explain any two string functions with example. (NOV 2016,JAN 2011,May-2019)
16. List any five built in string functions. (MAY 2017)
17. Write the syntax of else-if statements.[Apr/May-2018]
18. Difference between Auto and Static storage classes. (Nov-2018)
19. Write a program to create an array of 10 integers.

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)

21. Elucidate the two dimensional arrays with an example.[Apr.May-2018]


22. Define Recursion. Write a C program to. find the Factorial of a number using Recursian.
(Nov-2018)
80
MVIT UNIT-III T106-COMPUTER PROGRAMMING
23. a) Elaborate on 'for' and 'while' loops in C. (8)
b) Give general form of Passing Arrays to Function and Explain. (3) [May2019]
24. Explain the switch statement in C through an example. (5) [May2019]

81

You might also like