Steps of Learning @ Temple of Knowledge

Click here to edit subtitle

CP  ASSIGNMENT QUESTIONS AND THEIR ANSWERS



ASSIGNMENT – I
1) Define Structure. Write a program to read details of student in a structure (rno,
name, 5 subject marks, avg) and obtain grade of student.
A structure is a collection of items which may be of different types referenced commonly
using one name. Each item in the structure is called as a member. A structure is also called
user-defined data type. When a structure is declared a new data type is created. You declare
a structure using keyword struct.

Program to read details of student in a structure (rno, name, 5 subject marks, avg) and
obtain grade of student.
#include <stdio.h>
struct student
{
int no;
char name[30];
int marks[5];
int avg;
};
main()
{
struct student s;
int i,j,sum=0;
printf("Enter student number : ");
scanf("%d", & s.no);
fflush(stdin);
printf("Enter student name
: ");
gets( s.name);
printf("Enter 5 subject marks
: ");
for(i=0;i<5;i++) {
scanf("%d",&s[i].marks);
sum = sum + s[i].marks;
}
s.avg=sum/5;
if(avg>=90 && avg<=100)
printf(“Grade is O”);
else
if(avg>=80 && avg<=89)
printf(“Grade is A”);
else
if(avg>=70 && avg<=79)
printf(“Grade is B”);
else
if(avg>=60 && avg<=69)
printf(“Grade is C”);
else
if(avg>=50 && avg<=59)
printf(“Grade is D”);
else
printf(“Student Failed!”);
}
/* end of main*/2) Explain Nested Structure or Structure within Structure with an example.
Structures can be used as structures within structures. It is also called as 'nesting of
structures'.
Syntax:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
}inner_struct_var;
}outer_struct_var;
Example :
struct stud_Res
{
int rno;
char nm[50];
char std[10];
struct stud_subj
{
char subjnm[30];
int marks;
}subj;
}result;
In above example, the structure stud_Res consists of stud_subj which itself is a structure
with two members. Structure stud_Res is called as 'outer structure' while stud_subj is called
as 'inner structure.' The members which are inside the inner structure can be accessed as
follow :
result.subj.subjnm
result.subj.marks
3) Define Pointer. Write a program to swap 2 numbers using pointers.
A pointer is a variable that contains an address which is a location of another variable in
memory. A pointer enables us to access a variable that is defined outside the function.
Pointers reduce the length and complexity of a program. They increase the execution speed.
Program to swap 2 numbers using pointers
main()
{
int a,b,*p,*q;p=&a;
q=&b;
scanf(“%d %d”,p,q);
*p = *p + *q;
*q = *p - *q;
*p = *p - *q;
printf(“Values After Swapping: %d %d”,a,b);
}
4) Write a program to check whether given string is palindrome or not using
pointers.
main()
{
char str[30];
char *p,*t;
printf("Enter any string : ");
gets(str);
for(p=str ; *p!=NULL ; p++);
for(t=str, p-- ; p>=t; ) {
if(*p==*t) {
p--; t++;
}
else break;
}
if(t>p)
printf("\nString is palindrome");
else
printf("\nString is Not palindrome");
getch();
}


5) Write a program to find trace and norm of a matrix.
#include<math.h>
main() {
int a[3][3],i,j,trace=0;
float sum = 0,s;
clrscr();
printf("Enter elements of matrix: ");
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
scanf("%d",&a[i][j]);
}
}
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
printf("%d\t",a[i][j]);
if(i==j) {
trace = trace + a[i][j];
sum = sum + pow(a[i][j],2);}
}
printf("\n");
}
s = sqrt(sum);
printf("Trace of the matrix: %d\n",trace);
printf("Norm of the matrix: %f",s);
getch();
}



