34
Prof. A. Syed Mustafa HKBK COLLEGE OF ENGINEERING , Bengaluru-45 ANSWER TO MODEL QUESTION PAPER- 15PCD13- PROGRAMMING IN C AND DATA STRUCTURE

VTU PCD Model Question Paper - Programming in C

Embed Size (px)

Citation preview

Page 1: VTU PCD Model Question Paper - Programming in C

Prof. A. Syed Mustafa

HKBK COLLEGE OF ENGINEERING , Bengaluru-45

ANSWER TO MODEL QUESTION PAPER- 15PCD13- PROGRAMMING IN C AND

DATA STRUCTURE

Page 2: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 1

Page 3: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 2

Page 4: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 3

ANSWERS

1 a. Here is list of possible names for variables in C language. Which are valid names and invalid names? If name is invalid, explain why?

# Variable / identifier

Valid/ Invalid Reason

i). 1999_space Invalid Variable or identifier

Because variable or identifier should start with alphabet or _ (underscore) and after that it can have alphabet/ numeric values [digits]. Variable name should be defined as alphanumeric. It cannot start with numeric values.

ii). _apple Valid Variable / identifier.

-

iii). iNtEL Valid Variable / identifier.

-

iv). one_2 Valid Variable / identifier.

-

v). for Invalid Variable or identifier

Because ‘for’ is a keyword

vi). #12 Invalid Variable or identifier

Because variable or identifier should start with alphabet or _ and after that it can have alphabet/ numeric values [digits]. Variable name should be defined as alphanumeric. It cannot start with # symbol.

vii). i.b.m Invalid Variable or identifier

Because variable or identifier cannot have (.) dot symbol.

viii). help+me Invalid Variable or identifier

Because variable or identifier cannot have (+) plus symbol.

1b. What is the purpose of a printf() statement? Explain the formatted printf() along with the respective examples.

In the C Programming Language, the printf function writes a formatted string to the stdout stream.

SYNTAX

The syntax for the printf function in the C Language is:

int printf(const char *format, ...);

The printf function does following tasks:

→ Accept a series of arguments

→ Apply to each argument a format-specifier contained in the format-string

→ Output the formatted data to the screen

Page 5: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 4

• The syntax is shown below:

printf("format-string", variable-list);

where format-string contains one or more format-specifiers variable-list contains names of variables

Format specifiers Meaning

%d an int argument in decimal %ld a long int argument in decimal %c a character %s a string %f a float or double argument %e same as %f, but use exponential notation %o an int argument in octal (base 8) %x an int argument in hexadecimal (base 16)

#include <stdio.h> int main() { char ch = ‘A’; char str[20] = “HELLO”; float flt = 10.234; int no = 150; double dbl = 20.123456; printf(“Character is %c \n”, ch); printf(“String is %s \n” , str); printf(“Float value is %f \n”, flt); printf(“Integer value is %d\n” , no); printf(“Double value is %lf \n”, dbl); printf(“Octal value is %o \n”, no); printf(“Hexadecimal value is %x \n”, no); return 0; } .

Output:

Character is A String is HELLO Float value is 10.234000 Integer value is 150 Double value is 20.123456 Octal value is 226 Hexadecimal value is 96 .

Page 6: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 5

2 a. Write a C program to find area of a triangle when we know the lengths of all three of its sides.

Steps to find the area of a triangle using Heron's formula

Let A, B and C be the length of three sides of a triangle.

Calculate the semi perimeter of the triangle. Semi-Perimeter of triangle(S) = (A + B + C)/2

Now, we can calculate the area of triangle using below mentioned formula. Area of Triangle = √ S(S-A)(S-B)(S-C)) Where, S is the semi-perimeter that we calculated in first step.

#include <stdio.h> #include <math.h> #include <conio.h> int main() { float a, b, c, s, area; printf("Enter the length of three sides of triangle\n"); scanf("%f %f %f", &a, &b, &c); s = (a + b + c)/2; area = sqrt(s*(s-a)*(s-b)*(s-c)); printf("Area of triangle : %0.2f\n", area); getch(); return 0; }

