Programming in C (Common To Agri, Civil, Mech, Eee and Eie)
Programming in C (Common To Agri, Civil, Mech, Eee and Eie)
Programming in C (Common To Agri, Civil, Mech, Eee and Eie)
In arrays, the elements can be accessed randomly by using the index number. Arrays allocate memory
in contiguous memory locations for all its elements. Hence there is no chance of extra memory being
allocated in case of arrays. They are faster and can be utilized anywhere. They store data of similar
data types together.
An array is a series of elements of the similar type placed in contiguous memory locations.
data_typearrayName [ arraySize ];
5. What will happen when you access the array more than its dimension?
If the index of the array size is exceeded, the program will crash. But the modern compilers will take
care of this kind of errors.
1
9. Distinguish between one dimensional and two dimensional arrays.
1Dimensional array
* We can declare an array with a single subscript like ai .Arrays with only a single subscript are
known as one dimensional arrays.
*Syntax for initializing 1D array: datatypearrayname[size]={list of values};
2Dimensional array
* An array that has two subscripts, for example: aij is known as a two dimensional. A two dimensional
array is used to store a table of values which has rows and columns.
* A two dimensional array can be initialized in different ways either statically at compile time or
dynamically at run time.
*syntax for initializing 2D array: datatypearrayname[rows][column]={val1, val2,.. valn};
19. List out the any four functions that are performed on characterstrings.
-Finding the length of a string (strlen ( )).
- Copying the source string to the destination string (strcpy( )).
- Concatenating two strings (strcat( )).
- Comparing two strings (strcmp( )).
- Reversing the content of a string (strrev( )).
20. Write the output of the following Code:
main()
{
static char name[]=”KagzWrxAd”
inti=0;
while(name[i]!=’\0’)
{
3
printf(“%c”,name[i]);
i++;
}
}
Output: KagzWrxAd
PART-B
1. (i) Explain the need for array variables. Describe the following with respect to arrays:-
Declaration of array and accessing an array element. (6)
Need for array variables: Array variables are used for the storage of homogeneous data, i.e.data of
the same type, and they also provide an efficient mechanism for accessing data in ageneralized
manner.
• Array variables are needed for storing and processing string (i.e. a group of characters).
• There is no basic data type available in C to store strings. A variable of char type can beused to
store only one character and cannot be used to store more than one character.
• The derived type array enables the user to store the characters in a contiguous set ofmemory
locations, all of which can be accessed by only one name, i.e. the array name.
• Single or one-dimensional array variables are used extensively in searching and
sortingprocesses.
• Searching is an operation in which a given list (i.e. array) is searched for a particularvalue, and
the location of the searched element is informed, if found. The varioussearching methods are
linear or sequential search and binary search.
• Sorting is an operation in which all the elements of a list (i.e. array) are arranged in
apredetermined order (ascending or descending). The various sorting methods are linearor
sequential sort, selection sort, bubble sort, insertion sort, merge sort, quick sort, shellsort and
radix sort.
• Two-dimensional array variables are used to arrange the elements in a rectangular grid ofrows
and columns. Matrix operations such as addition, subtraction, multiplication, transpose,etc. can
be effectively done with the help of two-dimensional arrays.
The terms enclosed within angular brackets (i.e. <>) are optional. The terms shown in bold are
mandatory parts of a single-dimensional array declaration. The following declarations are valid:
int array1[8]; // array1 is an array of 8 integers (Integer array)
4
float array2[5]; // array2 is an array of 5 floating-point numbers (Floating-point array)
char array3[6]; // array3 is an array of 6 characters (Character array)
The size specifier specifies the number of elements in an array. The rules for size specifier are:
1. The size specifier should be a compile time constant expression of integral type and itcannot be
changed at the run-time.
2. The size specifier should be greater than or equal to one.
3. The size specifier is mandatory if an array is not explicitly initialized.
The terms enclosed within angular brackets (i.e. <>) are optional. The terms shown in bold
aremandatory parts of a single-dimensional array declaration. The following declarations are valid:
The row size specifier and column size specifier should be a compile time constant expressiongreater
than zero. The specification of a row size and column size is mandatory if aninitialization list is not
present. If the initialization list is present, the row size specifier can beskipped but it is mandatory to
mention the column size specifier.
Accessing an array element: The elements of a single-dimensional array can be accessed byusing a
subscript operator (i.e. []) and a subscript. The array subscript in C starts with 0, i.e. thesubscript of the
first element of an array is 0. Thus, if the size of an array is n, the validsubscripts are from 0 to n–1.
The elements of a two-dimensional array can be accessed byusing row and column subscripts.
(ii) Write a C programto re-order a one-dimensional array of numbers in descending order. (7)
Program
#include<stdio.h>
void main()
{
int a[20],i,j,n,t;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Enter %d elements...\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(a[i]>a[j])
5
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
printf("\nDescending Order:\n");
for(i=n-1;i>=0;i--)
printf("%d\t",a[i]);
}
Output
Enter the number of elements: 5
Enter 5 elements...
-25 21 -6 54 8
Descending Order:
54 21 8 -6 -25
2. Write a C program to multiply two matrices (two-dimensional array) which will be entered by a
user. The user will enter the order of a matrix and then its elements and similarly input the
second matrix. If the entered orders of two matrices are such that they can’t be multiplied by
each other, then an error message is displayed on the screen.(13)
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
if (n != p)
printf("The matrices can't be multiplied with each other.\n");
else
{
printf("Enter elements of second matrix\n");
multiply[c][d] = sum;
sum = 0;
}
}
printf("\n");
}
}
return 0;
}
7
for(j=i+1; j<n; j++) {
if(x[j] < x[i]) {
// swap elements
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
if(n%2==0) {
// if there is an even number of elements, return mean of the two elements in the middle
return((x[n/2] + x[n/2 - 1]) / 2.0);
}
else {
// else return the element in the middle
return x[n/2];
}
}
Determinant of a matrix:
#include<conio.h>
#include<stdio.h>
int a[20][20],m;
int determinant(int f[20][20],int a);
int main()
{
inti,j;
printf("\n\nEnter order of matrix : ");
scanf("%d",&m);
printf("\nEnter the elements of matrix\n");
for(i=1;i<=m;i++)
{
for(j=1;j<=m;j++)
{
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("\n\n---------- Matrix A is --------------\n");
8
for(i=1;i<=m;i++)
{
printf("\n");
for(j=1;j<=m;j++)
{
printf("\t%d \t",a[i][j]);
}
}
printf("\n \n");
printf("\n Determinant of Matrix A is %d .",determinant(a,m));
getch();
}
int array[4][7]={2,1,2,3,4,5,6,1,6,8}
2123456
1680000
0000000
0000000
c. The initializers in the initialization list can be braced to initialize elements of the individualrows. If
the number of initializers within the inner braces is less than the row size, trailinglocations of the
corresponding row get initialized to 0, 0.0 or ‘\0’, depending upon theelement type of the array.
int array1[4][7]={{2,1},{2,3,4},{5},{6,1,6,8}}
array1
10
2100000
2340000
5000000
6168000
int array2[4][7]={{2,1},{2,3,4}}
array2
2100000
2340000
0000000
0000000
(ii) Memory map of a two-dimensional array: A two-dimensional (2-D) array can be visualized as a
plane, which has rows and columns. Although multi-dimensional arrays are visualized in thisway, they
are actually stored in the memory, which is linear (i.e. one dimensional). The twomethods for
representing a multi-dimensional array are:
a. Row major order of storage: In row major order of storage, the elements of an array arestored row-
wise. In C language, multi-dimensional arrays are stored in the memory by usingrow major order of
storage.
In C language, 2-D array 2 3 1 4 will be stored 8 6 9 7 in the memory as2 3 1 4 8 6 9 7
2000 2002 2004 2006 2008 2010 2012 2014
b. Column major order of storage: In column major order of storage, the elements of an arrayare stored
column-wise. Column major order of array storage is used in the languages likeFORTRAN, MATLAB,
etc.
Using column major order of storage, 2-D array 28 36 19 47 will be stored in the memory as
2 8 3 6 1 9 4 72 2004 2006 2008 2010 2012 2014
#include<stdio.h>
voidmain()
{
12
intarr[3][4];
inti, j, k;
printf("Enter array element");
for(i=0;i<3;i++)
{
for(j =0; j <4;j++)
{
scanf("%d",&arr[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j =0; j <4;j++)
{
printf("%d",arr[i][j]);
}
}
}
Voidselection_sort()
{
inti, j, min, temp;
for (i=0; i<n; i++)
{
13
min = i;
for (j=i+1; j<n; j++)
{
if (a[j] < a[min])
min = j;
}
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
OUTPUT:
Enter size of an array: 8
After sorting:
14 25 44 45 55 65 68 78
10. Explain about the String arrays and its manipulation in detail.(13)
String is a sequence of characters that is treated as a single data item and terminated by null character '\0'.
Remember that C language does not support strings as a data type. A string is actually one-dimensional
array of characters in C language. These are often used to create meaningful and readable programs.
For example: The string "hello world" contains 11 characters including BLANK SPACE. \0' character
which is automatically added by the compiler at the end of the string.
String Handling Functions
You need to often manipulate strings according to the need of a problem. Most, if not all, of the time
string manipulation can be done manually but, this makes programming complex and large.
To solve this, C supports a large number of string handling functions in the standard library"string.h".
Few commonly used string handling functions are discussed below:
Method Description
strcat() It is used to concatenate(combine) two strings
strlen() It is used to show length of a string
strrev() It is used to show reverse of a string
strcpy() Copies one string into another
strcmp() It is used to compare two string
strcat() function
strcat("hello", "world");
strcat() function will add the string "world" to "hello" outputhelloworld.
strlen() function
strlen() function will return the length of the string passed to it.
int j;
j = strlen("studytonight");
printf("%d",j);
output :12
strcmp() function
strcmp() function will return the ASCII difference between first unmatching character of two strings.
15
int j;
j = strcmp("study", "tonight");
printf("%d",j);
output: -1
strcpy() function
It copies the second string argument to the first string argument.
#include<stdio.h>
#include<string.h>
intmain()
{
char s1[50];
char s2[50];
printf("%s\n", s2);
return(0);
}
StudyTonight
strrev() function
It is used to reverse the given string expression.
#include<stdio.h>
intmain()
{
char s1[50];
16
Enter your string: studytonight
Your reverse string is: thginotyduts
11. Write a C program to find whether the given string is palindrome or not without using string
functions.
Program
#include<stdio.h>
void main()
{
char s[20],i,j=0;
printf("Enter a string: ");
fflush(stdin);
gets(s);
while(s[j]!='\0')
j++;
for(i=0,j--;(i<j)&&(s[i]==s[j]);i++,j--);
if(i<j)
printf("%s is not a palindrome.",s);
else
printf("%s is a palindrome.",s);
}
Output
1. Enter a string: malayalam
malayalam is a palindrome.
2. Enter a string: college
college is not a palindrome.
12.(i)What are the different types of string function? Describe with their purpose.(5)
Method Description
strcat() It is used to concatenate(combine) two strings
strlen() It is used to show length of a string
strrev() It is used to show reverse of a string
strcpy() Copies one string into another
strcmp() It is used to compare two string
(ii)Write the C program to find the number of Vowels, Constants, Digits and white space in a string.
#include<stdio.h>
#include<ctype.h>
17
void main()
{
charstr[100];
inti,v,c,d,s,o;
printf("Enter a line of text...\n");
fflush(stdin);
gets(str);
v=c=d=s=o=0;
for(i=0;str[i]!='\0';i++)
if(isalpha(str[i]))
switch(tolower(str[i]))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':v++;
break;
default :c++;
}
else if(isdigit(str[i]))
d++;
else if(isspace(str[i]))
s++;
else
o++;
printf("No. of characters : %d\n",v+c);
printf("No. of vowels : %d\n",v);
printf("No. of consonants: %d\n",c);
printf("No. of spaces : %d\n",s);
printf("No. of digits : %d\n",d);
printf("Others : %d\n",o);
}
In real time application, it will happen to pass arguments to the main program itself. These arguments
are passed to the main () function while executing binary file from command line.
18
Syntax:
int main(intargc, char *argv[])
Here argc counts the number of arguments on the command line and argv[ ] is a pointer array which
holds pointers of type char which points to the arguments passed to the program.
The gets() function can also be used to read a string from the user at runtime and theprototype is:
char* gets (char*)
and is available in the stdio.h header file. This function reads characters from the keyboard until a new
line character is encountered, appends a null character and returns the starting address of the location
where the string is stored. The gets function is suited for reading multi-word strings.
String Output: The printf function can be used to print a string literal constant, the contentsof a
character array and the contents of the memory locations pointed by a character pointer on the screen
in two different ways:
a) Without using format specifier :i) printf(“Hello”); //Prints string literal constant
ii) charstr[20]=“Readers!!”; //Array holding string
printf(str); //Prints character array
Disadvantage: The contents of only one character array can be printed at a time.
b) Using %s format specifier:charstr[20]=“Readers!!”;
char str1[5]=“Dear”
printf(“%s%s%s”,“Hai”,str1,str); //Prints HaiDearReaders
Advantage: Two or more strings can be printed by a single call to the printf function havingmultiple
%s specifiers.
The puts() function can also be used to print the string or character array. The syntax is:
20
void puts (char*)
PART-C
1.Write a C program to find average marks obtained by a of 30 students in a test.(15)
#include<stdio.h>
void main()
{
intn,mark[30],i,tot=0;
floatavg;
printf("Enter the no. of students: ");
scanf("%d",&n);
printf("Enter the marks obtained by %d students...\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&mark[i]);
tot=tot+mark[i];
}
avg=(float)tot/n;
printf("Average marks obtained by %d students is %f.",n,avg);
}
Output
Enter the no. of students: 10
Enter the marks obtained by 10 students...
54 61 77 43 92 87 22 68 97 55
Average marks obtained by 10 students is 65.599998.
#include<stdio.h>
void main()
{
int a[10][10],b[10][10],res[10][10],i,j,r1,c1,r2,c2;
printf("Enter the order of the first matrix: ");
scanf("%d%d",&r1,&c1);
printf("Enter the order of the second matrix: ");
scanf("%d%d",&r2,&c2);
if((r1!=r2)||(c1!=c2))
printf("Matrix addition is not possible...");
else
{
printf("Enter the first matrix of order %d x%d...\n",r1,c1);
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
printf("Enter the second matrix of order %d x%d...\n",r2,c2);
21
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
scanf("%d",&b[i][j]);
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
res[i][j]=a[i][j]+b[i][j];
printf("The added matrix is...\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
printf("%d\t",res[i][j]);
printf("\n");
}
}
getch();
}
Output
1. Enter the order of the first matrix: 3 3
Enter the order of the second matrix: 2 3
Matrix addition is not possible...
2. Enter the order of the first matrix: 3 3
Enter the order of the second matrix: 3 3
Enter the first matrix of order 3 x 3...
123
456
789
Enter the second matrix of order 3 x 3...
957
865
271
The added matrix is...
10 7 10
12 11 11
9 15 10
(ii) Subtraction(4)
#include<stdio.h>
void main()
{
int a[10][10],b[10][10],res[10][10],i,j,r1,c1,r2,c2;
printf("Enter the order of the first matrix: ");
scanf("%d%d",&r1,&c1);
printf("Enter the order of the second matrix: ");
scanf("%d%d",&r2,&c2);
if((r1!=r2)||(c1!=c2))
printf("Matrix addition is not possible...");
else
22
{
printf("Enter the first matrix of order %d x%d...\n",r1,c1);
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
printf("Enter the second matrix of order %d x%d...\n",r2,c2);
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
scanf("%d",&b[i][j]);
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
res[i][j]=a[i][j]-b[i][j];
printf("The subtracted matrix is...\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
printf("%d\t",res[i][j]);
printf("\n");
}
}
getch();
}
Output
1. Enter the order of the first matrix: 3 3
Enter the order of the second matrix: 2 3
Matrix addition is not possible...
2. Enter the order of the first matrix: 3 3
Enter the order of the second matrix: 3 3
Enter the first matrix of order 3 x 3...
957
865
789
Enter the second matrix of order 3 x 3...
123
654
271
The subtracted matrix is...
834
211
518
(iii)multiplication (7)
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
23
printf("Enter number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter elements of first matrix\n");
if (n != p)
printf("The matrices can't be multiplied with each other.\n");
else
{
printf("Enter elements of second matrix\n");
multiply[c][d] = sum;
sum = 0;
}
}
printf("%s\n", s2);
return(0);
}
Study
(ii) Compare and contrast gets() and puts().(8)
Reading string(gets): The user can enter strings and store them in character arrays at the runtimeby
using the scanf function with %s format specifier. This function can be used to read onlysingle word
strings. The scanf function automatically terminates the input string with a nullcharacter (i.e. \0), and
therefore the character array should be large enough to hold the input
string plus the null character.
The gets() function can also be used to read a string from the user at runtime and theprototype is:
char* gets (char*)
and is available in the stdio.h header file. This function reads characters from the keyboard untila new
line character is encountered, appends a null character and returns the starting address of the location
where the string is stored. The gets function is suited for reading multi-word
strings.
Writing string(puts): The printf function can be used to print a string literal constant, the contentsof a
character array and the contents of the memory locations pointed by a character pointer onthe screen in
two different ways:
4.Write a C program to Check whether a given number is Armstrong number or not using command
line argument.(15)
#include<stdio.h>
int main(intargc, char * argv[])
25
{
intnum,temp,arms=0,rem;
if (argc!= 2)
{
printf("Enter the number:\n");
scanf("%d",&num);
}
else
{
num = atoi(argv[1]);
}
temp=num;
while(num>0)
{
rem=num%10;
arms=arms+rem*rem*rem;
num=num/10;
}
if(temp==arms)
{
printf(" \n%d is an Armstrong number",temp);
}
else
{
printf("\n%d is not an Armstrong number",temp);
}
return 0;
}
26