ASSIGNMENT - II
1) What is a function? What is the difference between call by value and call by
reference?
Function: A function is a self-contained program segment that carries out a specific, well-
defined task. A function is a collection of instructions that performs a specific task.
Difference between Call by value and call by reference
Cal by Value
This is the usual method to call a function in
which only the value of the variable is passed
as an argument
Any alternation in the value of the argument
passed is local to the function and is not
accepted in the calling program
Memory location occupied by formal and
actual arguments is different
Since a new location is created, this method is
slow
There is no possibility of wrong data
manipulation since the arguments are directly
used in an application
Example:
main()
{
...
Swap(a,b);
...
}
Swap(int a,int b)
{
...
}
Call by Reference
In this method, the address of the variable is
passed as an argument
Any alternation in the value of the argument
passed is accepted in the calling
program(since alternation is made indirectly
in the memory location using the pointer)
Memory location occupied by formal and
actual arguments is same and there is a
saving of memory location
Since the existing memory location is used
through its address, this method is fast
There is a possibility of wrong data
manipulation since the addresses are used in
an expression. A good skill of programming
is required here
Example:
main()
{
...
Swap(&a,&b);
...
}
Swap(int *a,int *b)
{
...
}
2) Explain different types of parameters in C functions. Give the classification of
functions related to parameters.
A parameter or argument is a value passed to function so that function can use that value
while performing task. The types of parameters in C functions are:
Actual Parameter: It is the value that is passed to function while calling the function. For
example; 10 and 20 values that we passed to getaverage() function are actual parameters.
Example: getaverage(10,20);
Formal Parameter: Variable that is used to receive actual parameter is called formal
parameter.
Example: getaverage(int a, int b); Here a and b are formal parameters.
Classification of Functions
A function depending on whether arguments are present or not and whether a value is
returned or not may belong to one of the following categories:
1. Functions with no arguments and no return value.
2. Functions with arguments and no return value.
3. Functions with arguments and return value.
4. Functions with no arguments and return value.
Functions with no arguments and no return value
When a function has no argument, it does not receive any data from calling function. When
it does not return a value, the calling function does not receive any data from called
function. In effect, there is no data transfer between calling function & called function.
Program:
#include<stdio.h>
main() {
printf("Addition of 2 numbers:\n");
sum();
}
sum() {
int a,b;
printf("Enter 2 numbers: ");
scanf("%d %d",&a,&b);
printf("\nSum of %d and %d is %d",a,b,a+b);
}
Functions with no arguments and return value
When a function has no argument, it does not receive any data from calling function. When
it does return a value, the calling function receives data from called function. In effect, there
is data transfer between called function & calling function.
Program:
#include<stdio.h>
float average();
main() {
float avg;
printf("Average of 3 numbers:\n");
avg = average();printf("Average: %f",avg);
}
float average() {
int a,b,c,s;
printf("Enter 3 numbers: ");
scanf("%d %d %d",&a,&b,&c);
s=a+b+c;
return s/3.0;
}
Functions with arguments and no return value
When a function has argument(s), it does receive data from calling function. When it does
not return a value, the calling function receives does not data from called function. In effect,
there is data transfer between calling function & called function.
Program:
#include<stdio.h>
main() {
dline(15);
printf("\nFunctions...");
dline(15);
}
dline(int n) {
int l;
for(l=0;l<n;l++)
putch('-');
}
Functions with arguments and return value
When a function has an argument, it receives back any data from calling function. When it
returns a value, the calling function receives any data from called function. In effect, there is
a data transfer between the calling function & called function.
Program:
int getsum(int n);
main() {
int v,sum;
printf("Enter n value: ");
scanf("%d",&v);
sum = getsum(v);
printf("Sum=%d",sum);
}
int getsum(int n) {
int s=0;
for(;n>0;n--) s+=n;
return s;
}
3) Explain
a. Structure and functions
b. Structure and pointerStructure and function
Passing structure as argument to function: A structure can be passed to a function. To pass a
structure to a function you have to pass it just like how you would pass standard data types
like int and float.
Example: Program to illustrate the concept of passing structure to function.
struct point {
int x,y;
};
void display(struct point t);
main() {
struct point p;
printf("Read Coordinates of a point: ");
scanf("%d %d",&p.x,&p.y);
display(p);
}
void display(struct point t) {
printf("Coordinates of a point: x=%d, y=%d",t.x,t.y);
}
When you are sending a structure to a function, make sure that both calling function and
called function have access to structure. This can be done if you declare the structure at the
beginning of the program.
Structure and Pointer
Pointer to Structure: A pointer can also point to structure just like how it can point to a
standard data type. The process is similar to what we have already seen with standard data
types.
struct employee *p;
/*a pointer pointing to struct employee*/
Now p can be made to point to e1 (a variable of struct employee) as follows:
struct employee e1 = {1, "Srikanth","Vizag",65000};
p=&e1; /* make p point to e1 */
To access a member of a structure variable using a pointer to structure, use arrow operators .
Arrow operator is combination of hyphen and greater than symbol (->).
pointer-to-struct -> member
In order to use p, which is a pointer to struct, to access the data of e1, which is a struct
employee variable, use arrow operator as follows: printf("%d %f", p->eno, p->bs);
In fact you can also use * operator to access a member through pointer. The following is the
expression to access member x using pointer p. x = (*p).x;
Example: Program to illustrate pointer to structure variables concept.
main()
{
struct employee {
int eno;
char ename[20];
float bs;
};
struct employee e,*emp;
printf("Enter employee name: ");
gets(e.ename);printf("Enter employee number: ");
scanf("%d",&e.eno);
printf("Enter employee salary: ");
scanf("%f",&e.bs);
emp = &e;
printf("\nEmployee Details:\n");
printf("%d\t%s\t%0.2f",emp->eno,emp->ename,emp->bs);
}
4) What is a File? How is file created? Explain different file operations in C.
A file can be defined as a collection of bytes stored on the disk under a name. A file may
contain anything, in the sense the contents of files may be interpreted as a collection of
records or a collection of lines or a collection of instructions etc.
FILE is a data type which is a means to identify and specify which file you want to operate on
because you may open several files simultaneously.
When a request is made for a file to be opened, what is returned is a pointer to the structure
FILE. To store that pointer, a pointer variable is declared as follows:
FILE *file_pointer;
where file_pointer points to first character of the opened file.
File Operations in C:
1) Opening a file: A file needs to be opened when it is to be used for read/write
operation.
fopen(“filename”, “modes”);
2) Writing to file:
fputc() – Writes character to file
fputc(character,file_pointer);
fputw() – Writes integer to file
fputw(integer,file_pointer);
fputs() – Writes a string to file
fputs(string,file_pointer);
fprintf() – Writes different types of data into file
fprintf(file_pointer, control string, list of argument);
fwrite() – Writes a record/structure into binary file
fwrite(address, sizeof structure, no. of records, file_pointer);
3) Reading from file:
fgetc() – Reads character from file
fgetc(character,file_pointer);
fgetw() – Reads integer from file
fgetw(integer,file_pointer);
fgets() – Reads a string from file
fputs(string, size, file_pointer);
fscanf() – Reads different types of data from file
fprintf(file_pointer, control string, address of list of argument);
fread() – Reads a record/structure from binary file
fread(address, sizeof structure, no. of records, file_pointer);
4) Closing a file: The opened file should be closed to avoid pointer access errors in files.
fclose(file_pointer);5) Explain different Storage classes in C? Write a program to find number of
occurrences of a given character in a given string.
Types of Storage Classes
 auto
 register
 static
 extern