Program Output

Enter the length of three sides of triangle

3 4 5

Area of triangle : 6.00

2b. Write a C program that computes the size of int, float, double and char variables.

The sizeof is a keyword, but it is a compile-time operator that determines the size, in bytes, of a variable or data type.

C Programming sizeof operator 1. sizeof operator is used to calcualte the size of data type or variables.

2. sizeof operator can be nested.

3. sizeof operator will return the size in integer format.

4. sizeof operator syntax looks more like a function but it is considered as an operator

in c programming

Page 7: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 6

The syntax of using sizeof is as follows:

int sizeof (data type);

#include<stdio.h>

#include<conio.h>

void main() { int x; float y; double z; char ch; clrscr(); printf("Size of integer variable x:%d\n",sizeof(x)); printf("Size of float variable y:%d\n",sizeof(y)); printf("Size of double variable z:%d\n",sizeof(z)); printf("Size of character variable char:%d\n",sizeof(char)); getch(); } OUTPUT:

Size of integer variable x:2 Size of float variable y:4 Size of double variable z:8

Size of character variable char: 1

2c. What are Operators? Explain the relational and logical operators supported in C Language.

An operator is a symbol that tells the compiler to perform specific

mathematical or logical functions. C language is rich in built-in operators and

provides the following types of operators −

Arithmetic Operators

Relational Operators

Logical Operators

Bitwise Operators

Assignment Operators

Conditional operator/ ternary operator

Page 8: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 7

Relational Operators

The following table shows all the relational operators supported by C. Assume

variable A holds 10 and variable B holds 20 then

Operator

Description Example

== Checks if the values of two operands are equal or not. If yes, then the condition becomes true.

(A == B) is not true.

!= Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true.

(A != B) is true.

> Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true.

(A > B) is not true.

< Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true.

(A < B) is true.

>= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true.

(A >= B) is not true.

<= Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true.

(A <= B) is true.

Page 9: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 8

Logical Operators

Following table shows all the logical operators supported by C language.

Assume variable A holds 1 and variable B holds 0, then

Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.

(A && B) is false.

|| Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.

(A || B) is true.

! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.

!(A && B) is true.

Page 10: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 9

3 a. Explain the Syntax of nested if …else statement. Write a C program to find largest of three numbers using nested if … else statement.

Page 11: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 10

3b. Explain the syntax of do-while statement. Write a C program to find the factorial of a number using while loop, where the number n is entered by the user. (Hint: factorial of n = 1*2*3*….*n).

Page 12: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 11

/* calculate factorial value using do..while */

#include<stdio.h>

#include<conio.h>

void main()

{

long int i,n,fact=1; /*variable declaration */ clrscr(); printf("Enter the value of n \n"); scanf("%ld", &n); /* do loop start */ i=1; do

{

fact=fact*i; i++; }while(i<=n); printf("Factorial = %ld\n",fact); getch(); }

Output:

Enter the value of n 5 Factorial =120 Another Example: #include<stdio.h>

#include<conio.h>

void main()

{ int n; long int f=1; clrscr(); printf("enter any number\n"); scanf("%d",&n); do

{

f=f*n; n--; }while(n>0); printf("factorial is=%d\n",f); getch(); }

Page 13: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 12

4 a. Write a C Program to find GCD of two numbers using ternary operator and for loop. This program is little optimized than the other GCD programs to find GCD/H.C.F. In this program, smallest of two integers entered by user is stored in variable min. Then i is initialized to min and

for loop is executed. In each looping iteration, whether i is factor of these two numbers is checked.

If i is a factor of these two numbers then, i will be the Greatest Common Divisor / Highest Common Factor and loop is terminated using break statement.

#include <stdio.h> void main() { int n1, n2, min,i,gcd; printf("Enter two Numbers:\n"); scanf("%d%d", &n1, &n2); min=(n1<n2)?n1:n2; /* minimum value is stored in variable min */ for(i=min;i>0;i--) if(n1%i==0 && n2%i==0) { gcd=i; break; } printf("HCF/GCD of %d and %d is %d\n", n1, n2,i); }

