Question CS
Question CS
Question CS
FOR
2020-21
1
UNIT 1:
1. Explain in detail the structure of C Program and procedure to create, compile and run the C
program.
Answer:
Structure of C program
• Structure of C program is defined by set of rules called protocol, to be followed by programmer while
writing C program.
• All C programs are having sections/parts which are mentioned below.
S.No Sections Description
1 Documentation We can give comments about the program, creation or modified date,
section author name etc in this section
Single line comment - example : //sample program
Multiline comment - Example : /* comment line1 comment line2
comment3 */
2 Link Section Header files that are required to execute a C program are included in this
section
3 Definition Section In this section, variables are defined and values are set to these variables.
4 Global declaration Global variables are defined in this section. When a variable is to be used
section throughout the program, can be defined in this section.
5 Function Prototype Function prototype gives many information about a declaration section
function like return type, parameter names used
6 Main function Every C program is started from main function and this function contains
two major sections called declaration section and executable section.
7 User defined User can define their own functions in this section which perform
function section particular task as per the user requirement.
3
3. Develop Algorithm, Flowchart and program code for printing prime number?
Answer:
Algorithm:
step 1: Start
Step 2: Initialize variables num,flag=1, i=2
Step 3: Read num from user
Step 4: If num<=1
Display "num is not a prime number"
Goto step 7
Step 5: Repeat the steps until i<[(n/2)+1]
5.1 If remainder of number divide i equals to 0,
Set flag=0
Goto step 6
5.2 i=i+1
Step 6: If flag==0,
Display “ prime number"
Else
Display “not prime number"
Step 7: Stop
Program:
#include <stdio.h>
int main()
{
int n, i, flag = 1;
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}
4
Output:
5
5. what is an opertor? Explain relational operator with example?
Answer:
The symbols which are used to perform logical and mathematical operations in a C program are called C
operators.
These C operators join individual constants and variables to form expressions.
Operators, functions, constants and variables are combined together to form expressions
Relational operators:
• Relational operators in c programming is used for specifying the relation between two operands such as
greater than, less than and equals.
• Relational operators are used to compare, logical, arithmetic and character expression and each relational
operator takes two operands.
• Each operator compares their left side with their right side. It evaluates to 0 if the condition is false and 1
if it is true
UNIT 2:
1.What is an array ? Different ways for initialising 1D array?
Answer:
An array is collection of items or elements stored at continuous memory locations.
Declaration:
datatype arrayname[maxsize];
Declaration and Initialization:
Storage class datatype arrayname[size] = {List of Value};
Different ways for initialising 1D array:
1. int arr[10]; // declaration for one dimensional array
6
2. int arr[] = {10, 20, 30, 40} // declaration and initialization above is same as
int arr[4] = {10, 20, 30, 40}
3. int arr[6] = {10, 20, 30, 40} above is same as
int arr[] = {10, 20, 30, 40, 0, 0}”
Memory Address of an array Elements are accessed by specifying the index ( offset ) of the desired element
within square [ ] brackets after the array name.
2. List and explain any five string handling functions with examples.
Answer:
1 strcpy(s1, s2); Copies string s2 into string s1.
2 strcat(s1, s2); Concatenates string s2 onto the end of string s1.
3 strlen(s1); Returns the length of string s1.
4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s13.
5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
Program:
#include<stdio.h>
#include <string.h>
int main ()
{
char str1[12] = “Hello”;
char str2[12] = “World”;
char str3[12];
int len ;
strcpy(str3, str1);
printf(“strcpy( str3, str1) : %s\n”, str3 );
strcat( str1, str2);
printf(“strcat( str1, str2): %s\n”, str1 );
len = strlen(str1);
printf(“strlen(str1) : %d\n”, len );
return 0;
}
Output :
7
strcpy( str3, str1) : Hello
strcat( str1, str2) : HelloWorld
strlen(str1) : 10
4. Define a structure for Student with Sno, Sname, marks of three subjects ,avg.
Write a C program to read 4 students information calculate average and display 4 students
information.
Answer:
PROGRAM:
#include<stdio.h>
struct student
{
int sno;
char sname[20];
int mark[3];
float avg;
};
8
int main()
{
struct student s[4];
int i , j, sum=0;
for(i=0;i<4;i++)
{
sum=0;
printf(“ enter student %d details\n”,i+1);
printf(“sno, sname\n”);
scanf(“%d%s”, &s[i].sno, s[i].sname);
printf(“enter 3 subject marks\n”);
for(j=0;j<3;j++)
{
scanf (“%d”,&s[i].mark[j];
sum=sum+ s[i].mark[j];
}
s[i].avg=sum/3.0;
}
Printf(“Student details are”);
for(i=0;i<4;i++)
{
printf(“%d student : ”,i+1);
printf(“%d student sno: %d\n”,s[i].sno);
printf(“%d student name: %s\n”,s[i].sname);
printf(“%d student pecentage: %f\n”,s[i].avg);
}
return 0;
}
UNIT 3:
1. Explain different preprocessor directives in C?
Answer:
Program:
#include <stdio.h>
#define PI 3.1415
#define circleArea(r) (PI*r*r)
int main()
{
float radius, area,area1;
printf("Enter the radius: ");
scanf("%f", &radius);
area = PI*radius*radius;
printf("Area=%.2f",area);
area1 = circleArea(radius);
printf("Area = %.2f", area1);
printf("Current time: %s",--TIME--);
return 0;
10
}
OUTPUT:
Enter the radius: 5
Area=78.54
Area1 = 78.54
Current time: 07:19:33
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any simple text editors.
When you open those files, you'll see all the contents within the file as plain text. You can easily edit or
delete the contents.
They take minimum effort to maintain, are easily readable, and provide least security and takes bigger
storage space.
2. Binary files
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better security than text files.
11
Opening a File or Creating a File:
The fopen() function is used to create a new file or to open an existing file. this function available in stdio.h
file
Syntax:
Function Description
4. Write a C program to merge two files into a third file (i.e., the contents of the first file followed by
those of the second are put in the third file).
Answer:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fs1, *fs2, *ft;
char ch;
fs1 = fopen(“file1.txt”,"r");
fs2 = fopen(“file2.txt”,"r");
ft = fopen(“file3.txt”,"w");
if( fs1 == NULL || fs2 == NULL || ft == NULL )
12
{
printf("Press any key to exit...\n");
exit(0);
}
INPUT:
Source file : file1.txt : ABC
file2.txt : XYZPQR
file3.txt : ABC XYZPQR
OUTPUT: Two files were merged into third file successfully
5. what are different file positioning function available in c. ( fseek, rwind ftell)
Answer:
There is no need to read each record sequentially, if we want to access a particular record. C supports these
functions for random access file processing.
1. fseek()
2. ftell()
3. rewind()
fseek():
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: fseek( file_pointer, displacement, pointer position);
OR
int fseek ( FILE *fp, long num_bytes, int origin ) ;
Where
file_pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or negative.
This is the number of bytes which are skipped backward (if negative) or forward ( if positive) from the current
position.
Pointer position:
13
This sets the pointer position in the file.
0 Beginning of file.
1 Current position
2 End of file
Example:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file, from this statement pointer position is skipped 10
bytes from the beginning of the file.
2) fseek( p,5L,1)
1 means current position of the pointer position. From this statement pointer position is skipped 5 bytes
forward from the current position.
3)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes backward from the current position.
ftell():
This function returns the value of the current pointer position in the file. The value is count from the beginning
of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.
rewind():
This function is used to move the file pointer to the beginning of the given file.
Syntax: rewind( fptr);
Where fptr is a file pointer.
Answer:
#include
void main(){
FILE *fp;
int i;
fp = fopen("file1.txt","r");
for (i=1;i<5;i++){
printf("%c : %d\n",getc(fp),ftell(fp));
fseek(fp,ftell(fp),0);
14
if (i == 5)
rewind(fp);
}
fclose(fp);
}
UNIT 4:
15
Example: Program to Print a sentence using function.
#include <stdio.h>
void display(); //function declaration
void main() void display() //function definition
{ {
display(); //function call printf(“C Programming”);
} }
Output: C Programming
2. Compare parameter passing techniques of Call by Value and Call by reference with an examples.
Answer:
Call by Value : In this type, value of actual arguments are passed to the formal arguments and the operation
is done on the formal arguments. Any changes made in the formal arguments does not affect the actual
arguments because formal arguments are photocopy of actual arguments. Changes made in the formal
arguments are local to the block of calledfunction. Once control returns back to the calling-function the
changes made vanish.
Example: Program to send values using call-by-value method.
#include <stdio.h>
Void swap(int a, int b);
void main()
{
int x,y;
printf(“enter values of x & y : “); void swap(int a, int b)
scanf(“%d %d “, &x, &y); {
printf(“\n old values x=%d y =%d”, x, y); int t=a;
swap(x,y) ; a=b;
printf(“\n new values x=%d y =%d”, x, y); b=t;
} }
Output:
enter values of x & y : 2 3
old values x=2 y =3
new values x=2 y =3
16
Call by reference: The Address of actual parameters are copied to formal parameters. Here changing the
formal parameters indirectly affects the actual parameters.
Example: Program to send values using call-by-reference method.
#include <stdio.h>
Void swap(int *a, int *b);
void main()
{
int x,y;
printf(“enter values of x & y : “); void swap(int *a, int *b)
scanf(“%d %d “, &x, &y); {
printf(“\n old values x=%d y =%d”, x, y); int t=*a;
swap( &x, &y) ; *a=*b;
printf(“\n new values x=%d y =%d”, x, y); *b=t;
} }
Output:
enter values of x & y : 2 3
old values x=2 y =3
new values x=3 y =2
3. List and brief the uses of Dynamic Memory Allocation Functions. Write a C program to allocate a
block of memory using malloc()?
Answer:
Dynamic Memory Allocation Functions:
malloc() Allocates the memory of requested size and ptr =(data_type *) alloc(byte_size);
returns the pointer to the first byte of allocated Example: ptr = (int *) malloc (50)
space.
calloc() Allocates the space for elements of an array. ptr= (data_type *) calloc (n, size);
Initializes the elements to zero and returns a Example:
pointer to the memory. ptr =(int *)calloc(10, sizeof(int));
17
Free() Frees or empties the previously allocated Free(ptr);
memory space.
Advantages:
Data structures can grow and shrink according to the requirement. (less memory wastage)
We can allocate (create) additional storage whenever we need them.
We can de-allocate (free/delete) dynamic space whenever we are done with them.
Dynamic Allocation is done at run time.
#include <stdio.h>
int main()
{
int* ptr = malloc(10 * sizeof(*ptr));
if (ptr != NULL){
*(ptr + 2) = 50;
printf("Value of the 2nd integer is %d",*(ptr + 2));
}
free(ptr);
}
Output
18
else return n* rec_fact(n-1);
for(i=1;i<=n;i++) }
f=f*i;
return(f);
}
Output:
enter the number : 5
factoria of number using function: 120
factoria of number using recursion: 120
UNIT 5:
1.Build Linear Search on list of elements 20, 12, 17, 28, 70, 80 and key element is 70.
Write the algorithm, draw the flowchart along with the program.
Answer:
Algorithm:
1. variables needed: array[100], key, i, n, found=0
2. read n value
3. enter n elements into array
4. read the value for search key.
5. for (i = 0 ;i < n ; i++ )
{
if (a[i] == key)
{
found=1; break;
}
}
6. if found = = 1,
6.1 Display message “Search is successful and item is found at location: loc”
7. else
7.1 Display the message “Search Unsuccessful” and exit.
8. stop
Flowchart:
19
Program:
#include <stdio.h>
int main()
{
int array[100], key, i, n, found=0;
return 0;
20
}
Output:
Enter the number of elements in array
5
Enter 5 numbers
2
6
18
25
1
Enter the number to search
25
25 is present at location 4.
Program:
#include<stdio.h>
void main()
{
int a[50],n,i,j,temp;
printf("Enter the size of array: ");
scanf("%d",&n);
printf("Enter the array elements: ");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
for(i=1;i<n;++i)
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
printf("Array after sorting: ");
for(i=0;i<n;++i)
21
printf("%d ",a[i]);
OUTPUT:
Enter total elements: 5
Enter 5 elements: 45 67 32 68 20
The array after sorting is: 20 32 45 67 68.
22