Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Programming in C (Common To Agri, Civil, Mech, Eee and Eie)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

1901006 – PROGRAMMING IN C

(COMMON TO AGRI, CIVIL, MECH, EEE AND EIE)


UNIT – 2 QUESTION BANK QUESTIONS WITH ANSWER
PART-A

1. List out the advantages of Arrays.

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.

2. Define a float array of size 5 and assign 5 values to it.

float f[5]={ 1.2, 3.4, 5.6, 7.8, 6.7};

3. Identify the way to assign an array to another array.


To assign one array to another array. Ensure that the two arrays have the same rank (number of
dimensions) and compatible element data types. Use a standard assignment statement to assign the
source array to the destination array.

4. What is an array? Write the syntax for array.

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.

6. Point out an example code to express two dimensional array.


int a[2][2]={1,2,3,4};

7. How to create a two dimensional array?


data_typearrayName [ arraySize1 ] [ arraySize2 ];

8. What is the method to equate an array?


Given two given arrays of equal length, the task is to find if given arrays are equal or not. Two arrays
are said to be equal if both of them contain same set of elements.


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

10. What are the different ways of initializing array?


After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random
value). An array can be initialized at either compile time or at runtime.

11. What is the use of ‘\0’ and ‘%s’?


‘\0’ is the null character. Every string literal constant is automatically terminated by ‘\0’. The number
of bytes required to store a string literal constant is one more than the number of characters present in
it. The additional byte is required for storing ‘\0’.
• ‘%s’ is the format specifier used in scanf function that reads all the characters up to, but not
including the white-space character. Thus, scanf function with ‘%s’ specifier can be used to read
single word strings but cannot be used to read multi-word strings.

12. Is address operator used in scanf() statement to read an array? Why?


Array name represents the address of the starting element in the array. Hence, we don’t use the address
operator (&) while reading an array through scanf() function.

13. What is the role of strrev()?


The strrev( ) function reverses all the characters of a string except the terminating null character (‘\0’).

14. Show a C function to compare two strings.


strcmp() function is used to compare two strings.
Syntax: if (strcmp(s1,s2)= = 0), then both the strings are equal
if (strcmp(s1,s2) > 0), then string s1 is greater.
if (strcmp(s1,s2) < 0), then string s2 is greater.

15. How to initialize a string? Give an example.


A string can be initialized in two different ways:
By using string literal constant. Example: char str[6]=”Hello”;
By using initialization list. Example: char str[6]={‘H’,’e’,’l’,’l’,’o’,’\0’};

 
16. What will be the output of following program ?
#include <stdio.h>
int main()
{
charstr[8]="IncludeHelp";
printf("%s",str);
return 0;
}
Ans:
Error: Too many initializers/ array bounds overflow.
17. Write the output of the following Code:
main()
{
char x;
x = ‘a’;
printf(“%d \n”,x);
}
Output: 97
It prints the ASCII value of the character ‘a’ (i.e. 97).

18. Specify any two applications of Array.


• Arrays are used to implement mathematical vectors and matrices, as well as other kinds of
rectangular tables.
• Arrays are used to implement other data structures, such as lists, heaps, hash tables, queues and
stacks.

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’)
{

 
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.

Declaration of array: Declaring an array is also referred as creating an array type.

Declaration of a single-dimensional array: The general form of a single-dimensional


arraydeclaration is:
data_typearray_name [size] = { list_of_elements};

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)


 
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.

Declaration of a two-dimensional array: The general form of a two-dimensional arraydeclaration is:


data_typearray_name [row_size][col_size] = { list_of_elements};

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:

int array1[2][3]; //array1 is an integer array of 2 rows and 3 columns


float array2[5][1]; //array2 is a float array of 5 rows and 1 column
char array3[3][3]; //array3 is a character array of 3 rows and 3 columns

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

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

printf("Enter number of rows and columns of first matrix\n");


scanf("%d%d", &m, &n);
printf("Enter elements of first matrix\n");

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);

printf("Enter number of rows and columns of second matrix\n");


scanf("%d%d", &p, &q);