Output Enter two Numbers: 20 35 HCF/GCD of 20 and 35 is 5

4b. Write a calculator program in C language to do simple operations like addition, subtraction, multiplication and division. Use switch statement in your program. void main() { char op; float n1,n2,res; printf("Enter the Expression in value operator value format\n"); scanf("%f%c%f",&n1,&op,&n2); switch(op) { case '+' : res= n1+n2; break; case '-' : res= n1-n2; break; case '*' : res= n1*n2; break; case '/' : res= n1/n2; break; default : printf("Error! operator is not correct"); break; } printf(“%f\n”,res); }

Page 14: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 13

5a. What is an array? Explain the declaration and initialization of single dimensional array with example.

ARRAY

• Array is a collection of elements of same data type.

• The elements are stored sequentially one after the other in memory.

• Any element can be accessed by using

→ name of the array

→ position of element in the array

• Arrays are of 2 types: 1) Single dimensional array

2) Multi dimensional array

SINGLE DIMENSIONAL ARRAY

• A single dimensional array is a linear list consisting of related elements of same type.

• In memory, all the elements are stored in continuous memory-location one after the other.

Declaration of Single Dimensional Arrays

• The syntax is shown below: data_type array_name[array_size]

where data_type can be int, float or char array_name is name of the array

array_size indicates number of elements in the array

• For ex:

int age[5];

• The above code can be pictorially represented as shown below:

• Note that, the first element is numbered 0 and so on.

• Here, the size of array “age‟ is 5 times the size of int because there are 5 elements.

Storing Values in Arrays

• The values can be stored in array using following three methods: 1) Initialization 2) Assigning values

3) Input values from keyboard

Page 15: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 14

Initialization of One-Dimensional Array

• The syntax is shown below:

data_type array_name[array_size]={v1,v2,v3}; where v1, v2, v3 are values

• For ex:

int age[5]={2,4,34,3,4};

• The above code can be pictorially represented as shown below:

Page 16: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 15

5b. Write a C Program to concatenate two strings without using built in function strcat( ). #include <stdio.h> void main() { char s1[100], s2[100], i, j; printf("Enter first string:"); scanf("%s",s1); printf("Enter second string: "); scanf("%s",s2); for(i=0; s1[i]!='\0'; i++); /* i contains length of string s1. */ for(j=0; s2[j]!='\0'; j++) { s1[i]=s2[j]; i++; } s1[i]='\0'; printf("After concatenation: %s\n",s1); }

Output: Enter first string: HKBK Enter second string: College After concatenation: HKBKCollege

5c. Write a C program to check a number is a prime number or not using recursion.

If a number is divisible between any one of the number of 2 to number/2 [ half of the number], then the given number is not a prime. Otherwise it is divisible only by 1 and itself. #include<stdio.h> int isPrime(int,int); void main( ) { int num,prime; printf("Enter a positive number: "); scanf("%d",&num); prime = isPrime(num,num/2); if(prime==1) printf("%d is a prime number",num); else printf("%d is not a prime number",num); } int isPrime(int num, int i)

Page 17: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 16

{ if(i==1) return 1; else { if(num%i==0) return 0; else isPrime(num, i-1); } } Output: Enter a positive number: 13 13 is a prime number

6a. What is function? Write a C program to find cube of a Number using function.

Function Declaration

Every function in C program should be declared before they are used.

• Function declaration gives compiler information about → function name

→ type of arguments to be passed and return type

Page 18: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 17

The syntax is shown below:

return_type function_name(type argument1,....,type argumentn);

Function Call

• Control of the program cannot be transferred to user-defined function unless it is called invoked.

• The syntax is shown below: function_name(argument1,....argumentn);

Function Definition

• Function definition contains programming codes to perform specific task.

• The syntax is shown below: return_type function_name(type argument1,..,type argumentn)

{

//body of function

}

