Programming in c by pkv

53
1 PROGRAMMING IN C LANGUAGE (SOLUTION OF IMPORTANT QUESTIONS) For B.TECH. CSE (Cloud Technology & Information Security) By PRAMOD VISHWAKARMA M.TECH. (CSE) [email protected] 2015-16

Transcript of Programming in c by pkv

1

PROGRAMMING IN C LANGUAGE (SOLUTION OF IMPORTANT QUESTIONS)

For

B.TECH. CSE (Cloud Technology & Information Security)

By

PRAMOD VISHWAKARMA M.TECH. (CSE)

[email protected]

2015-16

2

MODULE-II QUES. (1) Explain in detail about fundamental data type in ‘C’ language, mentioning their range, space they occupy in memory and keyword used for their representation in programming. [5 Marks] Ans. DATA TYPE: Data type tell us about the type of the data, whether it is a character data, integer, or float. FUNDAMENTAL DATA TYPES IN C: There are four fundamental data types in C language- char, int, float and double. These data types are also known as primitive or basic data type. char: char data type is used for character values such as ‘A’, ‘a’ etc. int: int data type is used for integer values (Value without decimal point) e.g. -5, 35, etc. float and double are used for real value (value with decimal point) e.g. -35.89, 45.9876 The following table shows the detail about Fundamental data types- Data Types Keyword Format Memory Space Range Character char %c 1 byte -128 to +127 Integer int %d 2 bye -32768 to +32767 Float float %f 4 byte -3.4e38 to +3.4e38 Double double %lf 8 byte -1.7e308 to +1.7e308 Note:- The sizes and ranges of data types are compiler dependent. Sizes in this figure are for 16-bit compiler, e.g. Turbo C and Turbo C++.

3

QUES.(2) Explain in detail about various storage classes in ‘C’, mentioning their place and storage, default initial value, scope and life of each of them. [10 marks] Ans. STORAGE CLASSES IN C: To fully define a variable one needs to mention not only its type but also its storage class. A variable’s storage class tells us:

(a) Where the variable would be stored. (b) What will be the initial value of the variable, if initial value is not specifically assigned (i.e. the

default initial value). (c) What is the scope of the variable; i.e. in which functions the value of the variable would be

available. (d) What is the life of the variable; i.e. how long would the variable exist.

There are four storage classes in C:

1. Automatic storage class 2. Register storage class 3. Static storage class 4. External storage class

1. Automatic Storage Class The features of a variable defined to have an automatic storage class are as under:

Storage − Memory. Default initial value − An unpredictable value, which is often called a garbage value.

Scope − Local to the block in which the variable is defined.

Life − Till the control remains within the block in which the variable is defined.

Note: The keyword for this storage class is auto. By default the variable’s storage class is auto.

Ex- int a; // by default auto auto int a; // auto storage class

2. Register Storage Class

The features of a variable defined to be of register storage class are as under:

Storage - CPU registers. Default initial value - Garbage value. Scope - Local to the block in which the variable is defined.

Life - Till the control remains within the block in which the variable is defined.

* Keyword for register storage class is register. * A value stored in a CPU register can always be accessed faster than the one that is stored in memory.

ex- register int i ;

3. Static Storage Class

4

The features of a variable defined to have a static storage class are as under:

Storage − Memory. Default initial value − Zero. Scope − Local to the block in which the variable is defined.

Life − Value of the variable persists between different function calls.

Keyword: static

Ex- static int a;

4. External Storage Class The features of a variable whose storage class has been defined as external are as follows:

Storage − Memory. Default initial value − Zero. Scope − Global. Life − As long as the program’s execution doesn’t come to an

end. * Keyword: extern

* External variables are declared outside all functions

ex-

int x; void main() { ; ;

;

}

5

QUES. (3) What is an operator? What are the various types of arithmetic, relational, logical bitwise and increment and decrement operators? Clearly state their meaning and give example of each. [10 marks] Ans. Operator: An operator is a special symbol in programming language which performs specified operation on variable and yields the result. There are various types of operators in C language-

1. Unary operators 2. Arithmetical operators 3. Relational operators 4. Logical operators 5. Assignment operators 6. Bitwise operators 7. Conditional or Ternary operators

1. Unary operators: It operates on single variable. e.g. –x; a + (-b); 2. Arithmetical operators- Arithmetical/Mathematical operators are used to perform mathematical operations such as addition, subtraction, multiplication, division and modulus.

Operators Meaning + Addition - Subtraction * Multiplication / Division

% Remainder/modulus Ex-

a = 15; b = 5; a + b = 20, a - b = 10, a * b = 75, a / b = 3, 11%3 = 2.

3. Relational Operators- Relation operators are used to check relation between two values. The relational operators give true or false as result. To make any condition in program these operators are used.

Operator Meaning < Less than > Greater than

= = Equal to > = Greater than or equal to < = Less than or equal to ! = Not equal to

4. Logical Operators- Logical operators are used to combine two or more than two conditions.

Operators Meanings && And | | Or ! Not

6

5. Assignment operator- This operator is used to store value in variable. = is assignment operator. Ex- a = 20; // the value 20 is stored into a 6. Bitwise operators-

One of C’s powerful features is a set of bit manipulation operators. These permit the programmer to access and manipulate individual bits within a piece of data.

Operator Meaning

~ One’s complement >> Right shift << Left shift & Bitwise AND | Bitwise OR ^ Bitwise XOR(Exclusive OR)

