Assign 3 Full

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

Name:Arindom Borkakoti

Reg No: 14-1-2-090


Branch:Mechanical Engineering
Section:D

CS ASSIGNMENT-3

pointers
Q-1: Define pointers and declaration syntax of pointers with examples.

Ans: A pointer is a variable whose value is the address of another variable, i.e., direct address of
the memory location. Like any variable or constant, we must declare a pointer before we can
use it to store any variable address.

The general form of a pointer variable declaration is:


datatype *pointer_name;

For example:
int *ptra;
char *ptrb;
float *ptrc;

Q-2: Explain the difference between null pointer and void pointer.

Ans: Null pointer is a special reserved value of a pointer. A pointer of any type has such a reserved
value. Formally, each specific pointer type (int *, char * etc.) has its own dedicated null-
pointer value. Conceptually, when a pointer has that null value it is not pointing anywhere.

On the other hand, void pointer is a specific pointer type - void * - a pointer that points to
some data location in storage, which doesn't have any specific type.

Q-3: What is an array of pointers? How is it different from pointer to an array?

Ans: In array of pointers, each element of the array is an address to memory location which holds
the data.

For example:
int *ptr[100];

This is an array of pointers and will declare 100 pointers.

On the other hand, pointer to an array is a pointer which points to the address of any element
of a pre-declared array (generally the base element).

For example:
int A[3]={28,7,32};
int *ptr;
*ptr=A;

This pointer is pointing to the address of the base element of the array A i.e. A[0].

Q-4: Explain the advantages and disadvantages of pointers.

Ans: Advantages of pointers are:

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. Addresses of objects can be extracted using pointers.

Disadvantages of pointers are:

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.

Q-5: Explain the term dynamic memory allocation. Also differentiate between malloc(),
calloc() and realloc() with a program as an example.

Ans: The process of allocating memory during program execution is called dynamic memory
allocation. That is, the memory which is allocated during run-time is called dynamic memory
allocation.

C language offers 4 dynamic memory allocation functions. They are:


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

The differences between malloc(), calloc() and realloc() are:

1. malloc() function:

malloc() function is used to allocate space in memory during the execution of the program.
malloc() does not initialize the memory allocated during execution. It carries garbage value.
malloc() function returns null pointer if it couldnt able to allocate requested amount of
memory.

For example:
int *ptr;
ptr=(int*)malloc(20*sizeof(int));
For the above, 20*4 bytes of memory only allocated in one block.
Total = 80 bytes.

2. calloc() function:

calloc() function is also like malloc() function. But calloc() initializes the allocated memory
to zero. But, malloc() doesnt.

For example:
int *ptr;
ptr=(int*)calloc( 20,sizeof(int));

For the above, 20 blocks of memory will be created and each contains 20*4 bytes of
memory. Total = 1600 bytes

3. realloc() function:

realloc() function modifies the allocated memory size by malloc() and calloc() functions to
new size. If enough space doesnt exist in memory of current block to extend, new block is
allocated for the full size of reallocation, then the existing data is copied to new block and
then the old block is free.

Example of a program using these functions:

#include<stdio.h>
#include<string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation=malloc(20*sizeof(char));
if(mem_allocation==NULL)
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"How are you?");
}
printf("Dynamically allocated memory content: %s\n",mem_allocation);
mem_allocation=realloc(mem_allocation,100*sizeof(char));
if(mem_allocation==NULL)
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy(mem_allocation,"Space is extended upto 100 characters");
}
printf("Resized memory: %s\n",mem_allocation);
free(mem_allocation);
}
Q-6: Differentiate between pointers to constant and constant to pointers.

Ans: Constant pointers:

These type of pointers are the one which cannot change address they are pointing to. This
means that suppose there is a pointer which points to a variable (or stores the address of that
variable). Now if we try to point the pointer to some other variable (or try to make the pointer
store address of some other variable), then constant pointers are incapable of this.

A constant pointer is declared as 'int *constptr'.

Pointer to constant:

These type of pointers are the one which cannot change the value they are pointing to. This
means they cannot change the value of the variable whose address they are holding.

A pointer to a constant is declared as 'const int *ptr'.

Pointer to constant Constant pointers

*ptr=20 statement is invalid in pointer to *ptr=20 is absolutely valid in constant pointers


