CCP-UNIT-4
CCP-UNIT-4
CCP-UNIT-4
UNIT 4
Module – 4: (Arrays & Basic Algorithms)
Basic Algorithms:
Searching & Basic Sorting Algorithms (Bubble, Insertion and Selection)
Finding roots of equations.
Ans : An array elements can be initialized like an ordinary variables when declared. The general syntax is as
following : data_type array_name [size] = { list of values separated by comma};
Ques 2.What are the different ways to store the values in arrays?
Ans : (a) Initialization of array during declaration (b) Input values for the elements from the keyboard.
(c) Assign values to individual elements.
Examples: (a) Initialization of array during declaration
int marks [ 5] { 90, 65, 78, 80 , 47}; // initialization at the time of declaration.
90 65 78 80 47
[0] [1] [2] [3] [4]
When values are initialized in a 1-D array they are stored consecutively in memory, starting from index 0 to
size-1 i.e. in above example from 0 to 4 , because size of array is 5.If we declare like this :
int marks [ ] = { 2 , 4, 10}; We have not mentioned the size inside subscript operator, So compiler will
allocate space automatically equal to number of elements inside { } braces.
(c) Assigning Values to individual Elements : This can be done using assignment operator. Any value that
matches to the data type of an array can be assigned to the individual array element.
Example : marks [ 3] = 45 ; // 45 is assigned to 4th index of 1-D array.
Mr. Anuj Khanna (Assistant Professors), KIOT Kanpur
www.uptunotes.com Programming for Problem Solving(UNIT-4)
Initialization: data type * ptr_var = & var name 2 ; // & is known as address of operator
Example : // * is called value at address or indirection
operator
int a = 10;
int *p = &a ; // pointer variable p holds the value of variable a.
int a p
10 2000
2000 4000
(i) 2000 is the address of variable a , and pointer p holds this address as a value. Pointer variable p has
its own address 4000. 10 is the value stored at location a.
Ques 5. WAP in C to print the values and address with the help of pointers.
Ans :
#include<stdio.h>
#include<conio.h>
Mr. Anuj Khanna (Assistant Professors), KIOT Kanpur
www.uptunotes.com Programming for Problem Solving(UNIT-4)
Void main()
{
int x ;
int *p;
x = 10 ; p = &x ;
printf( “Value of x = %d \n” , x) ;.
printf(“ Variable x has address = %u \n” , &x ) ;
The following declaration and initialization create a string consisting of the word "Hello". To hold the null
character at the end of the array, the size of the character array containing the string is one more than the
number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows:
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C/C++ −
Actually, you do not place the null character at the end of a string constant. The C compiler automatically
places the '\0' at the end of the string when it initializes the array.
Ans : Base address of an array refers to the 1st element of a 1-D array at 0th Index position. If we only write
the name of an array then also it refers to the base address.
E.g : int a [ 5] = { 1 , 4 , 7, 9 , 10 };
Base address
Here 1002 is the base address of array a. Since it is an integer array, so addresses of each elements will be at
the difference of 2 bytes. While displaying the elements of array, next adjacent address is automatically called
when its previous element is displayed. Using pointers we can access the individual elements.
Increment / decrement of pointers lead to increment /decrement of addresses based on the data type of
pointers.
Ans : (i) gets() :This is a library function . Definition is stored in string.h header file. This function reads the
string as gets(str) , where str is the name of character array str.It takes the starting address of an string which
will hold the input.This function does not terminates if a blank space occurs between two strings as in scanf().
(ii) puts() : The string can be displayed by writing puts(str). This function overcomes the
drawback of printf. The puts() function writes a line of output on the screen. It terminates the
line by ‘\n’ .
(iii) sprint() : This is formatted output is written to memory area rather than directly on the
output screen. Syntax is as following :
sprint( char * buffer , const char* format string [ arg 1,arg2 ….arg n] ) ;
E.g : void main()
{
char buf [100] ;
int num = 10 ;
sprint( buf , “ num = %d ” , num ) ;
}
(iv) strcmp() : This function compares the string pointed to by str1 with string pointed by str2.
Syntax strcmp( const char *str1 , const char str2) ;
Function returns zero if the strings are equal. Otherwise it returns a value less than
zero or greater than zero if str1 is less than or greater than str2 respectively.
Ans : The 2-D arrays are also known as matrix which are created in row and column form.
Syntax to declare: data_type array_name [i ] [j ] ; Where two subscripts i and j are rows and
columns of a 2-D array. Subscripts i and j must be set at compile time.
E.g : int a [ 2] [3] ; // 2-D array with 2 rows and 3 columns.
Initialization of 2-D array : int a [2] [3] = { 0, 2, 3, 10, 30, 20 } ;
Matrix can be arranged in Row major and column major forms. In Row major form firstly elements of
1st row , then 2nd row …so on are stored . In column major form 1st column , then 2nd column…son on are
stored.
0 2 3
Row major form : 10 20 30 OR int a[2] [3] = { { 0,2,3} , { 10, 20, 30}} ;
0 3 30
Column Major form : 2 10 20
While initializing a 2-D array , it is necessary to mention 2nd dimension(number of columns), whereas 1st
dimension is optional.
E.g : int arr [ ] [2] = { 12 , 34 , 23 , 45 };
Compulsory.
Optional
Ans : The concept of array is very much dependent on pointers. Elements of array occupy contiguous memory
locations depending on the data type of elements stored. Array location is a form of a pointer notation. The
name of the array is the starting/base address of an array.
Use of pointers : We can access the values of array elements using pointers as mentioned below:
(i) Expression a [ i] is equivalent to write * ( a + i ). If a is the name of array, then compiler implicitly
takes a = &a[0] . To print the value of third element of the array , we can use the expression
*( a + 2). Because a [i] = * (a + i).
Ques 12. (i) What is referencing and dereferencing in pointers. Give an example.
(ii)What are the rules for pointers and Pointer arithmetic?
Ans : Referencing in pointers : In this a pointer variable is used to refer the address of an object . use of
reference operator (& , ampersand), also called address of operator. This is a unary operator on left side of
operands. The operand should be a variable of arithmetic type or pointer type.
E.g : float f = 12.5 ;
float * fptr ;
fptr = &f ;
Dereferencing a pointer : When we want to access the value stored at a particular address in a variable ,
then we use dereferencing with the help of pointers. This operator is also known as value at address operator
, ( * , asterisk) . Operand of * operator must be a pointer type variable.. This is a unary operator.
E.g : If we write *(p) or *(&a) = value at address of variable a.
// Referencing & Dereferencing of pointers
void main()
{
int a = 12;
int *i = &a;
printf (“ Value of a is = %d \n ” , a) ;
printf ( “ Value by dereferencing a = %d \n ” , *i) ;
printf ( “ Value of a = %d \n” , *(&a))
printf ( “ Address of a = %u ” , & a) ;.
}
Rules of pointers
(a) A pointer can be assigned /initialized with the address of a variable. A pointer can’t hold a
non address value , so it can only be initialized with addresses.
(b) A pointer to a specific data type variable /object can’t point to an object of another data type.
E.g : Following is an invalid assignment :
void main()
{
int val = 10 ;
float * ptr = & val ;
printf ( “ value of variable = %d \n” , val) ;
printf ( “ Pointer ptr holds the address = %u \n ” , ptr) ;
}
(c) Increment and decrement operator can be applied to pointer variables which will change the addresses
Accordingly.
E.g : float * fptr ;
fptr = ptr ++ // post increment and initially , ptr = 2000 (address).
So address will be incremented by 4 bytes because of float data type .So fptr = 2004.But ptr will
remain 2000 because it is post increment. Similarly , If we perform ptr - - , then new address will be
1996.
(d) Subtraction: Subtraction between two pointer variables gives the difference in number of bytes , (
subscripts of two array elements)depending on data type of variables. E,g : Consider following float
array b
Let pointer p1 = 1002 and pointer p2 = 1010. So p1 – p2 = 2 , i.e difference of two subscripts , where each
subscript element is of 4 bytes (Array is float type)). So , 4 x 2 = 8 bytes.
Subtraction of two pointers is useful only if both the pointers hold the address of variables in same array.
Ques 13. WAP in C to read and display n numbers Ques 14. WAP in C Find the smallest
Using an array. number of a 1-D array .
#include<stdio.h> #include < stdio.h>
#include<conio.h> #include <conio.h>
void main() void main()
{ {
int i=0 , n , arr [20] ; int arr [ 100 ] , min, i , n, s , pos ;
clrscr(); float avg_marks = 0.0 ;
printf ( “ Enter the number of elements : \n” ) ; clrscr() ;
getch () ;
}
Ques 15.WAP in C to enter number of digits. Form Ques 16. WAP in C to calculate the sum and
a number using these digits. average of marks , secured by students
using array named marks[ ] .Number of
students must be read through keyboard.
#include<stdio.h> #include < stdio.h>
#include<conio.h> #include <conio.h>
#include<math.h> void main()
void main {
{ int marks[ 200 ] , i , sum = 0, studs ;
int num =0, digit [10], n , i ; float avg_marks = 0.0 ;
clrscr() ; clrscr() ;
printf( “Enter the number of digits for number \n” ) ; printf ( “ Enter the number of students \n”);
scanf ( “ %d ” , &n) ; scanf ( “ %d” , & studs) ;
for( i=0 ; i < n; i ++) printf ( “ Enter the marks of all students \n”) ;
{ for( i = 0; i < studs ; i++)
printf ( “ \n Enter the %d digit : ” , i ) ; {
scanf( “ %d” , &digit [i]) ; printf ( “Enter the marks of students %d
} \n\t”,marks[i]);
i=0 ; scanf ( “ %d” , & marks [i]) ; i)
while ( i < n) }
{ for (i =0 ; i < studs ; i++ )
num = num + digit [ i] + pow (10,i) ; { sum = sum + marks [i] ; }
i++; avg_marks = (float) sum / studs ;
} printf ( “ Sum of marks = %d” , sum);
printf( “ \n The number = %d ” , num) ; printf( “\n Average marks of %d students =
getch(); %f ”, studs , avg_marks ) ;
} getch () ;
}
Ques 17. WAP in C to print the elements of an Ques 18.WAP in C to check whether an array of
array using pointers. integers contain a duplicate number or not.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main()
{
{
int b [3] = { 10 , 20 , 30 } ; int i , n ,j , arr [20] , flag=0 ;
printf( “Elements are %d %d %d \n”, b[0], b[1] , clrscr();
printf ( “ Enter the number of elements : \n” ) ;
b[2]) ;
scanf( “ %d ” , &n) ;
printf(“ Elements are %d %d %d \n” , *(b +0), printf( “ \n Enter the elements \n”) ;
*(b+1) , *(b + 2)) ; for ( i=0 ; i<n ; i++)
{
getch();
printf( “ \n arr [ %d] = ” , i );
} scanf( “ %d” , &arr[ i]) ;
}
for ( i=0 ; i < n ; i ++)
{
Mr. Anuj Khanna (Assistant Professors), KIOT Kanpur
www.uptunotes.com Programming for Problem Solving(UNIT-4)
Ques 19. What operations can be performed on 1-D arrays? Explain linear searching. WAP to
demonstrate linear searching in an array.
SEARCHING: The technique for finding the desired data element that has been stored in an array is
known as searching .After searching is completed , there may be two cases w.r.t data
element : Case 1: Search is successful , if it locates an element at required position
Case 2 : Search is unsuccessful , if it fails to locate an element .
LINEAR SEARCH : In this method , array is searched for a particular data item by comparing every element
of the array one by one until a match is found .An element to be searched is generally called KEY element is
used to compare with another values. Linear search is generally applied to unordered list (unsorted) of
elements.
Example : #include<stdio.h>
#include<conio.h>
void main()
{ int arr[ 10 ] = { 15, 20 , 30 , 9 , 14 , 56 , 40 , 100 , 67, 7 };
int i , num ;
printf( “ Enter the key element to be searched in array\n”);
scanf ( “ %d” , & num);
for(I = 0 ; i <10 ; i ++ )
{ if (num = = arr [ i ])
{ printf ( “ %d number is found \n ”, num) ;
break ;
}
else
{
printf( “ %d number not found ” , num ) ;
} }
getch () ; } // End of main()
Ques 20 : What is sorting ? WAP in C to sort the elements of an array using bubble sort.
Ans : Term sorting} means arranging the elements of an array in some relevant order which may be either
ascending / descending. If A is an array then , the elements of an array arranged in ascending order will be
such that : A[0 ] < A[ 1 ] < A[ 2 ] < ……A[N-1]. Example : if we have elements of array as :
A[ ] = { 21 , 34 ,11, 9 , 1 , 0 , 22} ; Then the sorted array in ascending order will be as given below :
A[ ] = { 0 , 1 , 9 , 11 , 21 , 22 , 34}.Efficient sorting algorithms are used to optimize the use of other
Algorithms like search and merge algorithms which require sorted lists to work properly.
Two types of Sorting exist : (i)Internal Sorting (ii) External Sorting.
Internal sorting deals with sorting the data stored in computer’s memory.External sorting deals with the data
stored in files . It is used when large data can not be stored in memory of computer.
Bubble Sort: In this method of sorting array elements is done by repeatedly moving the largest elements to
the highest index position of the array( if using ascending order). In this consecutive adjacent pairs of
elements are compared with each other. If element at lower index is greater than the element at higher index,
the two elements interchange their positions. This process continues till the list if unsorted elements are
finished.
Ques 21. Write a C program to accept a matrix of Ques 22. Write a C program to accept a matrix of
order M x N and find the sum of each row and order m x n and find its transpose .
each column
#include <stdio.h>
#include <stdio.h> #include <conio.h>
#include<conio.h> void main ()
void main () {
{ int mat [10][10];
int m1[10][10]; int i, j, m, n ;
int i, j, m, n, sum=0; printf ("Enter the order of the matrix \n");
clrscr() ; scanf ("%d %d", &m ,&n);
printf ("Enter the order of the matrix\n"); printf ("Enter the elements of the matrix\n");
scanf ("%d %d", &m, &n); for (i=0; i<m;++i)
printf ("Enter the co-efficients of the matrix\n"); {
for (i=0; i<m ; ++i) for (j=0;j<n;++j)
{ for (j=0 ; j<n ; ++j) {
{ scanf ("%d", &m1[i][j]) ; } scanf ("%d",& mat[i][j]);
} }
}
for (i=0;i<m;++i) printf ("The given matrix is \n");
{ for (j=0;j<n;++j) for (i=0;i<m;++i) // Here outer loop is now for
{ sum = sum + m1[i][j] ; } counter variable i
printf ("Sum of the %d row is = {
OUTPUT: else
{
Enter number of rows and columns of first matrix ( printf("Matrix Multiplication is Not Possibl
MAX 10) e");
3 }
3 getch();
Enter number of rows and columns of second matri }
x MAX 10)
3
3
Ques 24.WAP to find the length of a string without using library function.
#include<stdio.h>
#include<conio.h> printf("The length of a string is the number of
void main() characters in it\n");
{ printf("So, the length of %s =%d\n", string,
char string[50]; length);
int i , length = 0; }
printf ("Enter a string\n"); /*----------------------------------------------------
gets (string); Output
for (i=0; string[i] != '\0'; i++) Enter a string
{ length++ ; hello
} The length of a string is the number of
characters in it
So, the length of hello = 5
Ques 25. Program to compare two strings using user defined function. If strings are identical display
“The Two Strings are Identical” otherwise the strings are different.
#include<stdio.h> if (flag==0)
#include<conio.h> printf("Both strings are equal\n");
void main() if (flag==1)
{ printf("String1 is greater than string2\n",
int count1=0,count2=0,flag=0,i; str1, str2);
char str1[10],str2[10]; if (flag == -1)
clrscr(); printf("String1 is less than string2\n", str1,
puts("Enter a string:"); str2);
gets(str1); getch(); }
puts("Enter another string:"); /*----------------------------------------
gets(str2); Output
/*Count the number of characters in str1*/ Enter a string:
while (str1[count1]!='\0') happy
count1++; Enter another string:
/*Count the number of characters in str2*/ HAPPY
while (str2[count2]!='\0') String1 is greater than string2
count2++;
i=0 ; RUN2
while ( (i < count1) && (i < count2)) Enter a string:
{ if (str1[i] == str2[i]) Hello
{ i++; Enter another string:
continue ; Hello
} Both strings are equal
if (str1[i]<str2[i])
{ flag = -1; RUN3
break; Enter a string:
} gold
Mr. Anuj Khanna (Assistant Professors), KIOT Kanpur
www.uptunotes.com Programming for Problem Solving(UNIT-4)
Ques 26. WAP in C to reverse a string Ques 27. WAP in C to reverse a string
input through the keyboard. using a user defined function.
#include<stdio.h> #include<stdio.h>
#include<conio.h>
#include<conio.h>
char* mystrrev(char*s)
int main()
int main()
{ {
int i= -1; char str [ 20] ;
char str[100]; puts(“ Enter a string”) ;
char rev[100]; gets(str) ;
char *strptr = str; mystrrev (str) ;
char *revptr = rev; puts(“After the reversal string is : ”) ;
clrscr(); puts(str);
printf("Enter the string:n"); getch();
scanf("%s",str); }
while(*strptr) char* mystrrev (cahr* s)
{ {
strptr++; int i=0 , j=0 ;
i++; char temp;
} while (s[i] !=’\0’)
while(i >=0) { i++;
strptr--; i-- ;
*strptr = *revptr; while (i > j)
revptr++; {
--i; temp = s[i] ;
} s[i] = s[j] ;
printf("nn Reversed string is:%s", rev); s[j] = temp ;
return 0; j++ , i-- ;
}
getch();
return s ;
}
}
Ans : (i) Passing Arrays to functions : When we need to pass an entire array to a function, we can
pass the name of the array. Entire array is always passed by reference to the function. Following are
the rules to pass 1-D array in a function :
Rule 1. The actual argument in the function call should only be the name of the array without any
subscript, because name of an array represents base address.
Rule 2. Formal parameters in the function definition must be of array type or pointer type ( i.e pointer
to first element of the array.) If formal parameter is of array type , it will be implicitly converted to
pointer type.
Rule 3. Parameter type in the function declaration should be of array type or pointer type.
Example :
void main() // Calling function. Note : When an entire array is to be sent to the
{ called function, the calling function just needs to
int arr [5] = { 1 ,4 , 10 , 45 , 65 }; pass the name of array.
func(arr) ; In cases where called function does not makes
} any changes to the array, the array must be
void func (int arr [ 5]) // Called function received as a constant array by the called
{ function. It prevents any type of unnecessary
int i ; modifications by called function to the array
(ii) Enumerated Data Types : This is a user defined data type based on the basic integer type.
Enumeration has a set of named integer constants. Each integer value is assigned an identifier, also
known as enumeration constant, which can be used as a symbolic name to make program easy to be
read.
Keyword enum is used for this data type.
Syntax : enum enumeration_name { identifier1 , identifier 2, ……., identifier n}.
Enumeration name is optional.
Example : enum COLORS { RED , BLUE , BLACK , GREEN , YELLOW ,PURPLE} ;
Now COLORS is a new data type. COLORS is the name given to the set of constants. In case we
do not assign any value to a constant , default value for the first one in list , RED has value of 0.
Next constants will have sequential values after 0 i.e , 1, 2, 3…so on.
RED = 0 ,BLUE = 1, Black =2 , GREEN = 3 , YELLOW= 4, PURPLE= 5.
We can also initialize symbolic constants explicitly by specific integer values , which may not be
in sequence.
Example : enum COLORS { RED = 3 , BLUE = 7 , BLACK = 0 , GREEN = 5 ,
YELLOW = 2, PURPLE = 10} ;
(iii) Union: This is a user defined data type. It is a collection of variables of different data types.
In Unions we can only store information in one field at any one time. It is like a chunk of
memory used to store variables of different data types. When a new value is assigned to a field, the
existing data is replaced with the new data.
data_type var-name1;
data_type var-name2 ;
}
Ques 29. What are structures? What is the advantage of structures over array? Differentiate
between Structures and Unions.
Ans : Structures are the user defined data types that is of heterogeneous nature , that means it can
store information of different data types. Keyword struct is used to declare a structure.
Declaration of structure: struct structure _ name
{
Data_type var-nmae1;
Data_type var-nmae1
};
Example: if we define a structure for a student Each variable name declared inside structure is
, then the Related information can be : rollno , called member of structure. Structure declaration
name , course , fees. This structure can be does not consume any storage space. Example:
, we can define a variable by writing :
declared as :
struct student stud1 ;
struct student
{ E.g : struct student
int rollno ; {
char name [ 20]; int rollno ;
char course [ 25] ; char name [ 20];
float fees ; char course [ 25] ;
}; float fees ;
} stud1,stud2 ;
Example : declaration of a structure
named date. Here stud1 and stude2 are two variables of
structure name student. Variables are
struct date separated by commas.
{
int day ; A separate memory is allocated to variables while
int month ; declaring them.
int year ;
}
Initialization of structures: A structure can be initialized in the same way as other data types
are initialized. Initializing a structure means assigning some constants to the members of the
structure. If explicitly, then C automatically does that. For int and float members, values are initialized
to zero and character and string members are initialized to ‘\0’ by default. Initializers are enclosed in
curly braces separated by commas.
Advantage of Structure over Arrays : Structure is advantageous than arrays in the sense that
it can store information of variables of different data types where as arrays have information of only
same data types.
Difference between Structure & Union
getch();
} // End of main for(i=0 ; i<3 ; i++)
{
std[i].avg = total/3.0 ;
printf( “ %d %s %d %d %d % f\n ”,
std[i] .rollno,std[i].name,std[i].m1,
std[i].m2,std[i].m3,std[i].avg) ;
} // End of for loop
getch() ;
} // End of main()
Ques 32 : How an array of structure is created ? Explain with the help of a program.
Ans : It is possible to create an array whose elements are of structure type. Such an array is called
Array of Structures. If we consider a book example where we have to display information of book
name , author name , number of pages and its price then it can be stored in a variable of type struct
book. We can create two variable book1 , book2 and read and display the information about two
books..
But in case if we want to access the information of suppose 100 books , then we will have to create
100 variables like book1 , book2, book3 ,…..book100 . Also we will have to read and display the
information separately for each book. This will be a very long , difficult process ,and time consuming
also. So array of structures will provides an easy way to store information of 100 books.
General Syntax :
struct struct_name
{
Data_type1 member_name1 ;
Data_type2 member_name2 ;
Data_type3 member_name3 ;
……………………………….
Data _type n member_name n ;
} ; struct struct_name struct_var [ index ];
/* Program of Array of Structure for Book information */
#include<stdio.h>
#include<conio.h>
void main
{
struct book
{
char Name[30];
char author[20] ;
int pages ;
float price ;
};
struct book b[ 100 ]; //array of structures.
int i;
for(i=0;i<100;i++)
{
printf("\n Enter details of %d Book ",i+1);