Ex- a=5; b=~a; a<<1; // left shift the value of a b=8; b>>1; // right shift the value of a

7. Conditional or Ternary operator- ? operator is known as the conditional or ternary operator. Since there are three argument in this operator, it is known as ternary operator. This operator is the substitute of if---else. Syntax: condition ? True_section : False_section; Ex- void main()

{ int a,b; a=5; b=(a<10 ? 15 : 20); printf(“%d”,b); }

7

QUES. (4) Write a short note on top-down program development approach. [5 marks]

Ans.

Top-down is a programming style, the mainstay of traditional procedural languages, in which

design begins by specifying complex pieces and then dividing them into successively smaller pieces. The

technique for writing a program using top–down methods is to write a main procedure that names all the

major functions it will need. Later, the programming team looks at the requirements of each of those

functions and the process is repeated. These compartmentalized sub-routines eventually will perform

actions so simple they can be easily and concisely coded. When all the various sub-routines have been

coded the program is ready for testing. By defining how the application comes together at a high level,

lower level work can be self-contained. By defining how the lower level abstractions are expected to

integrate into higher level ones, interfaces become clearly defined.

A top-down approach (also known as stepwise design and in some cases used as a synonym

of decomposition) is essentially the breaking down of a program to gain insight into its compositional

sub-program. Top down approach starts with the big picture. It breaks down from there into smaller

segments

8

QUES. (5) What is conditional operator? Explain with example. [5 marks] Ans. Conditional Operator-

The conditional operator (?) is the substitute of if-else statement. This is also known as ternary operator, because there are three arguments.

Syntax-

expression_1 ? expression_2 : expression_3 Expression_1 is condition, if the condition is true, the control will come to expression_2 and if the condition is false, the control will come to expression_3. Ex-

void main() {

int a,b; printf(“\n Enter the value of a and b:”); scanf(“%d%d”,&a,&b); a>b ? printf(“\n a is greater”) : printf(“\n b is greater”);

}

9

QUES. (6) What do you mean by operator precedence and associativity of operator. [5 marks] Ans. OPERATOR PRECEDENCE- Operator precedence is the rank of the operator which decides the priority of operator in which the operation will be performed. In C language there is no BODOMAS rule, it follow the operator precedence to solve the expression of mixed operators.

While executing an arithmetic statement, which has two or more operators, we may have some problems as to how exactly does it get executed.

The priority or precedence in which the operations in an arithmetic statement are performed is called the hierarchy of operations. The hierarchy of commonly used operators is shown in following table-

Priority Operators Description

1st * / % multiplication, division, modular division

2nd

+ - addition, subtraction

3rd

= assignment

Ex-1 3 * 5 + 2 * 3 =15+2*3 =15+6 =21

Associativity of Operator- When operators having the same priority levels come together in an expression, then we follow the Associativity of operators. Associativity is the left-to-right or right-to-left order for grouping operands to operators that have the same precedence.

Priority Operators Associativity

1st * / % Left to right

2nd

+ - Left to right

3rd

= Right to left

Ex- 3 * 4 / 2 % 5 // * operator = 12 / 2 % 5 // / operator = 6 % 5 // % operator = 1

10

QUES. (7) Write a program in ‘C’ to input a five digit number through keyboard at run time and find sum of digits and reverse of number. [5 marks] Ans.

#include<stdio.h> #include<conio.h> void main() {

long int n, sum, rev; printf(“\n Enter a Five digit number:”); scanf(“%ld”,&n) a = n % 10; n = n / 10; b = n % 10; n = n / 10; c = n % 10; n = n / 10; d = n % 10; n = n / 10; e = n % 10; sum = a + b + c + d + e; rev = a * 10000 + b * 1000 + c * 100 + d * 10 + e; printf(“\n Sum of digits = %ld”,sum); printf(“\n Reverse = %ld”,rev); getch();

}

11

QUES. (8) What do you mean by type casting? What is difference between implicit and explicit type casting. Give example. [5 marks] Ans. Type Casting- Type casting is a way to convert a variable from one data type to another data type. Type casting is of two types-

(i) Explicit type casting (ii) Implicit type casting

(i) Explicit Type Casting- You can convert values from one type to another explicitly using the cast operator as follows:

(type_name) expression Ex-

#include <stdio.h> void main() { int sum = 17, count = 5; double mean; mean = (double) sum / count; printf("Value of mean : %f\n", mean ); }

(ii) Implicit Type Casting- Type conversions can be implicit which is performed by the compiler automatically.

Usual Arithmetic Conversion: The usual arithmetic conversions are implicitly performed to cast their values in a common type. Compiler first performs integer promotion; Ex-

float x; int y 5; x=y; // y is converted to float automatically

Ex-

void main() {

float avg1,avg2; int n, a,b,c,d,e,sum; scanf(“%d%d%d%d%d”. &a, &b, &c, &d, &e); sum = a + b + c + d + e; avg = sum / n; //Implicit type casting avg = (float) sum / n; //Explicit type casing printf(“\n Avg1 = %f \n Avg2 = %f”, avg1, avg2);

}

12

QUES. (9) Write a program in ‘C’ language to input the value of x, y, and z. Exchange the value of variable in such a way that x has the value of y, y has the value of z and z has the value of x. [5 marks] Ans.

#include<stdio.h> #include<conio.h> void main() {

int x, y, z, t; printf(“\n Enter the value of x, y, and z:”); scanf(“%d%d%d”,&x, &y, &z); t = x; x = y; y = z; z = t; printf(“\n x = %d \n y = %d \n z = %d”, x, y, z); getch();

} Output:

