SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
Prof. A. Syed Mustafa
HKBK COLLEGE OF ENGINEERING , Bengaluru-45
ANSWER TO MODEL QUESTION PAPER-
15PCD13- PROGRAMMING IN C AND
DATA STRUCTURE
PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13
HKBK College of Engineering, Bengaluru 1
PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13
HKBK College of Engineering, Bengaluru 2
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
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 specifiersMeaning
%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 %dn” , 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
.
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 trianglen");
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.2fn", 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
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:%dn",sizeof(x));
printf("Size of float variable y:%dn",sizeof(y));
printf("Size of double variable z:%dn",sizeof(z));
printf("Size of character variable char:%dn",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
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.
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.
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.
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).
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 = %ldn",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 numbern");
scanf("%d",&n);
do
{
f=f*n;
n--;
}while(n>0);
printf("factorial is=%dn",f);
getch();
}
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 %dn", 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 formatn");
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(“%fn”,res);
}
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
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:
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: %sn",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)
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
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("nn 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
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
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
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 matrixn");
scanf("%d%d",&m,&n);
printf("Enter the elements of matrixn");
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 %dn", 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.
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 ;
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.
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 );
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 %sn”,a);
}
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 Namen"); /* input details*/
gets(s1.Name);
printf("Enter the Student USNn");
scanf("%s",s1.USN);
printf("nEnter the Subject Namen");
gets(s1.Subname);
printf("Enter the Student IA markn");
scanf("%f", &s1.IA);
printf("Student Details aren"); /* display Details*/
printf("Student Name: %sn", s1.Name);
printf("Student USN: %sn", s1.USN);
printf("Subject Name: %sn", s1.Subname);
printf("IA Mark: %.2fn", s1.IA);
}
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
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 */
}
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
}
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.
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().
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(“%dt”,*(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.
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: %xn", &a );
/* address stored in pointer variable */
PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13
HKBK College of Engineering, Bengaluru 33
printf("Address stored in variable ip is: %xn", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %dn", *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 *******

Weitere ähnliche Inhalte

Was ist angesagt?

Looping statements in C
Looping statements in CLooping statements in C
Looping statements in CJeya Lakshmi
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c languagetanmaymodi4
 
Keywords, identifiers ,datatypes in C++
Keywords, identifiers ,datatypes in C++Keywords, identifiers ,datatypes in C++
Keywords, identifiers ,datatypes in C++Ankur Pandey
 
C programming decision making
C programming decision makingC programming decision making
C programming decision makingSENA
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programmingavikdhupar
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default argumentsNikhil Pandit
 
Chapter 2 : Balagurusamy_ Programming ANsI in C
Chapter 2 :  Balagurusamy_ Programming ANsI in CChapter 2 :  Balagurusamy_ Programming ANsI in C
Chapter 2 : Balagurusamy_ Programming ANsI in CBUBT
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1ReKruiTIn.com
 
Input output statement in C
Input output statement in CInput output statement in C
Input output statement in CMuthuganesh S
 

Was ist angesagt? (20)

Java notes
Java notesJava notes
Java notes
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in C
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
 
Keywords, identifiers ,datatypes in C++
Keywords, identifiers ,datatypes in C++Keywords, identifiers ,datatypes in C++
Keywords, identifiers ,datatypes in C++
 
C programming decision making
C programming decision makingC programming decision making
C programming decision making
 
C functions
C functionsC functions
C functions
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
Chapter 2 : Balagurusamy_ Programming ANsI in C
Chapter 2 :  Balagurusamy_ Programming ANsI in CChapter 2 :  Balagurusamy_ Programming ANsI in C
Chapter 2 : Balagurusamy_ Programming ANsI in C
 
C basics
C   basicsC   basics
C basics
 
C string
C stringC string
C string
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Input output statement in C
Input output statement in CInput output statement in C
Input output statement in C
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
 
Programming in c
Programming in cProgramming in c
Programming in c
 
C keywords and identifiers
C keywords and identifiersC keywords and identifiers
C keywords and identifiers
 

Andere mochten auch

VTU 1ST SEM PROGRAMMING IN C & DATA STRUCTURES SOLVED PAPERS OF JUNE-2015 & ...
VTU 1ST SEM  PROGRAMMING IN C & DATA STRUCTURES SOLVED PAPERS OF JUNE-2015 & ...VTU 1ST SEM  PROGRAMMING IN C & DATA STRUCTURES SOLVED PAPERS OF JUNE-2015 & ...
VTU 1ST SEM PROGRAMMING IN C & DATA STRUCTURES SOLVED PAPERS OF JUNE-2015 & ...vtunotesbysree
 
answer-model-qp-15-pcd13pcd
answer-model-qp-15-pcd13pcdanswer-model-qp-15-pcd13pcd
answer-model-qp-15-pcd13pcdSyed Mustafa
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGAbhishek Dwivedi
 
Grid computing notes
Grid computing notesGrid computing notes
Grid computing notesSyed Mustafa
 
Atmega lcd programing_with_header_file
Atmega lcd programing_with_header_fileAtmega lcd programing_with_header_file
Atmega lcd programing_with_header_fileABHISHEK MAURYA
 
NISM Currency Derivatives Model Question Paper
NISM Currency Derivatives Model Question PaperNISM Currency Derivatives Model Question Paper
NISM Currency Derivatives Model Question PaperSunil Yadav
 
Nism investment adviser level 1- model question paper
Nism investment adviser  level 1- model question paperNism investment adviser  level 1- model question paper
Nism investment adviser level 1- model question paperSunil Yadav
 
Introducing solved Question Papers of last 5 years for Anna University, 1st s...
Introducing solved Question Papers of last 5 years for Anna University, 1st s...Introducing solved Question Papers of last 5 years for Anna University, 1st s...
Introducing solved Question Papers of last 5 years for Anna University, 1st s...LearnEngg.com
 
VTU 8TH SEM CSE ADHOC NETWORKS SOLVED PAPERS OF JUNE-2014 DEC-14 & JUNE-2015
VTU 8TH SEM CSE ADHOC NETWORKS SOLVED PAPERS OF JUNE-2014 DEC-14 & JUNE-2015VTU 8TH SEM CSE ADHOC NETWORKS SOLVED PAPERS OF JUNE-2014 DEC-14 & JUNE-2015
VTU 8TH SEM CSE ADHOC NETWORKS SOLVED PAPERS OF JUNE-2014 DEC-14 & JUNE-2015vtunotesbysree
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Javaankitgarg_er
 
Steps for Developing a 'C' program
 Steps for Developing a 'C' program Steps for Developing a 'C' program
Steps for Developing a 'C' programSahithi Naraparaju
 

Andere mochten auch (20)

VTU 1ST SEM PROGRAMMING IN C & DATA STRUCTURES SOLVED PAPERS OF JUNE-2015 & ...
VTU 1ST SEM  PROGRAMMING IN C & DATA STRUCTURES SOLVED PAPERS OF JUNE-2015 & ...VTU 1ST SEM  PROGRAMMING IN C & DATA STRUCTURES SOLVED PAPERS OF JUNE-2015 & ...
VTU 1ST SEM PROGRAMMING IN C & DATA STRUCTURES SOLVED PAPERS OF JUNE-2015 & ...
 
1st Semester Chemistry Cycle (Dec-2015; Jan-2016) Question Papers
1st Semester Chemistry Cycle  (Dec-2015; Jan-2016) Question Papers1st Semester Chemistry Cycle  (Dec-2015; Jan-2016) Question Papers
1st Semester Chemistry Cycle (Dec-2015; Jan-2016) Question Papers
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
answer-model-qp-15-pcd13pcd
answer-model-qp-15-pcd13pcdanswer-model-qp-15-pcd13pcd
answer-model-qp-15-pcd13pcd
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
 
1st and 2nd sem VTU BE CBCS Scheme C sycle question papers june 2016
1st and 2nd sem VTU BE CBCS Scheme C sycle  question papers june 20161st and 2nd sem VTU BE CBCS Scheme C sycle  question papers june 2016
1st and 2nd sem VTU BE CBCS Scheme C sycle question papers june 2016
 
Grid computing notes
Grid computing notesGrid computing notes
Grid computing notes
 
1st semester chemistry stream (2013-June) Question Papers
1st semester chemistry  stream (2013-June) Question Papers 1st semester chemistry  stream (2013-June) Question Papers
1st semester chemistry stream (2013-June) Question Papers
 
Atmega lcd programing_with_header_file
Atmega lcd programing_with_header_fileAtmega lcd programing_with_header_file
Atmega lcd programing_with_header_file
 
1st and 2and Semester Chemistry Stream (2014-December; January) Question Papers
1st and 2and Semester Chemistry Stream (2014-December; January) Question Papers1st and 2and Semester Chemistry Stream (2014-December; January) Question Papers
1st and 2and Semester Chemistry Stream (2014-December; January) Question Papers
 
NISM Currency Derivatives Model Question Paper
NISM Currency Derivatives Model Question PaperNISM Currency Derivatives Model Question Paper
NISM Currency Derivatives Model Question Paper
 
C-Header file
C-Header fileC-Header file
C-Header file
 
Nism investment adviser level 1- model question paper
Nism investment adviser  level 1- model question paperNism investment adviser  level 1- model question paper
Nism investment adviser level 1- model question paper
 
7th semester VTU BE CS & IS question papers from 2010 to July 2016
7th semester VTU BE CS & IS question papers from 2010 to July 20167th semester VTU BE CS & IS question papers from 2010 to July 2016
7th semester VTU BE CS & IS question papers from 2010 to July 2016
 
1st semester chemistry stream (2015-June) Question Papers
1st semester chemistry stream (2015-June) Question Papers 1st semester chemistry stream (2015-June) Question Papers
1st semester chemistry stream (2015-June) Question Papers
 
Introducing solved Question Papers of last 5 years for Anna University, 1st s...
Introducing solved Question Papers of last 5 years for Anna University, 1st s...Introducing solved Question Papers of last 5 years for Anna University, 1st s...
Introducing solved Question Papers of last 5 years for Anna University, 1st s...
 
VTU 8TH SEM CSE ADHOC NETWORKS SOLVED PAPERS OF JUNE-2014 DEC-14 & JUNE-2015
VTU 8TH SEM CSE ADHOC NETWORKS SOLVED PAPERS OF JUNE-2014 DEC-14 & JUNE-2015VTU 8TH SEM CSE ADHOC NETWORKS SOLVED PAPERS OF JUNE-2014 DEC-14 & JUNE-2015
VTU 8TH SEM CSE ADHOC NETWORKS SOLVED PAPERS OF JUNE-2014 DEC-14 & JUNE-2015
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
4th semester Civil Engineering (2013-June) Question Papers
4th semester Civil Engineering (2013-June) Question Papers 4th semester Civil Engineering (2013-June) Question Papers
4th semester Civil Engineering (2013-June) Question Papers
 
Steps for Developing a 'C' program
 Steps for Developing a 'C' program Steps for Developing a 'C' program
Steps for Developing a 'C' program
 

Ähnlich wie VTU PCD Model Question Paper - Programming in C

Programming Fundamentals lecture 7
Programming Fundamentals lecture 7Programming Fundamentals lecture 7
Programming Fundamentals lecture 7REHAN IJAZ
 
C programming(Part 1)
C programming(Part 1)C programming(Part 1)
C programming(Part 1)SURBHI SAROHA
 
C Operators and Control Structures.pdf
C Operators and Control Structures.pdfC Operators and Control Structures.pdf
C Operators and Control Structures.pdfMaryJacob24
 
ppt on logical/arthimatical/conditional operators
ppt on logical/arthimatical/conditional operatorsppt on logical/arthimatical/conditional operators
ppt on logical/arthimatical/conditional operatorsAmrinder Sidhu
 
Expressions using operator in c
Expressions using operator in cExpressions using operator in c
Expressions using operator in cSaranya saran
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxKrishanPalSingh39
 
3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptx
3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptx3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptx
3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptxLeenaChaudhari24
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing TutorialMahira Banu
 
C programming session 02
C programming session 02C programming session 02
C programming session 02Dushmanta Nath
 
Kuliah komputer pemrograman
Kuliah  komputer pemrogramanKuliah  komputer pemrograman
Kuliah komputer pemrogramanhardryu
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programmingIcaii Infotech
 

Ähnlich wie VTU PCD Model Question Paper - Programming in C (20)

Programming Fundamentals lecture 7
Programming Fundamentals lecture 7Programming Fundamentals lecture 7
Programming Fundamentals lecture 7
 
C programming(Part 1)
C programming(Part 1)C programming(Part 1)
C programming(Part 1)
 
Presentation 2
Presentation 2Presentation 2
Presentation 2
 
C Operators and Control Structures.pdf
C Operators and Control Structures.pdfC Operators and Control Structures.pdf
C Operators and Control Structures.pdf
 
C programming
C programmingC programming
C programming
 
What is c
What is cWhat is c
What is c
 
C Programming
C ProgrammingC Programming
C Programming
 
ppt on logical/arthimatical/conditional operators
ppt on logical/arthimatical/conditional operatorsppt on logical/arthimatical/conditional operators
ppt on logical/arthimatical/conditional operators
 
Expressions using operator in c
Expressions using operator in cExpressions using operator in c
Expressions using operator in c
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
 
Ocs752 unit 1
Ocs752   unit 1Ocs752   unit 1
Ocs752 unit 1
 
3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptx
3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptx3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptx
3110003_PPS_GTU_Study_Material_Presentations_Unit-2_18122020041700AM (1).pptx
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing Tutorial
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
Kuliah komputer pemrograman
Kuliah  komputer pemrogramanKuliah  komputer pemrograman
Kuliah komputer pemrograman
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
 
Theory3
Theory3Theory3
Theory3
 
Unit 2
Unit 2Unit 2
Unit 2
 
Programming C Part 02
Programming C Part 02Programming C Part 02
Programming C Part 02
 
Unit 1
Unit 1Unit 1
Unit 1
 

Mehr von Syed Mustafa

BPOPS203 PRINCIPLES OF PROGRAMMING USING C LAB Manual.pdf
BPOPS203 PRINCIPLES OF PROGRAMMING USING C LAB Manual.pdfBPOPS203 PRINCIPLES OF PROGRAMMING USING C LAB Manual.pdf
BPOPS203 PRINCIPLES OF PROGRAMMING USING C LAB Manual.pdfSyed Mustafa
 
18CSL58 DBMS LAB Manual.pdf
18CSL58 DBMS LAB Manual.pdf18CSL58 DBMS LAB Manual.pdf
18CSL58 DBMS LAB Manual.pdfSyed Mustafa
 
Syed IoT - module 5
Syed  IoT - module 5Syed  IoT - module 5
Syed IoT - module 5Syed Mustafa
 
15CS81- IoT- VTU- module 3
15CS81- IoT- VTU- module 315CS81- IoT- VTU- module 3
15CS81- IoT- VTU- module 3Syed Mustafa
 
15CS81- IoT Module-2
15CS81- IoT Module-215CS81- IoT Module-2
15CS81- IoT Module-2Syed Mustafa
 
Internet of Things - module 1
Internet of Things -  module 1Internet of Things -  module 1
Internet of Things - module 1Syed Mustafa
 
15CS664- Python Application Programming- Question bank 1
15CS664- Python Application Programming- Question bank 115CS664- Python Application Programming- Question bank 1
15CS664- Python Application Programming- Question bank 1Syed Mustafa
 
15CS664- Python Application Programming VTU syllabus
15CS664- Python Application Programming  VTU syllabus15CS664- Python Application Programming  VTU syllabus
15CS664- Python Application Programming VTU syllabusSyed Mustafa
 
15CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 315CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 3Syed Mustafa
 
15CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 415CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 4Syed Mustafa
 
15CS664 Python Question Bank-3
15CS664 Python Question Bank-315CS664 Python Question Bank-3
15CS664 Python Question Bank-3Syed Mustafa
 
Data structures lab manual
Data structures lab manualData structures lab manual
Data structures lab manualSyed Mustafa
 
Unix system programming
Unix system programmingUnix system programming
Unix system programmingSyed Mustafa
 
Pointers and call by value, reference, address in C
Pointers and call by value, reference, address in CPointers and call by value, reference, address in C
Pointers and call by value, reference, address in CSyed Mustafa
 
Data structures lab c programs
Data structures lab  c programsData structures lab  c programs
Data structures lab c programsSyed Mustafa
 
Infix prefix postfix expression -conversion
Infix  prefix postfix expression -conversionInfix  prefix postfix expression -conversion
Infix prefix postfix expression -conversionSyed Mustafa
 
Service Oriented Architecture
Service Oriented ArchitectureService Oriented Architecture
Service Oriented ArchitectureSyed Mustafa
 
Data Structure with C -Part-2 ADT,Array, Strucure and Union
Data Structure with C -Part-2 ADT,Array, Strucure and  UnionData Structure with C -Part-2 ADT,Array, Strucure and  Union
Data Structure with C -Part-2 ADT,Array, Strucure and UnionSyed Mustafa
 

Mehr von Syed Mustafa (20)

BPOPS203 PRINCIPLES OF PROGRAMMING USING C LAB Manual.pdf
BPOPS203 PRINCIPLES OF PROGRAMMING USING C LAB Manual.pdfBPOPS203 PRINCIPLES OF PROGRAMMING USING C LAB Manual.pdf
BPOPS203 PRINCIPLES OF PROGRAMMING USING C LAB Manual.pdf
 
18CSL58 DBMS LAB Manual.pdf
18CSL58 DBMS LAB Manual.pdf18CSL58 DBMS LAB Manual.pdf
18CSL58 DBMS LAB Manual.pdf
 
Syed IoT - module 5
Syed  IoT - module 5Syed  IoT - module 5
Syed IoT - module 5
 
IoT - module 4
IoT - module 4IoT - module 4
IoT - module 4
 
15CS81- IoT- VTU- module 3
15CS81- IoT- VTU- module 315CS81- IoT- VTU- module 3
15CS81- IoT- VTU- module 3
 
15CS81- IoT Module-2
15CS81- IoT Module-215CS81- IoT Module-2
15CS81- IoT Module-2
 
Internet of Things - module 1
Internet of Things -  module 1Internet of Things -  module 1
Internet of Things - module 1
 
15CS664- Python Application Programming- Question bank 1
15CS664- Python Application Programming- Question bank 115CS664- Python Application Programming- Question bank 1
15CS664- Python Application Programming- Question bank 1
 
15CS664- Python Application Programming VTU syllabus
15CS664- Python Application Programming  VTU syllabus15CS664- Python Application Programming  VTU syllabus
15CS664- Python Application Programming VTU syllabus
 
15CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 315CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 3
 
15CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 415CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 4
 
15CS664 Python Question Bank-3
15CS664 Python Question Bank-315CS664 Python Question Bank-3
15CS664 Python Question Bank-3
 
Data structures lab manual
Data structures lab manualData structures lab manual
Data structures lab manual
 
Usp notes unit6-8
Usp notes unit6-8Usp notes unit6-8
Usp notes unit6-8
 
Unix system programming
Unix system programmingUnix system programming
Unix system programming
 
Pointers and call by value, reference, address in C
Pointers and call by value, reference, address in CPointers and call by value, reference, address in C
Pointers and call by value, reference, address in C
 
Data structures lab c programs
Data structures lab  c programsData structures lab  c programs
Data structures lab c programs
 
Infix prefix postfix expression -conversion
Infix  prefix postfix expression -conversionInfix  prefix postfix expression -conversion
Infix prefix postfix expression -conversion
 
Service Oriented Architecture
Service Oriented ArchitectureService Oriented Architecture
Service Oriented Architecture
 
Data Structure with C -Part-2 ADT,Array, Strucure and Union
Data Structure with C -Part-2 ADT,Array, Strucure and  UnionData Structure with C -Part-2 ADT,Array, Strucure and  Union
Data Structure with C -Part-2 ADT,Array, Strucure and Union
 

Kürzlich hochgeladen

Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 

Kürzlich hochgeladen (20)

Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 

VTU PCD Model Question Paper - Programming in C

  • 1. Prof. A. Syed Mustafa HKBK COLLEGE OF ENGINEERING , Bengaluru-45 ANSWER TO MODEL QUESTION PAPER- 15PCD13- PROGRAMMING IN C AND DATA STRUCTURE
  • 2. PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13 HKBK College of Engineering, Bengaluru 1
  • 3. PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13 HKBK College of Engineering, Bengaluru 2
  • 4. 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
  • 5. 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 specifiersMeaning %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 %dn” , 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 .
  • 6. 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 trianglen"); 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.2fn", 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
  • 7. 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:%dn",sizeof(x)); printf("Size of float variable y:%dn",sizeof(y)); printf("Size of double variable z:%dn",sizeof(z)); printf("Size of character variable char:%dn",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
  • 8. 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.
  • 9. 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.
  • 10. 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.
  • 11. 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).
  • 12. 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 = %ldn",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 numbern"); scanf("%d",&n); do { f=f*n; n--; }while(n>0); printf("factorial is=%dn",f); getch(); }
  • 13. 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 %dn", 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 formatn"); 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(“%fn”,res); }
  • 14. 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
  • 15. 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:
  • 16. 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: %sn",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)
  • 17. 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
  • 18. 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("nn 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
  • 19. 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
  • 20. 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
  • 21. 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 matrixn"); scanf("%d%d",&m,&n); printf("Enter the elements of matrixn"); 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 %dn", 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.
  • 22. 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 ;
  • 23. 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.
  • 24. 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 );
  • 25. 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 %sn”,a); }
  • 26. 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 Namen"); /* input details*/ gets(s1.Name); printf("Enter the Student USNn"); scanf("%s",s1.USN); printf("nEnter the Subject Namen"); gets(s1.Subname); printf("Enter the Student IA markn"); scanf("%f", &s1.IA); printf("Student Details aren"); /* display Details*/ printf("Student Name: %sn", s1.Name); printf("Student USN: %sn", s1.USN); printf("Subject Name: %sn", s1.Subname); printf("IA Mark: %.2fn", s1.IA); }
  • 27. 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
  • 28. 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 */ }
  • 29. 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 }
  • 30. 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.
  • 31. 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().
  • 32. 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(“%dt”,*(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.
  • 33. 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: %xn", &a ); /* address stored in pointer variable */
  • 34. PROF. A. SYED MUSTAFA ANSWER TO MODEL QUESTION PAPER- 15PCD13 HKBK College of Engineering, Bengaluru 33 printf("Address stored in variable ip is: %xn", ip ); /* access the value using the pointer */ printf("Value of *ip variable: %dn", *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 *******