#include<stdio.h> #include<conio.h> int cube(int n); void main() { int n,c; clrscr(); printf("\n Enter Any Number : "); scanf("%d",&n); c=cube(n); printf("\n\n Cube of %d is %d",n,c); getch(); } int cube(int n) { return(n*n*n); }

Output: Enter Any Number : 5 Cube of 5 is 125

Page 19: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 18

6b. List string manipulation library functions and explain any two of them with Example

STRING MANIPULATION FUNCTIONS FROM THE STANDARD LIBRARY

• Strings are often needed to be manipulated by programmer according to the need of a problem.

• All string manipulation can be done manually by the programmer but, this makes programming complex and large.

• To solve this, the C supports a large number of string handling functions. • There are numerous functions defined in <string.h> header file.

int strcmp(char *string1,const char *string2) -Compare string1 and string2 to determine alphabetic order.

returns zero if they are same.

If length of string1 < string2, it returns < 0 value.

If length of string1 > string2, it returns > 0 value. #include <stdio.h> #include <string.h> void main( ) { char str1[ ] = "abc" ; char str2[ ] = "bbc" ; int i, j, k ; i = strcmp ( str1, "abc" ) ; j = strcmp ( str1, str2 ) ; k = strcmp ( str2, str1 ) ; printf ( "\n%d %d %d", i, j, k ) ; }

Output:

0 -1 1

Page 20: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 19

char *strcpy(char *string1,const char *string2) - Copy string2 to stringl. #include <stdio.h> #include <string.h> vod main( ) { char source[ ] = "Program" ; char target[20] ; printf ( "\nsource string = %s", source ) ; strcpy ( target, source ) ; printf ( "\ntarget string after strcpy( ) = %s", target ) ; } Output:

source string = Program target string after strcpy( ) = Program

size_t strlen(const char *string) - Determine the length of a string. #include <stdio.h> #include <string.h> void main( ) { int len; char a[20]="Bengaluru" ; len = strlen(a) ; printf ( "\string length = %d \n" , len ) ; } Output:

string length = 9

char * strcat ( char * destination, const char * source ) - concatenates two given strings. It concatenates source string at the end of destination string.

#include <stdio.h> #include <string.h> void main() { char s1[10] = "Hello"; char s2[10] = "World"; strcat(s1,s2); printf("Output string after concatenation: %s", s1); } Output: Output string after concatenation: HelloWorld

Page 21: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 20

6c. Write a C Program to find greatest number from two dimensional array. #include<stdio.h> #include<conio.h> main() { int m, n, i, j, a[10][10], maximum; printf("Enter the number of rows and columns of matrix\n"); scanf("%d%d",&m,&n); printf("Enter the elements of matrix\n"); for( i = 0 ; i < m ; i++ ) for( j = 0 ; j < n ; j++ ) scanf("%d",&a[i][j]); maximum = a[0][0]; for( i = 0 ; i < m ; i++ ) for( j = 0 ; j < n ; j++ ) if (a[i][j] > maximum ) maximum = a[i][j]; printf("Maximum element in matrix is %d\n", maximum); getch(); }

Output: Enter the number of rows and columns of matrix 3 4 Enter the elements of matrix 3 2 6 1 9 45 33 22 11 34 32 -3 Maximum element in matrix is 45

7 a. What is a structure? Explain the C syntax of structure declaration with an example.

STRUCTURE:

Structure is a collection of elements of different data type.

Structure is a user-defined data type in C which allows you to combine different data types to store a particular type of record. Structure helps to construct a complex data type in more meaningful way.

Structure is composition of the different variables of different data types , grouped under same name.

C Structure is a collection of different data types which are grouped together and each element in a C structure is called member.

The variables that are used to store the data are called members of the structure.

Page 22: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 21

Declaring, initializing and accessing a C structure:

Type Using normal variable Using pointer variabe

Syntax struct tag_name { data type var_name1; data type var_name2; data type var_name3; };

struct tag_name { data type var_name1; data type var_name2; data type var_name3; };

Example struct student { int mark; char name[10]; float average; };

struct student { int mark; char name[10]; float average; };

Declaring structure variable struct student report; struct student *report, rep;