Enter the value of x, y, and z: 10 20 30 x = 20 y = 30 z = 10

13

QUESTIONS TO PRACTICE

Q.10. What is a constant? Define various types of constant in C.

Ans.

Constant- A constant is a fix value, which do not change during the execution of the program.

Types of C Constants

C constants can be divided into two major categories: (a) (b)

1. Primary Constants (i) Integer Constant: -5, 5

(ii) Real Constant: 3.75, -3.75 (iii) Character Constant: ‘A’

2. Secondary Constants

(i) Array (ii) Pointer

(iii) Structure (iv) Union (v) Enum. etc.

14

MODULE-III

Q. 1. What is the role of switch statement in ‘C’ programming language? Give the syntax of switch statement with suitable example. What is the limitation of switch statement? [10]

Ans.

switch() statement is used to make a choice from a number of alternatives. When we have to select only one option out of many options we use switch statement; rather than using a series of if statements.

Syntax:-

switch ( integer expression ) { case constant 1 :

do this ; break;

case constant 2 : do this ; break;

case constant 3 : do this ; break;

default : do this ;

} Note:-

Expression in switch could be an integer constant like 1, 2 or 3, or an expression that evaluates to an integer.

The keyword case is followed by an integer or a character constant. Each constant in each case must be different from all the others.

Example:-

#include<stdio.h> #include<conio.h>

void main( ) { int i x; printf(“\n Enter your option from (1-4):”);

scanf(“%d”,&x);

switch ( x ) { case 1 :

printf ( "I am in case 1 \n" ) ; break ;

case 2 : printf ( "I am in case 2 \n" ) ; break ;

15

case 3 : printf ( "I am in case 3 \n" ) ; break ;

case 4 : printf ( "I am in case 4 \n" ) ; break ;

default : printf ( "I am in default \n" ) ;

} getch(); }

Limitations of switch statement:

The disadvantage of switch is that one cannot have a case in a switch which looks like: case i <= 20 : i.e. one can’t check condition

All that we can have after the case is an int constant or a char constant or an expression that evaluates to one of these constants. Even a float is not allowed.

switch Versus if-else Ladder There are some things that you simply cannot do with a switch. These are:

A float expression cannot be tested using a switch Cases can never have variable expressions (for example it is wrong to say case a +3 : ) Multiple cases cannot use same expressions. Thus the following switch is illegal:

switch ( a ) { case 3 : ... case 1 + 2 : ... }

16

Q. 2. Write the program to find greatest number among three numbers. Also make flow chart. [10]

Ans.

Program to find greatest number among three numbers:

Source Code-1:

#include <stdio.h>

void main() { float a, b, c; printf("Enter three numbers: "); scanf("%f %f %f", &a, &b, &c); if(a>=b && a>=c) printf("Largest number = %.2f", a); else if(b>=a && b>=c) printf("Largest number = %.2f", b); else printf("Largest number = %.2f", c); }

Source Code-2:

#include <stdio.h> void main() { float a, b, c; printf("Enter three numbers: "); scanf("%f %f %f", &a, &b, &c); if (a>=b) { if(a>=c) printf("Largest number = %.2f",a); else printf("Largest number = %.2f",c); } else { if(b>=c) printf("Largest number = %.2f",b); else printf("Largest number = %.2f",c); } }

17

Q. 3. Differentiate between do-while and while loop. Given a number, write a program in ‘C’ using while loop using while loop to reverse the number. For example, the number 12345 should be 54321. [10]

Ans.

Differences Between Do-While And While Loop:

1. In while loop the condition is tested first and then the statements are executed if the condition turns out to be true.

In do while the statements are executed for the first time and then the conditions are tested, if the condition turns out to be true then the statements are executed again.

2. A do while is used for a block of code that must be executed at least once. These situations tend to be relatively rare, thus the simple while is more commonly used.

3. A do while loop runs at least once even though the the condition given is false while loop do not run in case the condition given is false

4. In a while loop the condition is first tested and if it returns true then it goes in the loop, in a do-while loop the condition is tested at the last.

5. While loop is entry control loop where as do while is exit control loop.

6. Syntax: while loop:

while (condition)

{

Statements; }

Syntax of do while loop:

do { Statements; }while(condition);

18

Program To Reverse The Number:-

#include <stdio.h> void main() { int n, reverse=0, rem; printf("Enter an integer: "); scanf("%d", &n); while(n!=0) { rem=n%10; reverse=reverse*10+rem; n/=10; } printf("Reversed Number = %d",reverse); }

19

Q. 4. Write a program in ‘C’ to input an array of size n and find the maximum and minimum number of the array. [10]

Ans.

#include <stdio.h> #define max 100 int main() { int a[max], max, min, size, c; printf("Enter the number of elements in array [max=100]:\n"); scanf("%d", &size); printf("Enter %d integers\n", size); for (c = 0; c < size; c++) { scanf("%d", &a[c]); } // Finding the maximum and minimum number max = min = a[0]; for (c = 1; c < size; c++) { if (a[c] > max) { max = a[c]; } if (a[c] < min) { min=a[c]; } } printf("Maximum = %d \n Minimum = %d”, max, min); }

20

Q. 5. Write a program in ‘C’ to input two matrices using array. Find the sum of matrix. Display all the matrices. [10]

Ans.