if (n != p)
printf("The matrices can't be multiplied with each other.\n");
else
{
printf("Enter elements of second matrix\n");

for (c = 0; c < p; c++)


for (d = 0; d < q; d++)

 
scanf("%d", &second[c][d]);

for (c = 0; c < m; c++) {


for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}

multiply[c][d] = sum;
sum = 0;
}
}

printf("Product of the matrices:\n");

for (c = 0; c < m; c++) {


for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);

printf("\n");
}
}
return 0;
}

3. Write a C program to calculate median for an array of elements.(13)


#include<stdio.h>
#include<conio.h>
void main()
{
int x[100],n,i;
float mean(int,int[]);
float median(int,int[]);
clrscr();
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&x[i]);
printf("median=%f\n",median(n,x));
getch();
}

float median(int n, int x[]) {


float temp;
inti, j;
// the following two loops sort the array x in ascending order
for(i=0; i<n-1; i++) {


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

4. Write a C program for Determinant of a matrix.(13)

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

 
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 determinant(int f[20][20],int x)


{
intpr,c[20],d=0,b[20][20],j,p,q,t;
if(x==2)
{
d=0;
d=(f[1][1]*f[2][2])-(f[1][2]*f[2][1]);
return(d);
}
else
{
for(j=1;j<=x;j++)
{
int r=1,s=1;
for(p=1;p<=x;p++)
{
for(q=1;q<=x;q++)
{
if(p!=1&&q!=j)
{
b[r][s]=f[p][q];
s++;
if(s>x-1)
{
r++;
s=1;
}

 
}
}
}
for(t=1,pr=1;t<=(1+j);t++)
pr=(-1)*pr;
c[j]=pr*determinant(b,x-1);
}
for(j=1,d=0;j<=x;j++)
{
d=d+(f[1][j]*c[j]);
}
return(d);
}
}

5. Describe the following with suitable examples. (6+7)


(i) Initializing a 2 Dimensional Array(ii) Memory Map of a Dimensional Array.
(i) Initializing a two-dimensional array: The elements of two-dimensional arrays can beInitializedby
providing an initialization list. An initialization list is a comma-separated list of initializersenclosed
within braces. The rules for initializing the elements of a two-dimensional array are:
a. The number of initializers in the initialization list should be less than or equal to the numberof
elements (i.e. row size × column size) in the array.
b. The array locations are initialized row-wise. If the number of initializers in the initialization listis less
than the number of elements in the array, the array locations that do not getinitialized will automatically
be initialized to 0 (in case of an integer array), 0.0 (in case of afloating-point array) and ‘\0’ (i.e. null
character if it is an array of character type).

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

6. Write a C program for transpose of a matrix.(13)


#include <stdio.h>
int main()
{
int a[10][10], transpose[10][10], r, c, i, j;
printf("Enter rows and columns of matrix: ");
scanf("%d %d", &r, &c);

// Storing elements of the matrix


printf("\nEnter elements of matrix:\n");
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
printf("Enter element a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}
11 
 
// Displaying the matrix a[][] */
printf("\nEntered Matrix: \n");
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
printf("%d ", a[i][j]);
if (j == c-1)
printf("\n\n");
}

// Finding the transpose of matrix a


for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
transpose[j][i] = a[i][j];
}

// Displaying the transpose of matrix a


printf("\nTranspose of Matrix:\n");
for(i=0; i<c; ++i)
for(j=0; j<r; ++j)
{
printf("%d ",transpose[i][j]);
if(j==r-1)
printf("\n\n");
}
return 0;
}

7. Discuss about the runtime initialization of a two dimensional array.(13)


The rules for initializing the elements of a two-dimensional array are:
a. The number of initializers in the initialization list should be less than or equal to the number of
elements (i.e. row size × column size) in the array.
b. The array locations are initialized row-wise. If the number of initializers in the initialization list is
less than the number of elements in the array, the array locations that do not getinitialized will
automatically be initialized to 0 (in case of an integer array), 0.0 (in case of afloating-point array) and
‘\0’ (i.e. null character if it is an array of character type).

Runtime initialization of a two dimensional Array

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

8. Write a C program to sort the n numbers using selection sort.(13)


#include <stdio.h>
Voidselection_sort();
int a[30], n;
void main()
{
inti;
printf("\nEnter size of an array: ");
scanf("%d", &n);
printf("\nEnter elements of an array:\n");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
selection_sort();
printf("\n\nAfter sorting:\n");
for(i=0; i<n; i++)
printf("\n%d", a[i]);
getch();
}

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

Enter elements of an array:


68 45 78 14 25 65 55 44

After sorting:

14 25 44 45 55 65 68 78

9. Develop a C program to search an element from the array.


#include<stdio.h>
void main()
{
intn,a[20],i,key,pos=-1;
printf("Enter the no. of elements: ");
scanf("%d",&n);
printf("Enter %d elements...\n",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])
{
pos=i+1;
break;
14 
 
}
if(pos==-1)
printf("Search element %d not found.",key);
else
printf("Search element %d found at position%d.",key,pos);
}

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