Initializing structure variable struct student report = {100, “Ravi”, 99.5};

struct student rep = {100, “Ravi”, 99.5}; report = &rep;

Accessing structure members

report.mark report.name report.average

report -> mark report -> name report -> average

Type Defined Structure

Another way of creating sturcture variable using the keyword typedef is:

typedef struct person { char name[50]; int age; float salary; } EMP; Inside main function:

EMP p1 ,p2 ; Here the above statement declares that the variables p1 and p2 are variables of type EMP(which is of type as struct person).

Declaring Structure Variables with Structure definition

struct Student { int rollno; char name[20]; floar marks; } S1, S2 ;

Page 23: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 22

7b. What is a file? Explain file open and close functions with arguments. A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. C programming language can handle files as Stream-oriented data (Text) files and System oriented data Binary) files. DEFINING, OPENING AND CLOSING OF FILES

Defining a File

• While working with file, we need to declare a pointer of type “FILE‟. This declaration is needed for communication between file and program.

FILE *ptr;

Opening a File

• fopen( ) function can be used

to create a new file or to open an existing file

• This function will initialize an object of the type FILE, which contains all the information necessary to control the stream.

• The syntax is shown below:

FILE *fopen( const char *filename, const char *access_mode );

where filename is string literal, which you will use to name your file. Opening Modes in Standard I/O

File Mode Meaning of Mode During Inexistence of file

r Open for reading. If the file does not exist, fopen() returns NULL.

w Open for writing. If the file exists, its contents are overwritten. If the file does not exist, it will be created.

a Open for append. i.e, Data is added to end of file. If the file does not exists, it will be created.

r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.

w+ Open for both reading and writing.

If the file exists, its contents are overwritten. If the file does not exist, it will be created.

a+ Open for both reading and appending. If the file does not exists, it will be created.

Page 24: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 23

Closing a File

The file should be closed after reading/writing of a file.

fclose( ) function can be used to close a file. The syntax is shown below:

int fclose(FILE *fp);

The fclose( ) function returns zero on success or returns EOF(special character) if there

is an error.

Example:

void main()