#include <stdio.h> int main() { int r, c, a[100][100], b[100][100], sum[100][100], i, j; printf("Enter number of rows (between 1 and 100): "); scanf("%d",&r); printf("Enter number of columns (between 1 and 100): "); scanf("%d",&c); printf("\nEnter elements of 1st matrix:\n"); /* Storing elements of first matrix entered by user. */ for(i=0;i<r;i++) for(j=0;j<c;j++) { printf("Enter element:”); scanf("%d",&a[i][j]); } /* Storing elements of second matrix entered by user. */ printf("Enter elements of 2nd matrix:\n"); for(i=0;i<r;i++) for(j=0;j<c;j++) { printf("Enter element :"); scanf("%d",&b[i][j]); } /*Adding Two matrices */ for(i=0;i<r;i++) { for(j=0;j<c;j++) { sum[i][j]=a[i][j]+b[i][j]; } } /* Displaying the resultant sum matrix. */ printf("\nSum of two matrix is: \n\n"); for(i=0;i<r;++i)

21

{ for(j=0;j<c;++j) { printf("%4d ",sum[i][j]); } printf("\n\n"); } return 0; }

22

Q. 6. Write a program in ‘C’ to multiply two matrices. [10]

Ans.

#include <stdio.h> void main() { int a[10][10], b[10][10], mult[10][10], r1, c1, r2, c2, i, j, k; printf("Enter rows and column for first matrix: "); scanf("%d%d", &r1, &c1); printf("Enter rows and column for second matrix: "); scanf("%d%d",&r2, &c2); /* If column of first matrix in not equal to row of second matrix, asking user to enter the size of matrix again. */ while (c1!=r2) { printf("Error! column of first matrix not equal to row of second.\n"); printf("Enter rows and column for first matrix: "); scanf("%d%d", &r1, &c1); printf("Enter rows and column for second matrix: "); scanf("%d%d",&r2, &c2); } /* Storing elements of first matrix. */ printf("\nEnter elements of matrix 1:\n"); for(i=0; i<r1; i++) for(j=0; j<c1; j++) { printf("Enter element: "); scanf("%d",&a[i][j]); } /* Storing elements of second matrix. */ printf("\nEnter elements of matrix 2:\n"); for(i=0; i<r2; i++) for(j=0; j<c2; j++) { printf("Enter element: "); scanf("%d",&b[i][j]); } /* Initializing elements of matrix mult to 0.*/ for(i=0; i<r1; i++) for(j=0; j<c2; j++) { mult[i][j]=0; }

23

/* Multiplying matrix a and b and storing in array mult. */ for(i=0; i<r1; ++i) { for(j=0; j<c2; ++j) { for(k=0; k<c1; ++k) { mult[i][j]+=a[i][k]*b[k][j]; } } } /* Displaying the multiplication of two matrix. */ printf("\nOutput Matrix:\n"); for(i=0; i<r1; ++i) { for(j=0; j<c2; ++j) { printf("%d ",mult[i][j]); } printf("\n\n"); } }

24

Q. 7. Write the program to print the Fibonacci series up to nth terms, also find the sum of the series. [10]

Ans.

#include<stdio.h> void main() { int n, first = 0, second = 1, next, c, sum = 0; printf("Enter the number of terms\n"); scanf("%d",&n); for ( c = 0 ; c < n ; c++ ) { if ( c <= 1 ) next = c; else { next = first + second; first = second; second = next; } sum+=next; printf("%d, ",next); } printf(“\n Sum = %d”,sum); }

25

Q. 8. Write a program in ‘C’ to print the following pattern- [5]

1 2 2 3 3 3 4 4 4 4 5 5 5 5 5

Ans.

#include<stdio.h>

void main()

{

int a, b;

for(a=1; a<=5; a++)

{

for(b=1; b<=a; b++)

{

printf(“%d”, a);

}

printf(“\n”);

}

}

26

Q. 9. Write a program in ‘C’ to print the following pattern- [5]

5 5 4 5 4 3 5 4 3 2 5 4 3 2 1

Ans.

#include<stdio.h>

void main()

{

int a, b;

for(a = 5; a>=1; a--)

{

for(b=5; b>=a; b--)

{

printf(“%d”, b);

}

printf(“\n”);

}

}

27

Q .10. Write a program in C to print the following pattern- [10] * * * * * * * * * * * * * * * * * * * * * * * * *

Ans.

#include<stdio.h>

void main()

{

int a, b;

for(a=1; a<=5; a++)

{

for(c = 1; c <= 5 – a; c + +)

{

printf(“%c”,32);

}

for(b=1; b<=2*a-1; b++)

{

printf(“*”);

}

printf(“\n”);

}

}

28

Q. 11. Write a program to print all the Armstrong numbers between 1 to 999, also draw the flow chart. [10] Ans. Program To Print All The Armstrong Numbers Between 1 To 999:-

#include<stdio.h> void main() { int n, m, sum; m = 1; while(m<=999) { n = m; sum = 0;

while(n!=0) { r = n % 10; sum = sum + r * r * r; n = n / 10; } if (m = = sum) { printf(“\n %d”, m);

} m = m + 1; } }

29

Q. 12. Write a program to find the sum of the following series- F(x) = x + x2/2! + x3/3! + ………. Xn/n! [5] Ans.

#include<stdio.h> void main() { float x, sum, fact; int n, i; printf(“\n Enter number of terms: ”); scanf(“%d”,&n); printf(“\n Enter the value of x: ”); scanf(“%d”,&n); sum = 0; fact = 1; i = 1; while(i < = n) { fact = fact * i; r = pow(x, i) / fact; sum = sum + r; i = i + 1; } printf(“\n Result = %f”, sum); }