constant i.e. assigning value is illegal i.e. assigning value is perfectly legal

ptr++ statement is valid in pointer to constant ptr++ statement is invalid in constant pointers
Pointer can be incremented and decremented Pointer cannot be incremented and decremented
Pointer is pointing to constant data object Constant pointer is pointing to data objects
Declaration: const int *ptr; Declaration: int *constptr;

Q-7: Differentiate between ptr++ and *ptr++.

Ans: The ++ operator adds the sizeof(datatype) number of bytes to the pointer so that it to the next
entry of the datatype.

For example:
int *ptr;
ptr++;

This adds 2 or 4 bytes (depends upon compiler) to the pointer so that it points to the next
entry of the datatype.
On the other hand, *ptr++ increments the value of the variable which the pointer is pointing
to by 1.

For example:
int a=10;
int *ptr;
ptr=&a;
*ptr++;

This adds 1 to the value of a i.e. a becomes equal to 11.

Q-8: How can we have array of function pointers? Illustrate with examples.
Ans: Arrays follow the normal C syntax of putting the brackets near the variable's identifier, so:
int (*ptr_array[4])( int ) declares a variable called ptr array which is an array of 4 function
pointers.

For example:

#include<stdio.h>

int display();
int(*arr[4])();
int(*(*ptr)[4])();

int main()
{
arr[0]=display();
arr[1]=getch();
ptr=&arr;

printf("%d",(**ptr)());

(*(*ptr+1))();
return 0;
}

int display()
{
int num = 100;
return num;
}

100

Output: 25

Step 1: Array of Function

int(*arr[4])();

Above statement tells that:

arr is an array of size 4.


Array stores address of functions.
Array stores address of function having integer as return type and does not takes any
parameter.

Step 2: Declaring array of function pointer

int(*(*ptr)[4])();

It is array of function pointer which points to "array of function".

Step 3: Store function names inside function array


arr[0]=display();
arr[1]=getch();

Step 4: Store address of function array to function pointer

ptr=&arr;

Step 5: Calling function

Following syntax is used to call display function:

(**ptr)();

This syntax is used to call getch function:

(*(*ptr+1))();

Q-9: What is memory leakage problem? Explain with example.