auto or Automatic Storage class
It is always implicitly associated with all local variables. The keyword used for this storage
class is auto. An auto variable is automatically created and initialized when control enters
into a block and removed when control comes out of block.
auto int i=30; /*an auto variable with local scope and extent*/
Storage Location: Main Memory
Default Value: Garbage
Scope: Local to the block in which variable is declared
Lifetime: till the control remains within the block.
Example: Program to illustrate how auto variables work.
main() {
auto int i=10;
clrscr();
{
auto int i=20; printf("%d",i);
}
printf("\t%d",i);
}
register or Register Storage class
We can tell the compiler that a variable should be kept in registers instead of keeping in the
memory (where normal variables are stored). Since a register access is much faster than a
memory access, keeping the frequently accessed variables (e.g. loop control variables) in
the registers will lead to faster execution of program.
r egister int i;
Storage Location: CPU registers
Default Value: Garbage
Scope: Local to the block in which variable is declared
Lifetime: till the control remains within the block.
Example:
main() {
register int i;
for(i=0;i<10000;i++)
. . . .
}
static or Static Storage Class
static is the default storage class for global variables. This is used to promote local extent of
a local variable to static extent. The value of static variables persists until the end of the
program. A variable can be declared static using the keyword static like
static float y;When you use static storage class while declaring local variable, instead of creating the
variable and initializing it whenever control enters the block, the variable is created and
initialized only for once - when variable's declaration is encountered for first time. So a
variable with static extent will remain in the memory across function calls.
Storage Location: Main Memory
Default Value: Zero
Scope: Local to the block in which variable is declared
Lifetime: till the value of the variable persists between different function calls.
Example: Program to illustrate the properties of a static variable.
main() {
int i;
for (i=0; i<3; i++)
incre();
}
incre() {
int avar=1; static int svar=1;
avar++; svar++;
printf("\n Automatic variable value : %d",avar);
printf("\t Static variable value : %d",svar);
}
extern or External Storage class:
extern is used to give a reference of a global variable that is visible to ALL the program files.
When you use 'extern' the variable cannot be initialized as all it does is point the variable
name at a storage location. External variable can be accessed by any function.
In case of large program, containing more than one file, if the global variable is declared in
file 1 and that variable is used in file 2 then, compiler will show error. To solve this problem,
keyword extern is used in file 2 to indicate that, the variable specified is global variable and
declared in another file.
/* File1.c */
extern int count; /* refers to an external variable count */
inccount() {
count++;
}
/* File2.c */
#include"File1.c"
int count; /* creates variable count with static extent */
main() {
. . .
}
In this case program File1.c has to access the variable defined in program File2.c.
Storage Location: Main Memory
Default Value: Zero
Scope: Global/File Scope
Lifetime: as long as the program execution doesn't come to an end.
P rogram to find number of occurrences of a given character in a given string.
main() {char st[20],ch;
int i,count=0;
clrscr();
gets(st);
ch = getchar();
for(i=0;st[i]!='\0';i++) {
if(st[i]==ch) count ++;
}
printf("Character %c count: %d",ch,count);
}
6) Differentiate between iteration and recursion. Write a program to generate n below
numbers using recursion.
Difference between Recursion and Iteration

Recursion
The process of calling a function itself
1
until a condition is met.
Recursion terminates when a base case
2
is recognized
Recursion is usually slower then
3
iteration
Recursion uses more memory than
4
iteration
5
Recursion makes code smaller
A conditional statement is required in
6
the body of the function for stopping
the function execution



Iteration
The process of repeating a section of
code until a condition is met.
Iteration terminates when the loop-
continuation condition fails
Iteration is faster than recursion
Iteration uses less memory
Iteration makes code longer
The iterative control statement itself
contains statement for stopping the
execution.



















Program to generate n below numbers using recursion
main()
{
int n;
printf("Enter n value: ");
scanf("%d",&n);
gennumbers(n);
}
gennumbers(int n) {
if(n==0)
exit(1);
printf("%d ",n);
gennumbers(n-1);
}