30

MODULE-IV Q.1. What is sequential search? Write a program to search a number given by user at run time. Array elements should be entered at run time in 1-D array. [10 marks] Ans. SEQUENTIAL SEARCH:

Sequential search is a method for finding a particular value in a list, which consists of checking every one of its elements, one at a time and in sequence, until the desired one is found. It is also known as linear search. Program for sequential search-

#include <stdio.h> void main() { int a[100], search, i, n, f=0; printf("\n Enter the number of elements in array: "); scanf("%d",&n); for (i = 0; i < n; i++) { printf("Enter a number: "); scanf("%d", &a[i]); } printf("Enter the number to search\n"); scanf("%d", &search); for (i = 0; i < n; i++) { if (search==a[i]) /* if required element found */ { printf("\n %d is found at location %d.\n", search, c+1); f=1; break; } } if (f==0) printf("\n %d is not present in array.\n", search);

}

31

Q.2. What are differences in searching and sorting? Write a program to sort the list containing ten numbers. [10 marks] Ans. SEARCHING: Searching is a method in which we look for an element in the list. Ex- Sequential searching and Binary searching. SORTING: In sorting we arrange the data in specified order. The list may be arranged in ascending order or descending order. If the data is number the ascending order is 1,2,3,4,5…. and so on and descending order is 5,4,3,2,1…. so on. If it is alphabet the ascending order is A to Z and descending order id Z to A. Ex- Selection sorting and bubble sorting. Program to sort the list containing ten numbers-

#include<stdio.h> #include<conio.h> void main() { int a[10], i, j, t; //Inputting array elements for(i = 0; i<10; i++) { printf(“\n Enter a no.”); scanf(“%d”,&a[i]); } // Sorting array elements:- Selection sorting for(i = 0; i<10; i++) { for(j = i+1; j<10; j++) { if(a[i] > a[j]) { t = a[i]; a[i] = a[j]; a[j] = t; } } } // Displaying sorted elements for(i = 0; i<10; i++) { printf(“\n %d”,a[i]); } getch(); }

32

Q.3. What is a string? Write a program in C that allows the user to enter a string and perform the following operation on it-

(i) Count number of characters in string (ii) Remove spaces in string

(iii) Count number of words in it. [10 marks] Ans. STRING: A group of characters is knows as string. In programming, String is an array of characters terminated by ‘Null character (\0)’. A string constant is enclosed within double inverted comma (“ “). A string constant is a one-dimensional array of characters terminated by a null ( ‘\0’ ). For example, char name[ ] = { 'D', 'E', 'N',’N’,'I', 'S', ' ',’R’,’I’,T’,’C’,’H’,’I’,’E’, '\0' } ; Another way to initialized string- char name[30]=” Dennis Ritchie” ; In this case the null character is stored automatically at the end of string. The ASCII value of null character is 0. Programs- (i) Count total number of characters in string

#include<stdio.h> #include<conio.h> void main() { char str[80]; int len, i; printf(“\n Enter any string:”); gets(str); len = 0; for(i =0; str[ i ]!=’\0’; i++) { len = len + 1; } printf(“\n Length of string = %d”,len); getch(); }

(ii) Remove spaces in string

#include<stdio.h> #include<conio.h> void main() { char str[80]; int i, j;

33

clrscr(); printf("\n Enter any string:"); gets(str); //Removing spaces for(i =0; str[ i ]!='\0'; i++) { if(str[i]==32) { for(j = i; str[ j ]!='\0'; j++) { str[j]=str[j+1]; } i--; } } printf("\n After removing spaces, string = %s",str); getch(); }

(iii) Count number of words in it

#include<stdio.h> #include<conio.h> void main() { char str[80]; int words, i; clrscr(); printf("\n Enter any string:"); gets(str); //Counting number of words words = 0; for(i =0; str[ i ]!='\0'; i++) { if(str[i]==32 && str[i+1] != 32 || str[i+1] == '\0') { words++; } } printf("\n Total number of words = %d", words); getch(); }

34

Q.4. Write a program which will read a string and rewrite it in the alphabetical order. For example the word STRING should be written as GINRST. [10 marks] Ans. Program to Read a String and Rewrite it in Alphabetical Order-

#include<stdio.h> #include<conio.h> #include<string.h> void main() { char a[80], i, j, t; int len; clrscr(); printf(“\n Enter a string: ”); gets(a); // Sorting string:- Selection sorting len = strlen(a); for(i = 0; i<len - 1; i++) { for(j = i+1; j<len; j++) { if(a[i] > a[j]) { t = a[i]; a[i] = a[j]; a[j] = t; } } } // Displaying the sorted string printf(“\n %s”,a); getch(); }

35

Q.5. Write a program to check whether a string is a palindrome string or not. For example: Naman. [10 marks] Ans. Program to Check Whether a String Is a Palindrome String or Not-

#include<stdio.h> #include<conio.h> #include<string.h> void main() { char str[80],rev[80]; int i, j; printf(“\n Enter any string:”); gets(str); len = strlen(str); i = 0; // Reversing the string for(j = len-1; j>=0; j--) { rev[i] = str[j]; i++; } str[i]=’\0’; d = strcmp(str, rev); if(d == 0) printf(“\n String is a palindrome string.”); else printf(“\n String is Not a palindrome string.”); getch(); }