{

FILE *fp;

fp = fopen("/tc/bin/test.txt", w+");

fprintf(fp, "writing to file...\n");

fputs("again writing to file...\n", fp);

fclose(fp);

}

7.c Explain fputc( ), fputs( ), fgetc( ) and fgets() functions with syntax.

INPUT AND OUTPUT OPERATIONS

Writing to a File: fputc(), fputs()

• fputc function can be used to write individual characters to a file stream: int fputc(int c, FILE *fp);

• The function fputc() writes the character value of argument c to the output stream referenced by fp.

• This function returns the written character on success; otherwise returns EOF if there is an error.

• fputs function can be used to write a null-terminated string to a file stream: int fputs( const char *s, FILE *fp );

• The function fputs() writes the string s into the file referenced by fp.

• This function returns a non-negative value i.e no. of characters written to the file on success; otherwise returns EOF if there is an error.

Reading a File: fgetc(), fgets()

• fgutc function can be used to read a text file character by character: int fgetc( FILE * fp );

Page 25: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 24

• The fgetc() function reads a character from the input file referenced by fp.

• This function returns the character being read on success; otherwise returns EOF if there is an error.

• fgets function can be used to read a string from a file stream:

char *fgets( char *buf, int n, FILE *fp );

• The functions fgets() reads up to n-1 characters from the input stream referenced by fp.

• It copies the read string into the buffer buf, appending a null character to terminate the string.

• If this function encounters a newline character '\n‟, then it returns only the characters read up to that point including new line character.

Example: Program to copy a file content to an another file. #include <stdio.h> #include <stdlib.h> void main() { char ch; FILE *fin,*fout; fin = fopen(“f1”,"r"); /* read mode*/ fout = fopen(“f2”,"w"); /* write mode*/ if( fin = = NULL ) { perror("Error while opening the file.\n"); exit(0); } while( ( ch = fgetc(fin) ) != EOF ) fputc(ch,fout); fclose(fin); fclose(fout); }

Example for fgets() and fputs() #include <stdio.h> void main() { FILE *fp; char a[50]; fp = fopen(“f1”,"w"); /* write mode*/ fputs("Hello world",fp); fclose(fp); fp = fopen(“f1”,"r"); /* read mode*/ fgets(a,12,fp); fclose(fp); printf(“ File content is %s\n”,a); }

Page 26: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 25

8 a. Write a C program to store Name, USN, subject name and IA Marks of students using structure.

struct student /* Declare Strucure*/

{

char Name[30]; /* Structure member stores student name */

char USN[10]; /* Structure member stores student USN */

char Subname[30]; /* Structure member stores subject name */

float IA; /* Structure member stores IA marks */

};

void main( )

{

struct student s1; /* declaring structure variable */

clrscr();

printf("\nEnter the Student Name\n"); /* input details*/

gets(s1.Name);

printf("Enter the Student USN\n");

scanf("%s",s1.USN);

printf("nEnter the Subject Name\n");

gets(s1.Subname);

printf("Enter the Student IA mark\n");

scanf("%f", &s1.IA);

printf("Student Details are\n"); /* display Details*/

printf("Student Name: %s\n", s1.Name);

printf("Student USN: %s\n", s1.USN);

printf("Subject Name: %s\n", s1.Subname);

printf("IA Mark: %.2f\n", s1.IA);

}

Page 27: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 26

8b. Explain how the structure variable passed as a parameter to a function with Example #include <stdio.h> #include <conio.h> struct employee /* declaring structure */ { char name[30]; int age; float salary; }; typedef struct employee EMP; /* user defined data type */ void getdetails(EMP *e1 ) /* function reads employee details by call / pass by reference*/ { printf("\nEnter Employee name:"); gets(e1 name); printf("\nEnter age:"); scanf("%d",&e1 age); printf("\nEnter Salary:"); scanf("%f",&e1 salary); } void displaydetails(EMP e1) /* function displays employee details by call/pass by value */ { printf("Name of the Employee : %s \n",e1.name); printf("Age of the Employee : %d \n",e1.age); printf("Salary of the Employee : %.2f \n",e1.salary); } int main( ) { EMP e1; clrscr(); getdetails(&e1); /* function call to read employee details using call by reference*/ displaydetails(e1); /* function call to display employee details using call by value */ getch(); }

Output: Enter Employee name: Pranab singh Enter age: 25 Enter Salary: 25000 Name of the Employee: Pranab singh Age of the Employee : 25 Salary of the Employee : 25000

Page 28: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 27

In C, structure can be passed to functions by two methods:

1. Passing by value (passing actual value as argument)

2. Passing by reference (passing address of an argument)

Passing structure by value

A structure variable can be passed to the function as an argument as normal variable. If

structure is passed by value, change made in structure variable in function definition does not

reflect in original structure variable in calling function.

Eg: displaydetails(e1); e1 member values will not be changed by this function.

Passing structure by reference

The address location of structure variable is passed to function while passing it by reference.

If structure is passed by reference, change made in structure variable in function definition

reflects in original structure variable in the calling function.

Eg: getdetails(&e1); e1 member values are initialized and changed by this function.

8c. Write a C program to read and display a text from the file.

#include <stdio.h> #include <stdlib.h> void main( ) { char ch, fname[25]; FILE *fp; printf("Enter the name of file \n"); gets(fname); fp = fopen(fname,"r"); /* opening file in read mode */ if( fp = = NULL ) { perror("Error while opening the file.\n"); exit(0); } printf("The contents of %s file are :\n", fname); while( ( ch = fgetc(fp) ) != EOF ) /* reading each character from file till end of file */ printf("%c",ch); fclose(fp); /* closing file */ }

Page 29: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 28

9 a. Write and explain any five preprocessor directives in C.

Preprocessor Directive / Macros:

The C preprocessor [CPP] is a macro processor that is used automatically by the C compiler to transform

programmer defined programs before actual compilation takes place. It is called a macro processor because

it allows the user to define macros, which are short abbreviations for longer constructs.

It instructs the compiler to do required pre-processing before the actual compilation. All preprocessor

directives begin with the # symbol (known as pound or hash).

List of pre-processor directives:

1. #include: This is used insert a particular header from another file.

2. #define, #undef : These are used to define and un-define conditional compilation symbols.

3. #if, #elif, #else, #endif : These are used to conditionally skip sections of source code.

Example:

#include “demo.h”

--tells CPP to get demo.h from the local directory and add the content to the current source file.

#define PI 3.1412 /* defines symbolic constant */

--This directive tells the CPP to replace symbolic constant pi with 3.1412.

#define SIZE 5 /* SIZE will be replaced with 5 */

Program to find area of a circle using #define. #include<stdio.h>

#define PI 3.1412

int main()

{

int radius; float area;

printf("Enter the radius: ");

scanf("%d", &radius);

area=PI*radius*radius;

printf("Area=%.2f",area);

return 0;

}

Use of #if, #elif, #else and #endif :

The preprocessor directives #if, #elif, #else and #endif allows to conditionally compile a block of code

based on predefined symbols.

#include<stdio.h>

#define MAX 100

void main( )

{

#if (MAX)

printf("MAX is defined");

#else

printf ("MAX is not defined");

#endif

}

Page 30: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 29

9 b. Write a C program to swap two numbers using call by pointers

method.

CALL BY ADDRESS/POINTER

The call to the function passes variable’s address to the called function. The actual arguments

are not copied to the formal arguments, the addresses of actual arguments (or parameters)

are passed to the formal parameters. Hence any operation performed by function on formal

arguments / parameters affects actual parameters.

void swap(int *x, int *y) /* function to swap 2 values using pointers as call by address */

{

int t;

t = *x;

*x = *y;

*y = t;

}

void main( )

{

int a=5, b=10 ;

printf("Before swap: a=%d,b=%d",a,b);

swap(&a, &b); /*calling swap function by passing address*/

printf("After swap: a= %d,b=%d",a,b);

}

Output: Before swap: a=5, b=10 After swap: a=10, b=5 Because variable declared ‘a’, ‘b’ in main() is different from variable ‘x’, ’y’ in swap().

Only variable names are different but both a and x, b and y point to the same memory

address locations respectively.

Page 31: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 30

9 c. Explain malloc( ), calloc( )functions with examples.

MEMORY ALLOCATION FUNCTIONS

1. Static Memory Allocation:

Memory space allocated from stack at compile time for variables declared in the program is fixed, it

cannot be altered during execution-time. This is called static memory allocation.

Example: int a[5]; float d;

2. Dynamic Memory Allocation

It is the process of allocating memory-space during execution-time i.e. run time from Heap. If there is

an unpredictable storage requirement, then the dynamic allocation technique is used.

This allocation technique uses predefined functions to allocate and release memory for data during

execution-time.

There are 4 library functions for dynamic memory allocation:

malloc( ), calloc( ), free( ), realloc( )

These library functions are defined under "stdlib.h"

1. malloc( ) -memory allocation

This function is used to allocate the required memory space during execution-time.

The syntax is shown below:

data_type *p;

p=(data_type*)malloc(size);

Here p is pointer variable.

data_type can be int, float or char. size is number of bytes to be allocated.If memory is successfully

allocated, then address of the first byte of allocated space is returned. If memory allocation fails, then

NULL is returned.

For ex: int *ptr;

ptr=(int*)malloc(100*sizeof(int));

The above code will allocate 200 bytes assuming sizeof(int)=2 bytes

2. calloc( ) - contiguous allocation This function is used to allocate the required memory-size during execution-time and at the same time,

automatically initialize memory with 0's.

syntax :

data_type *p;

p=(data_type*)calloc(n,size);

Ex:

p=(int*)calloc(25,sizeof(int));

3. free( )

Dynamically allocated memory with either calloc( ) or malloc( ) can be deallocated using free( )

explicitly to release space.

syntax:

free(ptr);

4. realloc() -reallocation

If the previously allocated memory is insufficient or more than sufficient. Then, we can change memory-

size previously allocated using realloc().

Page 32: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 31

The syntax is shown below:

ptr=(data_type*)realloc(ptr,newsize);

Example: Program to find the print 5 values using dynamic memory allocation & pointers

void main( )

{

int i;

int *a= (int *)malloc(10);

for(i=0;i<5;i++)

*(a+i)=i+10;

for(i=0;i<5;i++)

printf(“%d\t”,*(a+i)10;

}

Output: 10 11 12 13 14

10 a. Explain stack and queue related terms and give their applications.

STACKS • A stack is a special type of data structure where elements are inserted from one end and elements are deleted from the same end. • Using this approach, the Last element Inserted is the First element to be deleted Out, and hence, stack is also called LIFO data structure. • The various operations performed on stack:

Insert: An element is inserted from top end. Insertion operation is called push operation. Delete: An element is deleted from top end. Deletion operation is called pop operation. Overflow: Check whether the stack is full or not. Underflow: Check whether the stack is empty or not.

• This can be pictorially represented as shown below:

APPLICATIONS OF STACK 1) Conversion of expressions: The compiler converts the infix expressions into postfix expressions using stack. 2) Evaluation of expression: An arithmetic expression represented in the form of either postfix or prefix can be easily evaluated using stack. 3) Recursion: A function which calls itself is called recursive function. 4) Other applications: To find whether the string is a palindrome, to check whether a given expression is valid or not.