strcpy(s1, "StudyTonight"); //copies "studytonight" to string s1


strcpy(s2, s1); //copies string s1 to string s2

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

printf("Enter your string: ");


gets(s1);
printf("\nYour reverse string is: %s",strrev(s1));
return(0);
}

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

13. Illustrate with an example of command line arguments. (13)


Command line argument is a parameter supplied to the program when it is invoked. Command line
argument is an important concept in C programming. It is mostly used when you need to control your
program from outside. Command line arguments are passed to the main() method.
Parameters/arguments supplied to the program when it is invoked. They are used to control program
from outside instead of hard coding those values inside the code.

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.

Example for Command Line Argument


#include <stdio.h>
#include <conio.h>
int main(intargc, char *argv[])
{
inti;
if(argc>=2)
{
printf("The arguments supplied are:\n");
for(i =1; i<argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
return0;
}
Remember that argv[0] holds the name of the program and argv[1] points to the first command line
argument and argv[n] gives the last argument. If no argument is supplied, argc will be 1.

14. Explain about the following :


(i).String and character array.(4)
(ii).Initialising a string variables.(4)
(iii).String input and output (5)

(i).String and character array.(4)


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 12 characters including '\0' character which is
automatically added by the compiler at the end of the string.
Declaring and Initializing a string variables
19 
 
There are different ways to initialize a character array variable.
char name[13]="StudyTonight";// valid character array initialization

char name[10]={'L','e','s','s','o','n','s','\0'};// valid initialization


Remember that when you initialize a character array by listing all of its characters separately then you
must supply the '\0' character explicitly.
Some examples of illegal initialization of character array are,
charch[3]="hell";// Illegal
charstr[4];
str="hell";// Illegal

(ii).Initialising a string variables.(4)


A string can be initialized in two different ways:
• By using string literal constant. Example: char str[6]=”Hello”;
• By using initialization list. Example: char str[6]={‘H’,’e’,’l’,’l’,’o’,’\0’};

(iii).String input and output (5)


String Input: 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.

Example: scanf(“%s”, name); // name is a character array (i.e. char name[30]).

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.

2.Write a C program to perform the following matrix operations:

(i) Addition (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
{
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");

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);

printf("Enter number of rows and columns of second matrix\n");


scanf("%d%d", &p, &q);

if (n != p)
printf("The matrices can't be multiplied with each other.\n");
else
{
printf("Enter elements of second matrix\n");

for (c = 0; c < p; c++)


for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);

for (c = 0; c < m; c++) {


for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}

multiply[c][d] = sum;
sum = 0;
}
}

printf("Product of the matrices:\n");

for (c = 0; c < m; c++) {


for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
return 0;
}

3. (i) Write a C program to strcpy function.(7)


It copies the second string argument to the first string argument.
#include<stdio.h>
#include<string.h>
intmain()
24 
 
{
char s1[50];
char s2[50];
strcpy(s1, "Study"); //copies "studytonight" to string s1
strcpy(s2, s1); //copies string s1 to string s2

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.

Example: scanf(“%s”, name); // name is a character array (i.e. char name[30]).

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:

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 having
multiple %s specifiers.
The puts() function can also be used to print the string or character array. The syntax is:
void puts (char*)

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

END OF UNIT -II

26 
 

You might also like