36

Q.6. What do you mean by recursion? Give an example of recursive function. [5 marks] Ans. RECURSION: In C, it is possible for the functions to call themselves. A function is called ‘recursive’ if a statement within the body of a function calls the same function. Sometimes called ‘circular definition’, recursion is thus the process of defining something in terms of itself. Example-

#include<stdio.h> #include<conio.h> int sumofdigit(int n) { int s; if( n==0 ) return(0); s = n%10 + sumofdigit(n/10); //Recursion return(s); }

void main() { int n,s; clrscr(); n=12345; s = sumofdigit(n); //Calling the function printf("\n %d", s); getch(); }

Note- The compiler uses one such data structure called stack for implementing normal as well as recursive function calls. A stack is a Last In First Out (LIFO) data structure. This means that the last item to get stored on the stack (often called Push operation) is the first one to get out of it (often called as Pop operation). You can compare this to the stack of plates in a cafeteria—the last plate that goes on the stack is the first one to get out of it.

37

Q.7. Write a recursive function to find the factorial of a number passed to it? [5 marks] Ans. A Recursive Function to Find the Factorial of a Number Passed To It-

#include<stdio.h> // Definition of the fuction int fact(int n) { int f; if(n==1) return(1); f = n * fact(n-1); return(f); }

void main() { int n,f; n=6; f = fact(n); // Calling the function printf("\n %d",f); }

38

Q.8. Write a program in C to copy the contents from one file to another file. [10 marks] Ans. Program in C to Copy the Contents from One File to Another File-

#include "stdio.h" #include<stdlib.h> void main( ) { FILE *fs, *ft ; char ch ; fs = fopen ( "pr1.c", "r" ) ; if ( fs == NULL ) { puts ( "Cannot open source file" ) ; exit( ) ; } ft = fopen ( "pr2.c", "w" ) ; if ( ft == NULL ) { puts ( "Cannot open target file" ) ; fclose ( fs ) ; exit( ) ; } while ( 1 ) { ch = fgetc ( fs ) ; if ( ch == EOF ) break ; else fputc ( ch, ft ) ; } fclose ( fs ) ; fclose ( ft ) ;

}

39

Q.9. Write a program in C to read data from the keyboard, write it to file called INPUT, again read the same data from INPUT file and displays it of the screen. [10 marks] Ans. // Receive strings from keyboard and writes them to file

#include "stdio.h" #include<stdlib.h> void main( ) { FILE *fp ; char s[80] ; fp = fopen ( "INPUT.TXT", "w" ) ; if ( fp == NULL ) { puts ( "Cannot open file" ) ; exit( ) ; } printf ( "\nEnter a few lines of text:\n" ) ; while ( strlen ( gets ( s ) ) > 0 ) { fputs ( s, fp ) ; fputs ( "\n", fp ) ; } fclose ( fp ) ; }

// Reads strings from the file and displays them on screen

#include "stdio.h" #include<stdlib.h> void main( ) { FILE *fp ; char s[80] ; fp = fopen ( "INPUT.TXT", "r" ) ; if ( fp == NULL ) { puts ( "Cannot open file" ) ; exit( ) ; } while ( fgets ( s, 79, fp ) != NULL ) { printf ( "%s" , s ) ; } fclose ( fp ) ; }

40

Q.10. Write a program to display the content of a file. [5 marks] Ans. Program to Display the Content of a File-

# include "stdio.h" void main( ) { FILE *fp ; char ch ; fp = fopen ( "xyz.c", "r" ) ; while ( 1 ) { ch = fgetc ( fp ) ; if(ch==EOF) break; printf(“%c”,ch); }

fclose ( fp ) ; }

41

Q.11. What do you mean by structure in C, define? Write a program in C to create a structure named student having the fields name, class and marks. Store the records of 10 students, show all records of students. Then find the record of that student whose mark is maximum. [10 marks] Ans. STRUCTURE:

Structure provides us the facility to combine mix type of data into single unit. With the help of structure we can store mix type of data in a single variable. When we create a structure, a new data type is created. This data type is user defined data type. It is also known as Derived Data type because it is derived from built in data types. A structure gathers together, different atoms of information that comprise a given entity. A structure is a collection of variables under a single name. These variables can be of different types, and each has a name which is used to select it from the structure. A structure is a convenient way of grouping several pieces of related information together. When we have to mange record of books, students, employees or customers, we use structure. Syntax-

struct structure_name { Member variable(s); };

Ex-

struct BOOK { char name[30]; char author[30]; float price; };

Note: struct BOOK is new data type Another way to define a structure is-

typedef struct { char name[30]; char author[30]; float price; }BOOK;

Here, BOOK is new data type Notes-

It declares a structure called "BOOK" and states that this structure contains three pieces of information i.e. name, author and price.

42

Memory space reserved by structure variable is the sum of memory spaces reserved by its members.

Now struct BOOK is a new user defined data type(derived data type) struct BOOK x; // declares a variable names x, whose data type is “struct BOOK”.

Program-

#include<stdio.h> #include<conio.h> typedef struct Stu { char name[30]; char class[10]; int marks; } STUDENT; void main() { STUDENT a[10]; int i, max, index; // Inputting the record of 10 students for(i = 0; i<10; i++) { fflush(stdin); //clears the buffer standard input stream printf("\n Enter name:"); gets(a[i].name); printf("\n Enter Class:"); gets(a[i].class); printf("\n Enter marks:"); scanf("%d",&a[i].marks); } // Displaying the record of 10 students for(i = 0; i<10; i++) { printf("\n\n Name: %s ", a[i].name); printf("\n Class: %s ", a[i].class); printf("\n Marks: %d ", a[i].marks); getch(); } // Finding maximum marks max = a[0].marks; for(i = 1; i<10; i++) { if( a[i].marks > max)