Ans: A memory leak is memory which hasn't been freed, there is no way to access (or free it) now,
as there are no ways to get to it anymore. (For example: a pointer which was the only
reference to a memory location dynamically allocated (and not freed) which points
somewhere else now.

For example:

void func()
{
char *ch;
ch=(char*)malloc(10);
}

char *ch is a local variable that goes out of scope at the end of the function, leaking the
dynamically allocated 10 bytes.

This problem can be overcome by using the free() function as free(ch);

Q-10: What is dangling pointer.? Explain with an example.

Ans: Dangling pointers are pointers that do not point to a valid object of the appropriate type.
In many applications memory is allocated for holding data objects. After using these objects,
the application will de-allocate this memory so that the memory can be re-used. In some cases
the allocations may use a pointer to an object whose memory is already de-allocated. This
may lead to application crash or an unpredictable behaviour.

Scenarios which leads to dangling pointer:

Application makes use of an object after it has been released, and there by access to an invalid
memory location.

A function returns a pointer to one of its local variables, and sifnce this local variable is
defined only for the function, the pointer becomes invalid once the function ends.
The most common result of this bug is the crash of the application or its running thread.

For example:

#include<stdio.h>
main()
{
int *p;
p=increment(1);
printf(%d,*p);
}
int *increment(int n)
{
int *ptr=&temp;
temp=n+1;
return ptr;
}

The function returns the address of temp, but temp is erased as soon as increment(n) returns.
So the returned value is not a meaningful address to the calling function. The problem is that
anything allocated for the called function on stack is erased as soon as it returns. This is a
dangling pointer problem.

Q-11: Differentiate between *(arr+i) and (arr+i).

Ans: If arr is the name of an array, it acts as a pointer constant to the first element of the array.
Then, *(arr+i) returns the value (i.e. the content) of the (i+1)th element of the array.

Whereas, (arr+i) returns the address of the (i+1)th element of the array.

Q-12: Find Output:


main()
{
int x=3;
int *a=&x,*b=&a;
int **c=&b;
printf(%d%d%d,*a,*b,**c);
}

Ans: 3(address of x)(address of x)

Q-13: What is the output of the following program?


main()
{
int a[4]={57,32,79,87};
int *x=a;
printf(%d %d %d, *x,*x+2,*(x+2));
}

Ans: 57 59 79

Q-14: Write a program to print alternate letters of a string (Example: NITSilchar will
produce: NTica).

Ans: #include<stdio.h>
#include<string.h>
main()
{
int i,l=0;
char str[100];
printf("Enter a string (max 100 characters): ");
gets(str);
for(i=0;str[i]!='\0';i++)
l++;
for(i=0;i<l;i+=2)
printf("%c",str[i]);
}

Q-15: Write a program to obtain the number of elements from the user, store it dynamically in
memory and find out the smallest element in the list.

Ans: #include<stdio.h>
#include<stdlib.h>
main()
{
int *a,n,i,small;
printf("Enter the number of elements in the array: ");
scanf("%d",&n);
printf("Enter %d elements:\n",n);
a=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
scanf("%d",&a[i]);
small=a[0];
for(i=0;i<n;i++)
{
if(small>a[i])
small=a[i];
}
printf("The smallest element is: %d\n",small);
}

Q-16: Write a program to store addresses of array elements in another array.

Ans: #include<stdio.h>
main()
{
int a[10],*add[10],i;
printf("Enter 10 elements of array:\n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("\nThe details of the array are:\n\nName\t\tAddress\t\tContent\n\n");
for(i=0;i<10;i++)
{
add[i]=&a[i];
printf("a[%d]\t\t%d\t\t%d\n",i,add[i],*add[i]);
}
}

Q-17: Write a program to demonstrate working of calloc().


Ans: #include<stdio.h>
#include<stdlib.h>
main()
{
int n,*a,i;
printf("Enter the size of array: ");
scanf("%d",&n);
a=(int*)calloc(n,sizeof(int));
printf("Enter the first element only: ");
scanf("%d",&a[0]);
for(i=0;i<n;i++)
printf("a[%d]=%d\n",i,a[i]);
printf("\n\nAll uninitialised array elements take 0 as the default value\n");
}

Q-18: Write a program to reverse a string using pointers.

Ans: #include<stdio.h>
main()
{
int i,l=0;
char str[50],*ptr;
printf("Enter a string (max 50 characters): ");
gets(str);
for(i=0;*(str+i)!='\0';i++)
l++;
ptr=str+(l-1);
printf("\nThe reversed string using pointer is:\n\n");
for(i=0;i<l;i++)
printf("%c",*(ptr-i));
}

Q-19: Write a program to implement call by reference using functions to swap two integer
numbers.

Ans: #include<stdio.h>
main()
{
int a,b;
printf("Enter two numbers a and b: ");
scanf("%d%d",&a,&b);
printf("\nBefore function call:\na=%d\tb=%d\n",a,b);
swap(&a,&b);
printf("\nAfter function call:\na=%d\tb=%d\n",a,b);
}
void swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}

Q-20: Write a program to copy a string using pointers and not using strcpy function.
Ans: #include<stdio.h>
main()
{
int i=0,l=0;
char *str1[50],*str2[50];
printf("Enter a string (max 50 characters): ");
gets(str1);
for(i=0;*(str1+i)!='\0';i++)
l++;
for(i=0;i<l;i++)
*(str2+i)=*(str1+i);
printf("\nThe copied string is: ");
puts(str2);
}

Q-21: Write a program for addition of a matrix using pointers.

Ans: #include <stdio.h>


main()
{
int *a1=0,*a2=0,*a3,i,j;
int row,col;
int * add(int *a1,int *a2,introw,int col);
row=col=3;
printf("\nEnter value for the first array: ");
m1=(int*)malloc(sizeof(int)*row*col);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf("%d",a1+i*col+j);
}
}
printf("\nenter value for the second array: ");
a2=(int*) malloc(sizeof(int)*row*col);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf("%d",m2+i*col+j);
}
}
a3=(int*)malloc(sizeof(int)*row*col);
a3=add(a1,a2,row,col);
printf("The result is: \n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d ",*(a3+i*col+j));
}
printf("\n");
}
}
int * add(int *a1,int *a2,introw,int col)
{
int *a3=(int*)malloc(sizeof(int)*row*col);
int i,j,k,b1;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
a1=*(a1+i*col+j)+*(a2+i*col+j);
*(a3+i*col+j)=b1;
}
}
return a3;
}

