Updated C Programming Unit 3 Final
Updated C Programming Unit 3 Final
ARRAY
Array: Arrays is a data structure that can store a collection of elements of the same data type. Instead of
declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable
such as numbers[100] and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
A specific element in an array is accessed by an index. The rule for giving the array name is same as the ordinary
variable. The index specifies the location of the element in the array. The array index starts from zero. The
maximum index value will be equal to the size of the array minus one.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the
highest address to the last element.
Since an array provides a convenient structure for representing data, it is classified in following types based
on the number of subscripts in array:
1. One-dimensional arrays
2. Multidimensional arrays
This is also called a single-dimensional array. A one dimensional array has one subscript.
Declaration of one dimensional array: Like a variable, array should also be declared before they are used
in the program. The syntax for declaration of a one dimensional array is-
Datatype ArrayName[Size];
Here ArrayName denotes the name of the array and it can be any valid C identifier, Datatype is the datatype
of the elements of array. The Size of the array specifies the maximum number of elements that can be stored
in the array.
For example:
1. float marks[10]; Here marks is a variable array which is sufficient to hold up to 10 double numbers.
2. Assume that in a company we want to store the data of 50 employees, like employee id, age, salary
so, It can be declared as:
int emp_id[50];
int age[50];
float salary[50];
Note: Here, as the size of all the arrays is 50 means we can store data of maximum 50 employees not more
than that. The individual elements of the above arrays are:
1
When an array is declared, the compiler allocates sufficient space in memory to hold all the elements
of the array, so the size of array should be known at the compile time. Hence we can’t use the variable for
specifying the size of array in the declaration.
We can use either integer constants as given above or symbolic constants to declare the size of an array.
#define SIZE 10
main()
{
float salary[SIZE]; // Size declared using symbolic constant i.e 10
int age[15]; // Size declared using integer constant i.e. 15
................
................
}
Note: The use of symbolic constant to specify the size of array makes it convenient to modify the program
if the size of array is to be changed later, because the size has to be changed only at one place, in the #define
directive.
90 78 89 86 99
0 1 2 3 4 Index
The number of values between braces { } cannot be larger than the number of elements that we
declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write –
The number of values between braces { } can be greater than the size of array declared in square
brackets [ ]. So, here extra locations will be given value 0.
90 78 89 86 99 0 0 0
0 1 2 3 4 5 6 7 Index
Accessing one dimensional Arrays: Each array elements can be accessed with the index number. For
example:
Syntax: array_name[index number]
90 78 89 86 99
0 1 2 3 4
2
Here, marks[0]= 90
marks[1]=78
marks[2]= 89
marks[3]=86
marks[4]= 99
B.Two-Dimensional array
Datatype arrayname[RowSize][ColumnSize];
Where Datatype can be any valid C data type and arrayname will be a valid C identifier. Here RowSize is
the number of rows and ColumnSize is the number of columns. A two-dimensional array a, which contains
three rows and four columns can be shown as follows −
3
Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where 'a' is the
name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'.
0 1 2 3
4 5 6 7
8 9 10 11
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to the previous example −
int a[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
Every element in array matrix is identified by an element name of the form matrix[ i ][ j ]; matrix is
the name of the array, and i and j are the subscripts that uniquely identify each element in matrix. In the
case of Two-dimensional array, during declaration the maximum number of rows and maximum number of
column should be specified for processing all array elements.
Accessing two dimensional Array elements: Each array elements can be accessed with the index number.
For example:
Syntax: array_name[Row index number][Column index number]
for(i=0; i<r1; ++i) /* Multiplying matrix a and b and storing in array mult. */
{
for(j=0; j<c2; ++j)
{
mult[i][j]=0;
for(k=0; k<c1; ++k)
mult[i][j] += (a[i][k]*b[k][j]);
}
}
printf("\nOutput Matrix:\n"); /* Displaying the multiplication of two matrix. */
for(i=0; i<r1; ++i)
5
{
printf("\n");
for(j=0; j<c2; ++j)
printf("%d\t ",mult[i][j]);
}
}
else
printf(“ Multiplication not possible as number of columns of matrix 1 not equal to number of rows
of matrix 2\n”);
SEARCHING
The process of finding a particular item in the large amount of data is called searching. We have 2 types of
Searching techniques:
1. Linear search
2. Binary search
A linear search is the basic and simple search algorithm. A linear search searches an element or key
value from an array till the desired element or value is found. And it searches in a sequence order. It compares
the element with all the other elements given in the list and if the element is matched it returns the value i.e
successful search. If element is not found then it is called unsuccessful search. Linear Search is applied on
the unsorted or unordered list when there are fewer elements in a list.
Linear search technique is also known as sequential search technique. The linear search is a method
of searching an element in a list in sequence. In this method, the array is searched for the required element
from the beginning of the list/array or from the last element to first element of array and continues until the
item is found or the entire list/array has been searched.
ADVANTAGES:
1.It is simple and conventional method of searching data.
2.The elements in the list can be in any order. i.e. The linear search can be applied on sorted or unsorted
linear data structure.
3. works well for small arrays.
Disadvantage:
1. Less efficient if the array size is large.
2.It consumes more time and reduces the retrieval rate of the system.
ALGORITHM:
Step 1: Set-up a flag to indicate “element not found”
Step 2: Take the first element in the list
Step 3: If the element in the list is equal to the desired element
Set flag to “element found”
Display the message “element found in the list”
Go to step 6
Step 4: If it is not the end of list,
Take the next element in the list
Go to step 3
Step 5: If the flag is “element not found”
Display the message “element not found”
Step 6: End of the Algorithm
6
PROGRAM TO PERFORM LINEAR SEARCH:
# include<stdio.h>
main()
{
int array[100], k, i, n,flag=0;
printf("Enter the number of elements in array\n");
scanf("%d",&n);
printf("Enter %d integer(s)\n", n);
Binary Search:
To overcome the disadvantages of linear search, we use Binary Search. It is applied on the sorted array or
list. It is a simple and efficient searching techniques which can be applied if the items to be compared are
either in ascending order or descending order.
Binary search first compares the key value with the elements in the middle position of the array. If the key
value is matched, then returns the position. If the value is less than the middle element, then it must lie in the
lower half of the array and if it's greater than the element then it must lie in the upper half of the array. We
repeat this procedure on the lower (or upper) half of the array. Binary Search is useful when there are large
numbers of elements in an array.
ADVANTAGES:
1.It is simple method of searching data.
2.very efficient searching techniques.
3. works with both small arrays as well as larger arrays.
7
Algorithm for Binary Search
Write a c program to search an element in an array using binary search. (Lab program)
8
COMPARING THE TWO:
• Binary search requires the input data to be sorted; linear search doesn't.
• Binary search requires an ordering comparison; linear search only requires equality comparisons.
• Binary search has complexity O(log n); linear search has complexity O(n).
• Binary search requires random access to the data; linear search only requires sequential access.
Disadvantage is that it can take N scans, where N is the size of the array or list, because an out of position
item is only moved one position per scan.
9
1. Write a C program to sort a set of n elements using bubble sort
OR
Design a program for bubble sort. (Lab program)
10
FUNCTIONS:
WHAT IS C FUNCTION?
In programming, a function is a segment that groups code to perform a specific task. A large program
can be divided into many functions. Function contains set of instructions enclosed by “{ and }” which
performs specific operation in a program.
A C program has at least one function i.e main(). Without main() function, there is technically no C
program, and main() is user defined function.
Types of C functions:
There are two types of functions in C programming:
Library function/ Inbuilt function
User defined function
11
LIBRARY FUNCTIONS
Library functions are the in-built function in which C is programming language. For example:
printf(), scanf() are library functions defined in stdio.h header file in C.
sqrt(), pow() are the library functions defined in math.h header file in C.
As mentioned earlier, every C program begins from main() and program starts executing the codes inside
main() function. When the control of program reaches to function_name() inside main() function. The control
of program jumps to void function_name() and executes the codes inside it. When all the codes inside that
user-defined function are executed, control of the program jumps to the statement just after function_name()
from where it is called. Analyze the figure below for understanding the concept of function in C
programming.
12
Write a C program to add two integers. Make a function add to add integers and display sum in main()
function.
#include<stdio.h>
int add(int a, int b); //function prototype(declaration)
int main()
{
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2);//function call
printf("sum=%d",sum);
return0;
}
int add(int a, int b) //function definition
{
int c;
c=a+b;
return c; //return statement of function
}
ELEMENTS OF FUNCTIONS:
To use a user defined function in C we need to take care of 3 things i.e.
1. Function declaration
2. Function calling
3. Function definition.
1. Function prototype (declaration):
Every function in C programming should be declared before they are used. This type of declaration
are also called function prototype. Function prototype gives compiler information about function name, type
of arguments to be passed and return type.
Syntax of function prototype
return_type function_name (type(1) argument(1),…………………….....,type(n) argument(n));
Here , return type can be any valid C datatype like int, float, char etc. and if the function is not
returning any value return type is void. List of arguments is also called as parameter list.
In the above example, int add(int a, int b); is a function prototype which provides following
information to the compiler:
1. name of the function is add()
2. return type of the function is int.
3. two arguments of type int are passed to function.
Function prototype or declaration are not needed if user-definition function is defined before main() function.
13
2. Function call:
Control of the program cannot be transferred to user-defined function unless it is called invoked.
Syntax of function call
function_name(argument(1),.............................argument(n));
In the above example, function call is made using statement add(num1,num2); from main(). This
make the control of program jump from that statement to function definition and executes the codes inside
that function.
3. Function definition:
Function definition contains programming codes to perform specific task.
Syntax of function definition
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
//body of function
}
In above example the function is defined as
int add(int a,int b) //function definition
{
int c;
c=a+b;
return c; //return statement of function
}
RETURN STATEMENT
Return statement is used for returning a value from function definition to calling function.
Syntax of return statement
return (expression);
For example:
return a;
return (a+b);
In above example, value of variable add in add() function is returned and that value is stored in
variable sum in main() function. The data type of expression in return statement should also match the return
type of function.
14
CATEGORIES OF FUNCTIONS IN C PROGRAMMING
For better understanding of arguments and return type in functions, user-defined functions can be
categorized as:
1. Function with no arguments and no return value
2. Function with no arguments and return value
3. Function with arguments but no return value
4. Function with arguments and return value.
C PROGRAM TO ADD TWO NUMBERS USING ALL TYPES OF USER DEFINED FUNCTIONS:
1. Function with no arguments and no return value
#include<stdio.h>
void add(void); // Function declaration No return type and No arguments
int main( )
{
add(); //Function calling .No argument is passed to add().
Return 0;
}
/* There is no return value to calling function main(). Hence, return type of add() is void */
15
2. Function with no arguments and return value
#include<stdio.h>
int add(void); // Function declaration with return type int and no agruments
int main()
{
int sum;
sum= add(); // Function call with no arguments
printf(“sum=%d”,sum);
return 0;
#include<stdio.h>
void add(int a, int b); // Function declaration no return type but with agruments
int main()
{
int num1, num2;
printf(“Enter two integers”);
scanf(“%d%d”,&num1,&num2);
add(num1,num2); // Function call with arguments
return 0;
}
#include<stdio.h>
Int add(int a, int b); // Function declaration with return type and agruments
int main()
{
int num1, num2,sum;
printf(“Enter two integers”);
scanf(“%d%d”,&num1,&num2);
sum=add(num1,num2); // Function call with arguments
printf(“sum=%d”,sum);
return 0;
}
16
void add(int a,int b) //Function definition
{
return (a+b); // Function returns addition of two numbers
}
1. Call by value:
This method copies the actual value of an argument into the formal parameter of the function. In this
case, changes made to the parameter inside the function have no effect on the argument.
In call by value method, the value of the variable is passed to the function as an actual parameter and
copy will be created in form of formal parameter.
The value of the actual parameter cannot be modified by the function.
Different Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.
Note:
Actual arguments: The arguments that are passed/ used in a function call are called actual
arguments. These arguments are defined in the calling function.
Formal arguments: The formal arguments are the parameters/arguments which are used in a
function declaration/ definition. The scope of formal arguments is local to the function definition in
which they are used. Formal arguments belong to the called function. Formal arguments are a copy
of the actual arguments. A change in formal arguments would not be reflected in the actual arguments.
17
x = y; /* put y into x */
y = temp; /* put temp into y */
}
Output:
Before swap, value of a : 100 and value of b : 200
After swap, value of a : 100 and value of b : 200
It shows that there are no changes in the values of actual arguments i.e a and b , though they had been changed
inside the function for formal arguments i. e. x and y.
#include<stdio.h>
void swap(int *p,int *q); /* function declaration */
main ()
{
int a =100, b =200; /* local variable definition */
Output:
Before swap, value of a : 100 and value of b : 200
After swap, value of a : 200 and value of b : 100
It shows that the change has reflected outside the function as well, unlike call by value where the changes do
not reflect outside the function.
18
Explanation
Here in the main ( ) function we have declared two variables a and b with values 10 and 20 respectively. So
we have in memory:
When we call the swap ( ) function by address, two pointer variables x and y are created and they contain
the addresses of a and b respectively. So we have in memory now:
Inside the swap ( ) function we have interchanged the values of x and y. Since x and y point to a and b, any
changes made to x and y will affect a and b. So after swap function we have in memory:
19
arguments carefully else you get unexpected
results.
Execution is slower since all the values have to Execution is faster since only addresses are
be copied into formal parameters copied.
20
Strings
In C programming, array of character are called strings. A string is terminated by null character
\0. For example: "c string tutorial"
Here, "c string tutorial" is a string. When, compiler encounters strings, it appends null character at
the end of string.
Declaration of strings
Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char type.
char s[5];
Initialization of strings
In C, string can be initialized in different number of ways.
char c[]="abcd"; OR, char c[5]="abcd";
OR,
char c[]={'a','b','c','d','\0'}; OR; char c[5]={'a','b','c','d','\0'};
Printing Strings.
1.Using printf():
char c[20];
printf("%s",c);
printf() function is defined in stdio.h header file and it prints the string until null charater ‘\0’ occurred.
2.Using puts():
puts() function is defined in stdio.h header file and it prints the string until null charater ‘\0’ occurred.
21
C program to read and print a string using scanf() and printf().
#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s\n",name);
return 0;
}
Output
Enter name: Dennis Ritchie
Your name is Dennis.
Here, program will ignore Ritchie because, scanf() function takes only string before the white space.
String Handling (Library) functions: Strings are often needed to be manipulated by programmer
according to the need of a problem. All string manipulation can be done manually by the
programmer but, this makes programming complex and large. To solve this, the C supports a large
number of string handling functions.
There are numerous functions defined in "string.h" header file. Few commonly used string handling
functions are discussed below:
22
1. strlen(): In C, strlen() function calculates the length of string. It takes only one argument, i.e, string
name.
2.strcpy(): Function strcpy() copies the content of one string to the content of
another string. It takes two arguments.
Syntax of strcpy(): strcpy(destination,source);
Here, source and destination are both the name of the string. This statement, copies the
content of string source to the content of string destination.
3.Strcat(): In C programming, strcat() concatenates(joins) two strings. It takes two arguments, i.e, two
strings and resultant string is stored in the first string specified in the argument.
5.Strlwr(): In C programming, strlwr() function converts all the uppercase characters in that string to
lowercase characters. The resultant from strlwr() is stored in the same string.
Syntax of strlwr(): strlwr(string_name);
ASCII value of 'A' is 65 while 'a' is 97. Difference between them is 97 – 65 = 32
So if we will add 32 in the ASCII value of 'A' then it will be 'a' and if will we subtract 32 in ASCII value of
'a' it will be 'A'. It is true for all alphabets.
In general rule:
Upper case character = Lower case character – 32
Lower case character = Upper case character + 32
6.strupr():In C programming, strupr() function converts all the lowercase characters in that string to
uppercase characters. The resultant from strupr() is stored in the same string.
Syntax of strupr():strupr(string_name);
Some programming examples without using and with using library function:
1.C Program to Find the Length of a String using library function strlen().
#include <stdio.h>
#include <string.h>
int main()
{
char str[50];
printf("Enter a string: ");
gets(str);
printf("Length of string: %d",strlen(str));
return 0; }
Output
Enter a string: REVA
Length of string: 4
23
2.C Program to copy a String using library function strcpy().
#include <stdio.h>
#include <string.h>
int main()
{
char str1[50], str2[50];
printf("Enter a string: ");
gets(str1);
#include<stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("Enter a string");
gets(str);
4.C Program to compare two strings without using library function strcmp().
#include<stdio.h>
int main()
{
char str1[50],str2[50];
int i=0,n;
printf("Enter string1");
gets(str1);
printf("Enter string2");
gets(str2);
while(str1[i]!=’\0’)
{
if(str1[i]==str2[i])
i++;
else
break;
24
}
n= str1[i]- str2[i];
if(n>0)
printf(“\n%s is greater than %s”,str1,str2);
else if(n<0)
printf(“\n%s is greater than %s”,str2,str2);
else
printf(“\n%s and %s are equal”,str1,str2);
return 0;
}
Output
Enter String1 CHENNAI
Enter String2 CHENNAI
#include<stdio.h>
#include <string.h>
int main()
{
char str1[50],str2[50];
int n;
printf("Enter string1");
gets(str1);
printf("Enter string2");
gets(str2);
n= strcmp(str1,str2);
if(n>0)
printf(“\n%s is greater than %s”,str1,str2);
else if(n<0)
printf(“\n%s is greater than %s”,str2,str2);
else
printf(“\n%s and %s are equal”,str1,str2);
return 0;
}
Output
Enter String1 BANGALORE
Enter String2 BIJAPUR
6.C Program to concatenate(merge) two strings without using library function strcat().
#include<stdio.h>
int main()
{
char str1[50],str2[50],str3[100];
25
int i=0,j=0;
printf("Enter string1");
gets(str1);
printf("Enter string2");
gets(str2);
i++;
j++;
}
i=0;
while(str2[i]!=’\0’) //copy string2 to string3
{
str3[j]=str2[i];
i++;
j++;
}
str3[j]=’\0’; //Add Null to string3
printf(“Concatenated string is :”);
puts(str3);
return 0;
}
Output
Enter String1 Good
Enter String2 Morning
#include<stdio.h>
#include <string.h>
int main()
{
char str1[50],str2[50];
printf("Enter string1");
gets(str1);
printf("Enter string2");
gets(str2);
strcat(str1,str2);
26
Pointer
What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location. Like any variable or constant, you must declare a pointer before using it to store any variable
address. The general form of a pointer variable declaration is −
Here, type is the pointer's type; it must be a valid C data type and var-name is the name of the pointer
variable. The asterisk * is being used to designate a variable as a pointer. Take a look at some of the valid
pointer declarations −
Pointers are the powerful feature of C and (C++) programming, which differs it from other popular
programming languages like: java and Visual Basic. Pointers are used in C program to access the memory
and manipulate the address.
Reference operator(&); here var is a variable and , &var is the address in memory.
/* Example to demonstrate use of reference operator in C programming. */
#include <stdio.h>
int main(){
int var=5;
printf("Value: %d\n",var);
printf("Address: %d",&var); //Notice, the ampersand(&) before var.
return 0;
}
Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers,
and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it
becomes necessary to learn pointers to become a perfect C programmer. As you know, every variable is a
memory location and every memory location has its address defined which can be accessed using ampersand
(&) operator, which denotes an address in memory. Consider the following example, which prints the address
of the variables defined −
#include <stdio.h>
int main () {