43

{ max = a[i].marks; index = i; } } // Printing the record of the student whose marks is maximum printf("\n Record of the student having maximum Marks :\n "); printf("\n Name: %s ", a[index].name); printf("\n Class: %s ", a[index].class); printf("\n Marks: %d ", a[index].marks); getch(); }

44

Q.12. What is difference between structure and union? [5 marks] Ans. The difference between structure and union is in terms of how the memory is reserved for them. STRUCTURE: A structure has a separate memory location for each of its elements and they all can be used at once.

We can access all the members of structure at anytime. Memory is allocated for all variables. All members of structure can be initialized 'struct' keyword is used to declare structure. The memory space reserve by a structure variable is the sum of memory spaces reserve

by its members. Each member has its own memory location Syntax-

struct struct_name { structure element 1; structure element 2; ---------- ---------- structure element n; }

Union: With a union, you're only supposed to use one of the elements, because they're all stored at the same spot. This makes it useful when you want to store something that could be one of several types.

Only one member of union can be accessed at anytime. Allocates memory for variable which variable require more memory. Only the first member of a union can be initialized. 'union' keyword is used to declare union. The memory space reserve by a structure variable is the memory spaces reserve by its

largest member. Same memory location is shared by all the members at different point of time. Syntax-

union union_name { union element 1; union element 2; ---------- ---------- union element n; };

45

Q.13. A file named DATA contains a series of integers. Write a program to read these numbers and then write all ‘ODD’ numbers to a file called ODD and all even numbers to a file called EVEN. [10 marks] Ans. Program to Read Numbers and Then Write All ‘ODD’ Numbers to File Called ODD and All Even Numbers to a File Called EVEN-

# include <stdio.h> #include <conio.h> void main( ) { FILE *fd, *fe, *fo ; int n; fd = fopen ( "DATA", "r" ) ; fe = fopen ( "EVEN", "w" ) ; fo = fopen ( "ODD", "w" ) ; while ( (n = getw ( fd )) !=EOF ) { if(n%2 == 0) putw(n, fe); else putw(n, fo); } fclose ( fd ) ; fclose ( fe ) ; fclose ( fo ) ; }

46

Q.14. What is pointer? Why are they required? With reference to pointer define the work of & operator? Write a program in C to swap two numbers by using pointer variables. [10 marks] Ans. POINTER:

Pointer is a variable, which is used to hold the address of the variable. A pointer variable can store the address of variable of same data type. For example, to hold the address of integer variable, a pointer variable of integer type is required. Character pointer can hold the address of character variable and so on. Declaration- int *ip; //ip is an integer pointer it can store the address of only integer variable Work of & Operator: & operator returns the address of specified variable. Ex- int x, *ip; ip = &x; // address of x is stored in pointer variable ip. Program in C to swap two numbers by using pointer variables-

#include<stdio.h> #include<conio.h> void main() { int a, b, t, *p1, *p2; a = 30; b = 40; p1 = &a; p2 = &b; // Swapping the values of a and b by using pointers t = *p1; *p1 = *p2; *p2 = t; printf(“\n Value of a and b after swapping-“); printf(“\n a = %d \n b = %d”, a,b); getch(); }

47

Q.15. Write short note on the following- (i) Dynamic memory allocation (ii) malloc and calloc (iii) stack (iv) Linked list [10 Marks] Ans. (I) DYNAMIC MEMORY ALLOCATION

The process of allocating memory during program execution is called dynamic memory allocation. Dynamic memory allocation functions in C: C language offers 4 dynamic memory allocation functions. They are,

1. malloc() 2. calloc() 3. realloc() 4. free()

S.no Function Syntax

1 malloc () malloc (number *sizeof(int));

2 calloc () calloc (number, sizeof(int));

3 realloc () realloc (pointer_name, number * sizeof(int));

4 free () free (pointer_name); STATIC MEMORY ALLOCATION AND DYNAMIC MEMORY ALLOCATION:

S.no Static memory allocation Dynamic memory allocation

1

In static memory allocation, memory is allocated while writing the C program. Actually, user requested memory will be allocated at compile time.

In dynamic memory allocation, memory is allocated while executing the program. That means at run time.

2 Memory size can’t be modified while execution. Example: array

Memory size can be modified while execution. Example: Linked list

48

(ii) malloc and calloc malloc()

Allocates the specified number of bytes at the run time and returns a pointer to first byte of allocated space. Syntax- void *malloc(number_of_bytes) ptr = (typecast *) malloc (sizeof(data)); That is to say it returns a pointer of type void * that is the start in memory of the reserved portion of size number_of_bytes. If memory cannot be allocated a NULL pointer is returned. Since a void * is returned the C standard states that this pointer can be converted to any type. Ex-

char *cp; cp = malloc(100); attempts to get 100 bytes and assigns the start address to cp. int *ip; ip = (int *) malloc(2)); //typecasting ip = (int *) malloc(sizeof(int)); ip = (int *) malloc(100*sizeof(int)); Notes:-

Malloc does not initialise memory (to zero) in any way. Some C compilers may require to cast the type of conversion.

calloc()-