Q-22: Write a program to read and print a floating point array. The space for the array
should be allocated at the run time.

Ans: #include<stdio.h>
#include<stdlib.h>
main()
{
float *a;
int i,n;
printf("Enter the size of array: ");
scanf("%d",&n);
a=(void*)malloc(n*(sizeof(float)));
printf("Enter %d floating point numbers: ",n);
for(i=0;i<n;i++)
scanf("%f",&a[i]);
for(i=0;i<n;i++)
printf("\na[%d]=%f\tAddress of a[%d]=%d",i,a[i],i,&a[i]);
}

Q-23: Write a program to print HELLO WORLD using pointers.

Ans: #include<stdio.h>
main()
{
char let[12]="HELLO WORLD";
int i;
char *ptr[12];
for(i=0;i<11;i++)
{
ptr[i]=&let[i];
printf("%c",*ptr[i]);
}
}

Q-24: Write a program to subtract two integer values using pointers.

Ans: #include <stdio.h>


main()
{
int first, second, *p, *q, sub;
printf("Enter two integers to substract\n");
scanf("%d%d", &first, &second);
p=&first;
q=&second;
sub=*p-*q;
printf("Difference between the entered numbers = %d\n",sub);
}

Q-25: Write a program to find smallest of three integers values using pointer.

Ans: #include<stdio.h>
main ()
{
int *ptr1,*ptr2,*ptr3,a,b,c,max=0;
printf("Enter 3 numbers: ");
scanf("%d%d%d",&a,&b,&c);
ptr1=&a;
ptr2=&b;
ptr3=&c;
if(*ptr1>*ptr2)
{
if(*ptr1>*ptr3)
max=*ptr1;
else
max=*ptr3;
}
else
{
if(*ptr2>*ptr3)
max=*ptr2;
else
max=*ptr3;
}
printf("The maximum of the three numbers is %d",max);
}

structure
Q-1: Define a structure. Mention its advantages and disadvantages.

Ans: A structure is a complex data type declaration that defines a physically grouped list of
variables to be placed under one name in a block of memory, allowing the different variables
to be accessed via a single pointer, or the struct declared name which returns the same
address. The struct can contain many other complex and simple data types in an association.
Structures are used to group together different types of variables under the same name.

The general syntax for a struct declaration is:

structtag_name
{
type member1;
type member2;
/* declare as many members as desired, but the entire structure size must be known to
the compiler. */
};

For example, telephone, which is made up of a string (that is used to hold the name of the
person) and an integer (that is used to hold the telephone number).

struct telephone
{
char name[20];
int number;
};
Advantage :
1) You can implement all the OOPS concepts like Emulating classes, inheritance, and
polymorphism in C.
2) I believe that besides being useful in its own right, implementing OOP in C is an
excellent way to learnOOP and understand its inner workings. Experience of many
programmers has shown that to use a technique efficiently and confidently, a programmer
must understand how the underlying concepts are ultimately implemented.

Disadvantage:
1) As C does not provide the facilities of OOPS therefore you have to implement the
OOPS feature that can take some time and will be complex initially. This can be a
problem if you want to finish the project very soon. (Though i don't consider this as a
disadvantage as amount of learning in the process is huge.)

Q-2: Can a structure variable be defined as a member of another structure?

Ans: Yes, a structure variable can be defined as a member of another structure. Structure within a
structure means nesting of structures.

The following example will help in understanding it:

struct student
{
char name[50];
char department[50];
struct
{
int jee marks;
int roll no;
}cpi;
}player;
Here the structure student contains a member named cpi, which is itself a variable of a
structure.

Q-3: Can an array be included as a member of a structure? Can an array have structures as
elements?

Ans: Yes, an array can be included as a member of a structure. C permits the use of arrays as
structure members. We can use single dimensional or multi-dimensional arrays as structure
members.

For example:
struct marks
{
int number;
float subject[3];
}student[2];

Here, the member subject contains three elements subject[0],subject[1],subject[2].