Page 33: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 32

QUEUES • A queue is a special type of data structure where elements are inserted from one end and elements are deleted from the other end. • The end at which new elements are added is called the rear and the end from which elements are deleted is called the front. • The first element inserted is the first element to be deleted out, and hence queue is also called FIFO data structure. • The various operations performed on queue are

1) Insert: An element is inserted from rear end.

2) Delete: An element is deleted from front end. 3) Overflow: If queue is full and we try to insert an item, overflow condition occurs. 4) Underflow: If queue is empty and try to delete an item, underflow condition occurs.

• This can be pictorially represented as shown below:

10 b. What is pointer? Give the advantages and disadvantages of pointer

data type.

Pointers

A Pointer is just an address of the data stored in memory.

A pointer is a variable whose value is the address of another variable, i.e., direct address of the

memory location.

Syntax:

<variable_type> *<name>=&variable;

eg:- int *a=&b;

‘ * ’ used to declare a pointer variable and also used to retrieve the value from the pointed

memory location. ‘ * ’ is also called as derefence operator.

#include <stdio.h> void main () { int a = 20; /* actual variable declaration */ int *ip; /* pointer variable declaration */

ip = &a; /* store address of var in pointer variable*/

printf("Address of variable a is: %x\n", &a );

/* address stored in pointer variable */

Page 34: VTU PCD Model Question Paper - Programming in C

PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13

HKBK College of Engineering, Bengaluru 33

printf("Address stored in variable ip is: %x\n", ip );

/* access the value using the pointer */

printf("Value of *ip variable: %d\n", *ip );

}

Output: Address of variable a is: bffd8b3c Address stored in variable ip is: bffd8b3c Value of *ip variable: 20

ADVANTAGES OF POINTERS

1. Pointers provide direct access to memory 2. Pointers provide a way to return more than one value to the functions 3. Reduces the storage space and complexity of the program 4. Reduces the execution time of the program 5. Provides an alternate way to access array elements 6. Pointers can be used to pass information back and forth between the calling function and

called function. 7. Pointers allows us to perform dynamic memory allocation and deallocation. 8. Pointers helps us to build complex data structures like linked list, stack, queues, trees,

graphs etc. 9. Pointers allows us to resize the dynamically allocated memory block.

10. Pointers reduce length and complexity of programs

DISADVANTAGES OF POINTERS

1. Uninitialized pointers might cause segmentation fault. 2. Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to

memory leak. 3. Pointers are slower than normal variables. 4. If pointers are updated with incorrect values, it might lead to memory corruption.

******** ALL THE BEST *******