Allocates space for array elements, initializes to zero and then returns a pointer to memory. Syntax- void *calloc(num_of_elements, element_size); Thus to assign 100 integer elements that are all initially zero you would do: Ex- int *ip; ip = (int *) calloc(100, sizeof(int)); Differences between malloc() and calloc() There are two differences between these functions.

49

1. First, malloc() takes a single argument (the amount of memory to allocate in bytes), while calloc() needs two arguments (the number of variables to allocate in memory, and the size in bytes of a single variable).

2. Secondly, malloc() does not initialize the memory allocated, while calloc() initializes all bytes of the allocated memory block to zero

(III) STACK-

A stack is a Last In First Out (LIFO) data structure. This means that the last item to get stored on the stack (often called Push operation) is the first one to get out of it (often called as Pop operation). You can compare this to the stack of plates in a cafeteria—the last plate that goes on the stack is the first one to get out of it. There are different ways in which data can be organized. For example, if you are to store five numbers then we can store them in five different variables, an array, a linked list, a binary tree, etc. All these different ways of organizing the data are known as data structures (IV) LINKED LIST

A linked list is a set of dynamically allocated nodes, arranged in such a way that each node contains one value and one pointer. The pointer always points to the next member of the list. If the pointer is NULL, then it is the last node in the list. A linked list is held using a local pointer variable which points to the first item of the list. If that pointer is also NULL, then the list is considered to be empty.

A linked list whose nodes contain two fields: an integer value and a link to the next node. The last node is

linked to a terminator used to signify the end of the list. Linked list is a dynamic data structure whose length can be increased or decreased at run time. Linked lists are among the simplest and most common data structures. They can be used to implement several other common abstract data types, including lists (the abstract data type), stacks, queues etc. Advantages:

Linked lists are a dynamic data structure, allocating the needed memory when the program is initiated.

Insertion and deletion node operations are easily implemented in a linked list. Linear data structures such as stacks and queues are easily executed with a linked list. They can reduce access time and may expand in real time without memory overhead.

Disadvantages:

They have a tendency to waste memory due to pointers requiring extra storage space.

50

Nodes in a linked list must be read in order from the beginning as linked lists are inherently sequential access.

Nodes are stored incontiguously, greatly increasing the time required to access individual elements within the list.

Difficulties arise in linked lists when it comes to reverse traversing. Singly linked lists are extremely difficult to navigate backwards, and while doubly linked lists are somewhat easier to read, memory is wasted in allocating space for a back pointer.

Q.16. Given high level I/O functions file management in C, complete the following- [10] S.No. Function Operation Syntax

1 fopen() 2 getc() 3 putc() 4 fprintf() 5 getw() 6 putw() 7 fseek() 8 ftell() 9 fscanf()

10 rewind() 11 ftell()

Ans. File Handling Functions with description and syntax- S.No. Function Operation Syntax

1 fopen() Creates a new file for use Opens a new existing file for use

fp=fopen(“filename”,”mode”);

2 fclose Closes a file which has been opened for use fclose(fp); 3 getc() Reads a character from a file c=getc(fp); 4 putc() Writes a character to a file putc(c,fp); 5 fprintf() Writes a set of data values to a file fprintf(fp,”control string”, list); 6 fscanf() Reads a set of data values from a file fscanf(fp,”controlstring”,list); 7 getw() Reads a integer from a file number=getw(fp); 8 putw() Writes an integer to the file putw(number,fp); 9 fseek() Sets the position to a desired point in the file fseek ( fp, -recsize, SEEK_CUR ) ;

); 10 rewind() Sets the position to the beginning of the file rewind(fp); 11 ftell() Gives the current position in the file n= ftell(fp);

Note-

Here, -recsize moves the pointer back by recsize bytes from the current position. SEEK_CUR is a macro defined in “stdio.h”.

51

MORE PROGRAMS RELATED TO FILE HANDLING (1) Program to write number into a file named DATA.

#include <stdio.h> #include <conio.h> void main( ) { FILE *fd ; int n; clrscr(); fd = fopen ( "DATA", "w" ) ; if(fd == NULL) { printf("\n Can't open the file."); exit(0); } while (1) { printf("\n Enter a number to save into file.(-1 to exit): "); scanf("%d",&n); if(n == -1) break; putw(n, fd); } fclose ( fd ) ; getch(); }

52

(2) Program to read number from a file named DATA and display on the screen.

#include <stdio.h> #include <conio.h> void main( ) { FILE *fd ; int n; clrscr(); fd = fopen ("data", "r" ) ; if(fd == NULL) { printf("\n Can't open the file."); exit(0); } while ( (n=getw(fd)) != EOF) { printf("%d \n", n); } fclose ( fd ) ; getch(); }

53

(3) Program to count chars, spaces, tabs and newlines in a file # include "stdio.h" void main( ) { FILE *fp ; char ch ; int nol = 0, not = 0, nob = 0, noc = 0 ; fp = fopen ( "PR1.C", "r" ) ; while ( 1 ) { ch = fgetc ( fp ) ; if ( ch == EOF ) break ; noc++ ;

if ( ch == ' ' ) nob++ ;

if ( ch == '\n' ) nol++ ;

if ( ch == '\t' ) not++ ; }

fclose ( fp ) ;

printf ( "\nNumber of characters = %d", noc ) ; printf ( "\nNumber of blanks = %d", nob ) ; printf ( "\nNumber of tabs = %d", not ) ; printf ( "\nNumber of lines = %d", nol ) ; }

*****End*****