Yes, an array can have structures as elements. It is possible to define an array of structures i.e.
an array in which each element is a structure.

For example:

struct book
{
char bname[20];
int pages;
char author[20];
float price;
}b1[2]={{"DA VINCI CODE",1000,"DAN BROWN",580.00},{"Immortals of
meluha",800,"Amish Tripathi",250.00}};

Explanation :

As soon as after declaration of structure we initialize structure with the pre-defined values.
For each structure variable we specify set of values in curly braces. Suppose we have 2 array
elements then we have to initialize each array element individually and all individual sets are
combined to form single set.

Q-4: What is the precedence of the period (.)operator? What is its associativity?

Ans: In precedence order, it is a third position. It is preceded by () operator (function call) and []
operator (array subscript).

The associativity of dot operator is from left to right.

Q-5: How can the size of a structure be determined? In what units is the size reported?

Ans: The size of a structure can be determined using the unary operator sizeof.

The expression sizeof(struct x); will evaluate the number of bytes required to hold all the
members of the structure x.

The sizeof operator returns the number of bytes the operand occupies. It returns only an
integer, no unit.

Q-6: What is the precedence of the -> operator? What is its associativity?

Ans: The -> operator (member selection via pointer operator) is at the fourth position in the
precedence order list, preceded by the ( ), [ ] and . operators.

Its associativity is from left to right.

Q-7: Suppose a pointer variable points to a structure that contains another structure as a
member. How can a member of the embedded structure be accessed?
Ans: The member of the embedded structure can be accessed in the following way by using the
arrow operator ->.

#include<stdio.h>
struct data1
{
int a;
int b;
};
struct data2
{
struct data1 x;
int c;
};
main()
{
struct data2 *ptr;
ptr=(struct data2*)malloc(sizeof(struct data2));
printf("Enter the values of a,b and c: ");
scanf("%d%d%d",&ptr->x.a,&ptr->x.b,&ptr->c);
printf("\na=%d\tb=%d\tc=%d\n",ptr->x.a,ptr->x.b,ptr->c);
}

Q-8: Suppose a pointer variable points to a structure that contains an array as a member.
How can an element of the embedded array be accessed?

Ans: The elements of an embedded array can be accessed by using the arrow operator -> and for
loop.

The following program demonstrates this:


#include<stdio.h>
struct data
{
int a[3];
int b[3];
};
main()
{
struct data *ptr;
int i;
ptr=(struct data*)malloc(sizeof(struct data));
printf("Enter the 1st elements of a and b each, then 2nd and 3rd respectively: ");
for(i=0;i<3;i++)
scanf("%d%d",&ptr->a[i],&ptr->b[i]);
for(i=0;i<3;i++)
printf("\na=%d\tb=%d\n",ptr->a[i],ptr->b[i]);
}

Q-9: In what sense can unions, structures and arrays be intermixed?

Ans: An union may be a member of a structure and a structure may be a member of a union.
Moreover, structures and unions may be freely mixed with arrays.

For example:
struct student
{
char name[30];
char sex;
int rollno;
float percentage;
};
union details
{
struct student st;
};

Q-10: How is a union member accessed? How can a union member be processed?

Ans: The members of a union can be accessed in a similar way as the members of a structure using
the . operator and -> operator. Thus if variable is a union variable, variable.member refers to
a member of the union. Similarly, if ptvar is a pointer variable that points to a union, then
ptvar->member refers to a member of that union. During accessing a union member, we
should make sure that we are accessing the member whose value is currently stored.

A union member can be processed in the same manner as ordinary variables of the same data
type. However, only one member can be processed at a time. Union members can appear in
expressions, they can be passed to functions and they can be returned from functions . A
union member that is an array can be processed in the same manner as an ordinary array and
with the same restrictions. Moreover, most C compilers permit an entire union to be assigned
to another, provided both unions have the same composition.

Q-11: How is a member of a union variable assigned an initial value? In what way does the
initialization of a union variable differ from the initialization of a structure variable?
Ans: A union variable can be initialized provided its storage class is either external or static.
However, only one member of a union can be assigned a value at any one time. When
initializing a union, the initializer list must have only one member, which initializes the first
member of the union unless a designated initializer is used.

For example:

union
{
int x;
char c[4];
}u={1}: // makes u.x active with value 1

Union is similar to that of structure. Syntax of both are same but major difference between
structure and union is memory storage. In structures, each member has its own storage
location, whereas all the members of union use the same location. Union contains many
members of different types. Union can handle only one member at a time. So, only one
member of a union can be initialized at a time unlike structures where we can initialize one or
all the members at a time.

Q-12: Summarize the rules that apply to processing unions. Compare with the rules that apply
to processing structures.

Ans: The rules that apply to processing unions are:


1. Union is quite similar to structure and is also a derived type as structure
2. Union can be defined in same manner as structures just the keyword used
in defining union is union whereas the keyword used in defining structure
was struct
3. Union variables can be created in similar manner as structur e variable.

For example :

union car
{
char name[50];
int price;
}c1,c2,*c3;

Accessing members of an union:


The members of unions can be accessed in similar manner as that structure. Suppose,
we want to access price for union variable c1 in above example, it can be accessed
as c1.price. If we want to access price for union pointer variable c3, it can be
accessed as (*c3).price or as c3->price.

Difference between union and structure:


Though unions are similar to structure in so many ways, the difference between them
is crucial to understand. This can be demonstrated by this example:

#include <stdio.h>
union job //defining a union
{
char name[32];
float salary;
int worker_no;
}u;
struct job1
{
char name[32];
float salary;
int worker_no;
}s;
main()
{
printf("Size of union = %d",sizeof(u));
printf("\nSize of structure = %d", sizeof(s));
}

Output:

size of union = 32
size of structure = 40

There is difference in memory allocation between union and structure as suggested in


above example. The amount of memory required to store a structure variable is the
sum of memory size of all members.
But, the memory required to store a union variable is the memory required for
largest element of an union.

We know that all members of structure can be accessed at any time. But, only one
member of union can be accessed at a time in case of union and other members will
contain garbage value.

Here is a program showing the working of union:

#include <stdio.h>
union job
{
char name[32];
float salary;
int worker_no;
}u;
main()
{
printf("Enter name:\n");
scanf("%s",&u.name);
printf("Enter salary: \n");
scanf("%f",&u.salary);
printf("Displaying\nName :%s\n",u.name);
printf("Salary: %.1f",u.salary);
}

Output:

Note: We may get different garbage value of name.

Reason for such an output:


Initially, ABCXYZ will be stored in u.name and other members of union will contain
garbage value. But when user enters value of salary, 4897.4 will be stored
in u.salary and other members will contain garbage value. Thus in output, salary is
printed accurately but, name displays some random string.

Q-14: Define a structure called cricket that will describe the following information

a. Players name,
b. team name,
c. batting average

And also write a program to give the information about the semi-final of world cup 2015
between India and Australia using structures. Information should contain players
name, team name, batting average, scores of each players and total score of each team.

Ans: #include<stdio.h>
#include<string.h>
struct cricket
{
char name[20],team[10];
float avg;
int run;
};
main()
{
int i,j;
struct cricket in[11],aus[11];
printf("######### Enter the details of the players######### ");
printf("\n \n \n \n Enter the details of the Indian players: ");
for(i=0;i<11;i++)
{
strcpy(in[i].team,"India");
printf(" \n\n**** Enter the details of the player %d ****\n",i+1);
printf("Name: ");
scanf(" %s",in[i].name);
printf("Batting average: ");
scanf("%f",&in[i].avg);
printf("Runs scored: ");
scanf("%d",&in[i].run);
}
printf("\n\n\n\n Enter the details of Australian players: ");
for(j=0;j<11;j++)
{
strcpy(aus[j].team,"Australia");
printf("\n\n**** Enter the details of the player %d ****\n",j+1);
printf("Name: ");
scanf(" %s",aus[j].name);
printf("Batting average: ");
scanf("%f",&aus[j].avg);
printf("Runs scored: ");
scanf("%d",&aus[j].run);
}
printf("\n\n**Match summary CWC'15 2nd semifinal INDIA vs AUSTRALIA**");
printf("\n AUSTRALIA - 328/7 \n INDIA - 223/10 \n Australia won by 95 runs \n") ;
printf(" \n\n \t\tScorecard\n\n\t\tAUSTRALIA\n");
printf( "\n Sl.No.\tPlayer\t\tBatting Avg\tRuns scored");
for(j=0;j<11;j++)
printf("\n%d\t%s\t\t%.2f\t%d ",j+1,aus[j].name,aus[j].avg,aus[j].run);
printf("\n\n\t\tINDIA\n");
for(j=0;j<11;j++)
{
printf( "\n%d\t%s\t\t%.2f\t%d",j+1,in[j].name,in[j].avg,in[j].run);
}
}

Q.15: Write a program to store student information such as name, roll number, marks, subjects
and display the same for 100 students. Also access the 5th, 6th and 7th elements of structures and
display the information separately.

SOLUTION:

#include<stdio.h>
struct student
{
char name[20];
int roll;
char sub1[10],sub2[10],sub3[10];
int m1,m2,m3;
};
void main()
{
struct student s[100];
printf(enter the details \n\n);
for(int i=0;i<100;i++)
{
printf( \n enter details for student number %d,i+1);
printf(\n enter the name);
scanf( %s,s[i].name);
printf(\n enter roll number);
scanf( %d,&s[i].roll);
printf(enter the first subject and its marks);
scanf( %s%d ,s[i].sub1,&s[i].m1);
printf(enter the second subject and its marks);
scanf( %s%d ,s[i].sub2,&s[i].m2);
printf(enter the first subject and its marks);
scanf( %s%d ,s[i].sub3,&s[i].m3);
}
printf(\n \n printing details);
for(int i=0;i<100;i++)
{
printf( \n details for student number %d,i+1);
printf(name : %s,s[i].name);
printf(\n roll number : %d,s[i].roll);
printf( subject marks \n);
printf( %s %d ,s[i].sub1,s[i].m1);
scanf( \n%s %d ,s[i].sub2,s[i].m2);
scanf( \n%s %d ,s[i].sub3,s[i].m3);
}
printf(\n \n \n);
printf( \n details for student number 5);
printf(name : %s,s[i].name);
printf(\n roll number : %d,s[4].roll);
printf( subject marks \n);
printf( %s %d ,s[4].sub1,s[4].m1);
printf( \n%s %d ,s[4].sub2,s[4].m2);
printf( \n%s %d ,s[4].sub3,s[4].m3);
printf(\n \);
printf( \n details for student number 6);
printf(name : %s,s[5].name);
printf(\n roll number : %d,s[5].roll);
printf( subject marks \n);
printf( %s %d ,s[5].sub1,s[5].m1);
printf( \n%s %d ,s[5].sub2,s[5].m2);
printf( \n%s %d ,s[5].sub3,s[5].m3);
printf(\n );
printf( \n details for student number 7);
printf(name : %s,s[6].name);
printf(\n roll number : %d,s[6].roll);
printf( subject marks \n);
printf( %s %d ,s[6].sub1,s[6].m1);
printf( \n%s %d ,s[6].sub2,s[6].m2);
printf( \n%s %d ,s[6].sub3,s[6].m3);
}

16. Write a program to define a structure called employee , that would contain employee name,
designation, department, salary, date of joining. Use the concept of nested structure in this program
for date of joining.

Solution :
#include <stdio.h>
struct doj
{
int day,month,year;
};
struct employee
{
char name[100];
char desgn[100];
char dept[100];
struct doj d;
};
main()
{
struct employee detail;
printf("enter name:\n");
gets(detail.name);
printf("enter designation:\n");
gets(detail.desgn);
printf("enter department:\n");
gets(detail.dept);
printf("enter date of joining:\n");
scanf("%d %d %d",&detail.d.day,&detail.d.month,&detail.d.year);
printf("\n\n\n");
printf("name of the employee :");
puts(detail.name);
printf("designation of the employee:");
puts(detail.desgn);
printf("department of the employee: ");
puts(detail.dept);
printf("date of joining of the employee %d/%d/%d" ,detail.d.day,detail.d.month,detail.d.year);
}

17. Describe the output generated by the following program. Distinguish between meaninful and
meaningless output.

Solution :

We get the following output when we run the given code .

The output clearly indicates that the memory required to store a union variable is the
memory required for largest element of an union.

And this is the reason for getting 8 as the size of the union variable , because the largest element is of
double type.

As we go through the further outputs we observe that only one variable has a legal value and other
two are assigned with garbage values .

This is because only one member of union can be accessed at a time in case of union and
other members will contain garbage value.Thus as we initialse u.f , the memory is
reallocated for storing the value at u.f and thus the value at u.i is removed .
Q18.Write a C program that will accept the following information for each team in a baseball
or a football league.

1.Team name, including the city (e.g., Pittsburgh Steelers) 2. Number of wins 3. Number of
losses For a baseball team, add the following information: 4. Number of hits 5. Number of
runs 6.Number of errors 7. Number of extra-inning games

Similarly, add the following information for a football team: 4. Number of ties 5. Number
of touchdowns 6.Number of field goals 7.Number of turnovers 8. Total yards gained
(season total) 9. Total yards given up to opponents

Enter this information for all of the teams in the league. Then reorder and print the list of
teams according to their win-lose records, using the reordering techniques. Store the
information in an array of structures, where each array element (i.e., each structure)
contains the information for a single team. Make use of a union to represent the variable
information (either baseball or football) that is included as a part of the structure. This
union should itself contain two structures, one for baseball-related statistics and the other
for football-related statistics. Test the program using a current set of league statistics.

SOLUTION

#include<stdio.h>
struct team
{
char *name_city;
int wins,loss;
union game detail;
};
struct baseball
{
int hit,run,error,exinn;
};
struct football
{
int tie,goal,touchdown,turnover,yardgain,yardgiven;
};
union game
{
struct baseball bb;
struct football fb;
};
main()
{
clrscr();
int n,i,j,a;
struct team t[100];
printf(" \n enter the number of teams in the league ( max 100) ");
scanf("%d",&n);
printf("\n input console \n for football league press 1 \n for base ball league press any other key \n");
scanf("%d",&a);
if(a==1)
{
for(i=0;i<n;i++)
{
printf("enter the details of the football team number %d ",&i+1);
printf("enter the name with city");
scanf(" %s",t[i].name_city);
printf(" \n enter number of wins");
scanf("%d",t[i].wins);
printf(" \nenter number of losses");
scanf("%d",t[i].loss);
printf("\nenter the number of ties ");
scanf("%d",t[i].detail.fb.tie);
}
}
else
{
for(i=0;i<n;i++)
{
printf("enter the details of the baseball team number %d ",&i+1);
printf("enter the name with city");
scanf(" %s",t[i].name_city);
printf("\n enter number of wins");
scanf("%d",t[i].wins);
printf("\n enter number of losses");
scanf("%d",t[i].loss);
printf("\n enter the number of runs scored ");
scanf("%d",t[i].detail.bb.run);
}
}
int max;
struct team y[100];
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(t[i].wins>t[j].wins)
max=i;
else
max=j;
}
y[i]=t[max];
}
printf("\n ****Points table **** ") ;
printf("\nRANK TEAM WINS LOSSES " );
for(i=0;i<n;i++)
{
printf("\n%d %s &d &d",i+1,y[i].name_city,y[i].wins,y[i].loss);
}
}

19.Describe the output generated by each of the following programs. Explain any
differences between the programs.

Solution :
Following is the output we get when we run the programme .

Though every thing within the programme is same as any other general programme , there are two
concepts which we get to learn .

1.Pointers can be used to declare strings .


Eg : char *ptr;
ptr= i am fine;

2.The C programming language provides a keyword called typedef, which you can use to give a typea
new name .
Example

Typedef unsigned char BYTE ;

After this definition, the identifier BYTE can be used as an abbreviation for the type unsigned char.

The application of typedef can be extended to structures in the following manner


For example,
struct MyStruct
{
int data1;
char data2;
};
Here a struct MyStruct data type has been defined. To declare a variable of this type in C
the struct key word is required .
struct MyStruct a;
A typedef can be used to eliminate the need for the struct key word in C. For example, with:
typedef struct MyStruct newtype;
we can now create a variable of this type with:
newtype a;
Note that the structure definition and typedef can instead be combined into a single statement:
typedef struct MyStruct
{
int data1;
char data2;
} newtype;
Or simply we can also use it as:
typedef struct
{
int data1;
char data2;
} newtype;

You might also like