0% found this document useful (0 votes)
24 views

Module 2

Uploaded by

717821d112
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Module 2

Uploaded by

717821d112
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Page 1 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

Degree&Branch : B.E./B.TECH CSE, CST, CSD,IT, ECE, EEE, ETE


Semester: II / Year: I Course Code &Title: - ADVANCED C
PROGRAMMING
MODULE – II
Part-A – Short Answer Questions
(2 marks)

1 Write a c program to find length of the string using string handling functions
#include <stdio.h>
#include <string.h>
int main()
{
char a[20];
printf("Enter String =");
gets(a);
printf("Length of string a = %d",strlen(a));
return 0;
}
Output
Enter String =Programming
Length of string a = 11
2 Write a c program to copy one string into another string using string handling
functions
#include<stdio.h>
#include<string.h>
int main ()
{
char a[100];
char b[100];
printf("Enter string = ");
gets(a);
strcpy(b,a);
puts(b);
return 0;
}
Output
Enter string = advanced
Advanced
3 Write a c program to merge two string into one string using string handling
functions.
#include<stdio.h>
Page 2 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

#include<string.h>
int main ()
{
char a[100];
char b[100];
printf("Enter string I= ");
gets(a);
printf("Enter string II = ");
gets(b);
strcpy(a,b);
puts(a);
return 0;
}
Output
Enter string I= advanced
Enter string II = programming
advancedprogramming

4 Write a c program to reverse a string using string handling functions


#include <stdio.h>
#include <string.h>
int main()
{
char a[20];
printf("Enter String =");
gets(a);
printf("Reverse of string is = %s",strrev(a));
return 0;
}
Output
Enter String =advanced
Reverse of string is = decnavda
5 Write a c program to compare two strings. If two strings are match then display
“STRINGS ARE MATCH” otherwise “STRINGS ARE NOT MATCH” string
handling functions.
#include<stdio.h>
#include<string.h>
int main ()
{
char a[100];
char b[100];
printf("Enter string I= ");
gets(a);
printf("Enter string II = ");
gets(b);
if(strcmp(a,b)==0)
{
printf("Strings are not match");
}
else
{
printf("Strings are match");
Page 3 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

}
return 0;
}
Output:
Enter string I= abc
Enter string II = abc
Strings are match

6 Write a c program to read string and convert the string into upper case using string
handling functions.
#include <stdio.h>
#include <string.h>
int main()
{
char a[20];
printf("Enter String =");
gets(a);
printf("Upper case of string is = %s",strupr(a));
return 0;
}
Output:
Enter String =program
Upper case of string is = PROGRAM
7 Write a c program to read string and convert the string into lower case using string
handling functions.
#include <stdio.h>
#include <string.h>
int main()
{
char a[20];
printf("Enter String =");
gets(a);
printf("Upper case of string is = %s",strlwr(a));
return 0;
}
Output:
Enter String =PROGRAM
Upper case of string is = program

8 Static memory allocation vs dynamic memory allocation

Static memory allocation dynamic memory allocation


Memory is allocated at compile time. Memory is allocated at run time.
Memory can't be increased while executing Memory can be increased while executing
program. program.
Used in array. Used in linked list.
Page 4 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

9 Arrays vs pointers

Arrays Pointers
type var_name[size]; type * var_name;
Collection of elements of similar data Store the address of another variable.
type.
The array can be initialized at the time of Pointers cannot be initialized at definition.
definition.
Arrays are allocated at compile time. Pointers are allocated at run-time.
Memory allocation is in sequence. Memory allocation is random.
10 Structure vs union
Structure Union
The struct keyword is used to define a The union keyword is used to define
structure. union.
Each variable member occupied a unique Variables members share the memory
memory space. space of the largest size variable.
Changing the value of a member will not Changing the value of one member will
affect other variables members. also affect other variables members.
The structure allows initializing multiple Union allows initializing only one variable
variable members at once. member at once.
It allows accessing and retrieving any data It allows accessing and retrieving any one
member at a time. data member at a time.
11 Structure Vs Arrays

Structure Array
Array refers to a collection consisting of Structure refers to a collection consisting
elements of homogeneous data type. of elements of heterogeneous data type.
Array uses subscripts or “[ ]” (square Structure uses “.” (Dot operator) for
bracket) for element access element access
Array is pointer as it points to the first Structure is not a pointer
element of the collection.
Instantiation of Array objects is not Instantiation of Structure objects is
possible. possible.
Array size is fixed and is basically the Structure size is not fixed as each element
number of elements multiplied by the size of Structure can be of different type and
of an element. size.
12 getchar()
Input function
It is used to accept character data type only.
Read single character alone
Example
#include <stdio.h>
#include <conio.h>
int main()
{
char ch;
printf ("\n Enter the character \n");
Page 5 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

scanf ("%c", &ch);


printf( " You have entered %c", ch);
return 0;
}
13 Typedef
The C programming language provides a keyword called typedef, which you can use to
give a type a new name.
Eg:
#include<stdio.h>
#include<stdio.h>
typedef int integer;
int main()
{
int a=5;
integer b=7;
printf("%d",a);
printf("%d",b);
return 0;
}
Output
57
Advantage
 User can create their own datatype
 typedef interpretation is performed by the compiler
 typedef is the actual definition of a new data type
 typedef follows the scope rule which means if a new type is defined in a scope
(inside a function), then the new type name will only be visible till the scope is
there.
14 scanf()
 Scanf is a input statement
 It can accept all kin of input such as int, char, float etc..
 Give the input according to format specifier
Eg
#include<stdio.h>
int main()
{
char a[20];
printf("Enter String=");
scanf("%s",a);
return 0;
}
Output
Enter String=advanced
Advanced
15 Strings
 Collection of character is called string.
 End of string marked as a special character called null character
 Null character is representing by another character escape sequence.
 Null character = „\0‟

Declaration of strings
char a[30];
Page 6 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

char a[];
String Initialization
char str[9]=”I like C”;
char str[9]={„I‟,‟ „,‟l‟,‟i‟,‟k‟,‟e‟,‟‟,‟C‟,‟/0‟};

16 List and mention the syntax of all dynamic memory allocation

Type Syntax
malloc() ptr=(data_type*)malloc(byte-size)
calloc() ptr=(data_type*)calloc(number, byte-size)
realloc() ptr=realloc(ptr, new-size)
free() free(ptr)
17
18 What are the functions of dynamic memory allocation?

malloc()  It doesn't initialize memory at execution time, so it has garbage value


initially.
 It returns NULL if memory is not sufficient.

calloc()  The calloc() function allocates multiple block of requested memory.


 It initially initialize all bytes to zero.
 It returns NULL if memory is not sufficient.

realloc() If memory is not sufficient for malloc() or calloc(), you can reallocate the
memory by realloc() function. In short, it changes the memory size.
free() The memory occupied by malloc() or calloc() functions must be released
by calling free() function. Otherwise, it will consume memory until
program exit.

19 Find Output of the program


int main()
{
char str[2];
int i=0;
scanf("%s", str);
while(str[i] != '\0')
{
printf("%c", str[i]);
i++;
}
return 0;
}
//Input: KLMN
Answer
KLMN
20 Find Output of the program

int main()
Page 7 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

{
char p[] = "GODZILLA";
int i=0;
while(p[i] != '\0')
{
printf("%c",*(p+i));
i++;
}
}
Answer
GODZILLA
21 Runtime sized array
 Variable length arrays are also known as runtime sized or variable sized arrays.
 Variable sized arrays are data structures whose length is determined at runtime
rather than compile time.
 The size of such arrays is defined at run-time.
 Variable length arrays are a feature where we can allocate an auto array (on
stack) of variable size.
 It can be used in a typedef statement.
22 Structure
In C programming, a struct (or structure) is a collection of variables (can be of different
types) under a single name.
Initialization
Syntax 1
struct structure_name
{
Data member 1;
Data member 2;
.
.
.
Date member n;
}Object_name;
Syntax 2
struct structure_name
{
Data member 1;
Data member 2;
.
.
.
Date member n;
}Object_name1, Object_nam2………. Object_name n;

Syntax 3
struct structure_name
{
Data member 1;
Data member 2;
.
Page 8 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

.
.
Date member n;
};
int main()
{
struct structure_name object_name;
}

Syntax 4
struct structure_name
{
Data member 1;
Data member 2;
.
.
.
Date member n;
};
int main()
{
struct structure_name object_name1;
struct structure_name object_name2;
.
.
.
.
struct structure_name object_namen
}

23 Spot the error in following C program


#include<stdio.h>
structure address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void display(struct employee);
int main ()
{
struct employee emp;
printf("Enter employee information?\n");
Page 9 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

scanf("%s %s %d ",emp.name,add.city, &emp.add.pin, emp.add.phone);


display(emp);
}
void display(struct employee emp)
{
printf("Printing the details....\n");
printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone)
}
Answer
Error 1: Struct keyword replaced by structure
Error 2:%s is missing
Error 3:emp.add missing
Error 4:Semicolon missing in last line

Signature of the Course Coordinator Signature of the HoD


Page 10 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

Degree&Branch : B.E./B.TECH CSE, CST, CSD,IT, ECE, EEE, ETE


Semester: II / Year: I Course Code &Title: - ADVANCED C
PROGRAMMING
MODULE - II
Part-B - Essay type Questions
1 i) Write a c program to find length of the without string using string handling
functions
#include <stdio.h>
int main()
{
char s[100];
int i;
printf("Enter a string: ");
scanf("%s", s);
for(i=0;s[i]!='\0';i++);
printf("Length of string: %d", i);
return 0;
}
Output
Enter a string: advanced
Length of string: 8

ii) Write a c program to copy one string into another string without using string
handling functions
#include <stdio.h>
int main()
{
char s1[100], s2[100],i;
printf("Enter string s1:");
gets(s1);
for(i = 0; s1[i] != '\0'; i++)
{
s2[i] = s1[i];
}
s2[i] = '\0';
printf("String s2=");
puts(s2);
return 0;
}
Output
Enter a string: advanced
Length of string: 8
Page 11 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

2 i) Write a c program to merge two string into one string without using string
handling functions.
#include <stdio.h>
int main()
{
char str1[100],str2[100],str3[100];
int i = 0, j = 0;
printf("\nFirst string:");
gets(str1);
printf("\nSecond string:");
gets(str2);
while (str1[i] != '\0')
{
str3[j] = str1[i];
i++;
j++;
}
i = 0;
while (str2[i] != '\0') {
str3[j] = str2[i];
i++;
j++;
}
str3[j] = '\0';
printf("\nConcatenated string: %s", str3);
return 0;
}
Output:
First string:abc
Second string:def
Concatenated string: abcdef
ii) Write a c program to reverse a string without using string handling functions
#include <stdio.h>
int main()
{
char s1[100],i,len;
printf("Enter string s1:");
gets(s1);
for(len = 0; s1[len] != '\0'; len++);
for(i=len-1;s1[i]>=0;i--)
{
printf("%c",s1[i]);
}
return 0;
}
Output
Enter string s1:abc
cba

3 i) Write a c program to compare two strings. If two strings are match then display
“STRINGS ARE MATCH” otherwise “STRINGS ARE NOT MATCH” without
string handling functions.
Page 12 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

#include <stdio.h>
#include<string.h>
int main()
{
char str1[20]; // declaration of char array
char str2[20]; // declaration of char array
int value; // declaration of integer variable
printf("Enter the first string : ");
scanf("%s",str1);
printf("Enter the second string : ");
scanf("%s",str2);
// comparing both the strings using strcmp() function
value=strcmp(str1,str2);
if(value==0)
{
printf("strings are same");
}
else
{
printf("strings are not same");
}
return 0;
}
Output 1
Enter the first string : abc
Enter the second string : abc
strings are same
Output 2
Enter the first string : abc
Enter the second string : def
strings are not same

ii) Write a c program to read string and convert the string into upper case without
using string handling functions.
#include <stdio.h>
#include <string.h>
int main()
{
char Str1[100];
int i;
printf("\n Please Enter a String: ");
gets(Str1);
for (i = 0; Str1[i]!='\0'; i++)
{
if(Str1[i] >= 'A' && Str1[i] <= 'Z')
{
Str1[i] = Str1[i] +32;
}
}
printf("\n Lower Case = %s", Str1);
return 0;
}
Output
Page 13 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

Please Enter a String: PROGRAM


Lower Case = program
4 i) Write a c program to read string and convert the string into lower case without
using string handling functions.
#include <stdio.h>
#include <string.h>
int main()
{
char Str1[100];
int i;
printf("\n Please Enter a String: ");
gets(Str1);
for (i = 0; Str1[i]!='\0'; i++)
{
if(Str1[i] >= 'a' && Str1[i] <= 'z')
{
Str1[i] = Str1[i] -32;
}
}
printf("\n Upper Case = %s", Str1);
return 0;
}
Output:
Please Enter a String: program
Upper Case = PROGRAM
ii) Write a C program to calculate length of the string using pointer without using
string handling functions
#include<stdio.h>
int main()
{
char str[20], *pt;
int i = 0;
printf("Enter Any string: ");
gets(str);
pt = str;
while (*pt!= '\0') {
i++;
pt++;
}
printf("Length of String : %d", i);
return 0;
}
Output
Enter Any string: advanced
Length of String : 8
5 i) Write a C program to using function for concatenation of two strings without
using string handling functions
#include <stdio.h>
void con(char [],char []);
int main()
{
char str1[100], str2[100];
Page 14 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

printf("\nFirst string:");
gets(str1);
printf("\nSecond string:");
gets(str2);
con(str1,str2);
return 0;
}
void con(char str1[],char str2[])
{
int i = 0, j = 0;
char str3[100];
while (str1[i] != '\0') {
str3[j] = str1[i];
i++;
j++;
}
i = 0;
while (str2[i] != '\0') {
str3[j] = str2[i];
i++;
j++;
}
str3[j] = '\0';
printf("\nConcatenated string: %s", str3);
}
Output
First string:advanced
Second string:program
Concatenated string: advancedprogram
ii) Explain dynamic memory allocation with example.
To allocate memory at runtime.
4 functions of stdlib.h header file.

malloc() - Allocates single block of requested memory.


calloc() - Allocates multiple block of requested memory.
realloc() - Reallocates the memory occupied by malloc() or calloc() functions.
free() - Frees the dynamically allocated memory.
Example for malloc
Page 15 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

malloc() ptr=(cast-  It doesn't initialize memory at execution


type*)malloc(byte- time, so it has garbage value initially.
size)  It returns NULL if memory is not sufficient.

calloc() ptr=(cast-  The calloc() function allocates multiple


type*)calloc(number, block of requested memory.
byte-size)  It initially initialize all bytes to zero.
 It returns NULL if memory is not sufficient.

realloc() ptr=realloc(ptr, new- If memory is not sufficient for malloc() or


size) calloc(), you can reallocate the memory by
realloc() function. In short, it changes the
memory size.
free() free(ptr) The memory occupied by malloc() or calloc()
functions must be released by calling free()
function. Otherwise, it will consume memory
until program exit.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char *str;

str =(char *) malloc( 15 * sizeof(char) );

if(str== NULL )
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
strcpy( str,"Welcome to KCE");
}

printf(" %s\n", str );


free(str);
}
output:
Welcome to KCE
Example for calloc
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char *str;
str =(char *) calloc ( 15 , sizeof(char) );
if(str== NULL )
{
Page 16 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

printf("Memory not allocated.\n");


exit(0);
}
else
{
strcpy( str,"Welcome to KCE");
}
printf(" %s\n", str );
free(str);
}
output:
Welcome to KCE
Example for realloc
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char *str;
str =(char *) malloc( 10 * sizeof(char) );
if(str == NULL )
{
printf("Memory not allocated.\n");
}
else
{
strcpy( str ,"Welcome");
}

printf("%s\n", str );
str =realloc(str ,100*sizeof(char));
if( str == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( str,"Welcome to KCE");
}
printf("Resized memory : %s\n", str);
free(str );
}
output:
Welcome
Resized memory : Welcome to KCE
Page 17 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

6 i) Brief about Enumeration data type


Enumeration (or enum) is a user defined data type in C. It is mainly used to assign
names to integral constants, the names make a program easy to read and maintain.
Syntax to Define Enum
enum enum_name{int_const1, int_const2, int_const3, …. int_constN};
enum enum_name object_name;
OR
enum enum_name{int_const1, int_const2, int_const3, …. int_constN}Object_name;

Example 1
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}
Output : 2
Because Mon=0, Tue=1, Wed=2 So the output will be 2
Example 2
#include<stdio.h>
enum week{Mon=8, Tue=9, Wed=2, Thur=3};
int main()
{
enum week day;
printf("%d%d%d%d",Mon,Tue,Wed,Thur);
return 0;
}
Output :
8923
Example 3
#include<stdio.h>
enum week{Mon=8,Tue,Wed,Thur=4,Fri,Sat,Sun};
int main()
{
enum week day;
printf("%d%d%d%d%d%d%d",Mon,Tue,Wed,Thur,Fri,Sat,Sun);
return 0;
}
Output :
Page 18 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

8 9 10 4 5 6 7
Example 4
#include<stdio.h>
enum week{a,b,c,d,e,f};
int main()
{
enum week day;
for(int i=a;i<=f;i++)
{
printf("%d",i);
}
return 0;
}
Output:
012345

ii) Write a C program to calculate total fine amount for individual book for
individual student in the following library details using structure.

Total fine =FINE1=FINE2


Title author subject book_id FINE1 FINE2
C Nuha Ali C Programming 6495407 Rs. 45 Rs.40
Programming Tutorial
Telecom Billing Zara Ali Telecom Billing 6495700 Rs .48 Rs.40
Tutorial
Answer
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
int fine1;
int fine2;
};
int main( ) {
int tot1;
int tot2;
struct Books Book1;
struct Books Book2;
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
Page 19 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

strcpy( Book1.subject, "C Programming Tutorial");


Book1.book_id = 6495407;
Book1.fine1=45;
Book1.fine2=40;
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
Book2.fine1=48;
Book2.fine2=40;
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
printf( "Book 1 fine1 : %d\n", Book1.fine1);
printf( "Book 1 fine2 : %d\n", Book1.fine2);
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);
printf( "Book 2 fine1 : %d\n", Book2.fine1);
printf( "Book 2 fine2 : %d\n", Book2.fine2);
tot1=Book1.fine1+Book1.fine2;
tot2=Book2.fine1+Book2.fine2;
printf("total fine Book1 =%d\n",tot1);
printf("total fine Book2 =%d\n",tot2);
return 0;
}
Output:
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 1 fine1 : 45
Book 1 fine2 : 40
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Book 2 fine1 : 48
Book 2 fine2 : 40
total fine Book1 =85
Page 20 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

total fine Book2 =88

7 i) Explain about Structure padding


 Structure padding is a concept in C that adds the one or more empty bytes
between the memory addresses to align the data in memory.
 Suppose we create a user-defined structure. When we create an object of this
structure, then the contiguous memory will be allocated to the structure
members.
struct student
{
char a;
char b;
int c;
} stud1;
 In the above example, we have created a structure of type student. We have
declared the object of this structure named as 'stud1'. After the creation of an
object, a contiguous block of memory is allocated to its structure members.
First, the memory will be allocated to the 'a' variable, then 'b' variable, and then
'c' variable.
What is the size of the struct student?
 Now, we calculate the size of the struct student. We assume that the size of the
int is 4 bytes, and the size of the char is 1 byte.
struct student
{
char a; // 1 byte
char b; // 1 byte
int c; // 4 bytes
}
In the above case, when we calculate the size of the struct student, size comes to be 6
bytes. But this answer is wrong. Now, we will understand why this answer is wrong?
We need to understand the concept of structure padding.
Structure Padding
The processor does not read 1 byte at a time. It reads 1 word at a time.
What does the 1 word mean?
If we have a 32-bit processor, then the processor reads 4 bytes at a time, which means
that 1 word is equal to 4 bytes.
1 word = 4 bytes
If we have a 64-bit processor, then the processor reads 8 bytes at a time, which means
that 1 word is equal to 8 bytes.
1 word = 8 bytes
Therefore, we can say that a 32-bit processor is capable of accessing 4 bytes at a time,
whereas a 64-bit processor is capable of accessing 8 bytes at a time. It depends upon
the architecture that what would be the size of the word.
Why structure padding?
struct student
{
char a; // 1 byte
char b; // 1 byte
int c; // 4 bytes
}
If we have a 32-bit processor (4 bytes at a time), then the pictorial representation of the
memory for the above structure would be:
Page 21 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

In order to achieve the structure padding, an empty row is created on the left, as shown
in the above diagram, and the two bytes which are occupied by the 'c' variable on the
left are shifted to the right. So, all the four bytes of 'c' variable are on the right. Now,
the 'c' variable can be accessed in a single CPU cycle. After structure padding, the total
memory occupied by the structure is 8 bytes (1 byte+1 byte+2 bytes+4 bytes), which is
greater than the previous one. Although the memory is wasted in this case, the variable
can be accessed within a single cycle.
#include <stdio.h>
struct student
{
char a;
char b;
int c;
};
int main()
{
struct student stud1; // variable declaration of the student type..
// Displaying the size of the structure student.
printf("The size of the student structure is %d", sizeof(stud1));
return 0;
}

Output
The size of the student structure is 8
ii) Explain about Pointers to Structures in C program
The structure pointer points to the address of a memory block where the Structure is
being stored.
Declare a Structure Pointer
struct structure_name *ptr;
Initialization of the Structure Pointer
ptr = &structure_variable;
Access Structure member using pointer:
1. Using ( * ) asterisk or indirection operator and dot ( . ) operator.
2. Using arrow ( -> ) operator or membership operator.
#include<stdio.h>
struct student{
int sno;
char sname[30];
float marks;
Page 22 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

};
int main ( )
{
struct student s;
struct student *st;
st = &s;
printf("enter sno, sname, marks:");
scanf ("%d%s%f", & st->sno, st->sname, &st->marks);
printf ("details of the student are");
printf ("Number = %d\n", st ->sno);
printf ("name = %s\n", st->sname);
printf ("marks =%f\n", st ->marks);
}
Output
enter sno, sname, marks:1
king
56
details of the student areNumber = 1
name = king
marks =56.000000
8 i) Discuss about Union in C.
A union is a special data type available in C that allows to store different data types in
the same memory location. You can define a union with many members, but only one
member can contain a value at any given time. Unions provide an efficient way of
using the same memory location for multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while
defining a structure. The union statement defines a new data type with more than one
member for program. The format of the union statement is as follows –
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
Example
union Data
{
int i;
float f;
char str[20];
} data;
 Now, a variable of Data type can store an integer, a floating-point number, or a
string of characters. It means a single variable, i.e., same memory location, can
be used to store multiple types of data.
 The memory occupied by a union will be large enough to hold the largest
member of the union. For example, in the above example, Data type will
Page 23 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

occupy 20 bytes of memory space because this is the maximum space which
can be occupied by a character string.
The following example displays the total memory size occupied by the above union –
Program:
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
Output
Memory size occupied by data : 20
Accessing union members
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here I,f are corrupted because the final value assigned to the variable has occupied the
memory location.
Example 2
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
Page 24 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

union Data data;


data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Example 3:
#include<stdio.h>
union abc
{
int a;
char b;
}var;
int main()
{
var.a = 66;
printf("\n a = %d", var.a);
printf("\n b = %d", var.b);
}
Outut
66
66

In the above code, union has two members, i.e., 'a' and 'b'. The 'var' is a variable of
union abc type. In the main() method, we assign the 66 to 'a' variable, so var.a will
print 66 on the screen. Since both 'a' and 'b' share the memory location, var.b will print
'B' (ascii code of 66).
ii) How the program is differ from structure into typedef.
STRUCTURE TYPEDEF
#include<stdio.h> #include<stdio.h>
struct Point{ struct Point{
int x; int x;
int y; int y;
}; };
int main() { typedef struct Point Point;
struct Point p1; int main() {
p1.x = 1; Point p1;
p1.y = 3; p1.x = 1;
printf("%d \n", p1.x); p1.y = 3;
printf("%d \n", p1.y); printf("%d \n", p1.x);
return 0; printf("%d \n", p1.y);
} return 0;
Output }
1 Output
3 1
3
Page 25 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

9 i) Write a C program to display third character from last.


Sample Input / Output
Enter String =Advanced
Third character from last =c
Answer
#include <stdio.h>
#include <string.h>
int main()
{
char a[100];
int len;
printf("Enter String =");
gets(a);
for(len=0;a[len]!='\0';len++);
printf("Third character from last= %c",a[len-3]);
}
Output
Enter String =Advanced
Third character from last =c

ii) Brief about types of Structures in C program


 C provides us the feature of nesting one structure within another structure by
using which, complex data types are created.
 For example, we may need to store the address of an entity employee in a
structure. The attribute address may also have the subparts as street number,
city, state, and pin code.
 Hence, to store the address of the employee, we need to store the address of the
employee into a separate structure and nest the structure address into the
structure employee.
Consider the following program.
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
Page 26 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

struct employee emp;


printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
printf("Printing the employee information....\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone:
%s",emp.name,emp.add.city,emp.ad
d.pin,emp.add.phone);
}
Output:
Enter employee information?
Arun
Delhi
110001
1234567890
Printing the employee information....
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890
The structure can be nested in the following ways.
1. By separate structure
2. By Embedded structure
1) Separate structure
Here, we create two structures, but the dependent structure should be used inside the
main structure as a member. Consider the following example.
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
2) Embedded structure
The embedded structure enables us to declare the structure inside the structure.
Hence,
it requires less line of codes but it cannot be used in multiple data structures.
Consider
the following example.
struct Employe
{
int id;
Page 27 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;

//printing first employee information


printf( "employee id : %d\n", e1.id);
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy) :
%d/%d/%d\n",e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
return 0;
}
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014
10 i) Bit fields
In C, we can specify size (in bits) of structure and union members. The idea is to use
memory efficiently when we know that the value of a field or group of fields will never
exceed a limit or is within a small range.
Bit Field Declaration
struct
{
type [member_name] : width ;
};
 Where Type- An integer type that determines how a bit-field's value is
interpreted. The type may be int, signed int, or unsigned int. member_name-
The name of the bit-field. width- The number of bits in the bit-field. The width
must be less than or equal to the bit width of the specified type.
 The variables defined with a predefined width are called bit fields. A bit field can
hold more than a single bit; for example, if you need a variable to store a value
from 0 to 7, then you can define a bit field with a width of 3 bits as follows –
Example:
struct {
Page 28 of 28 Course Code: 18DC04/18SC04/18LC04/18TC04/18EC04/18PC04/18FC04

unsigned int age : 3;


} Age;
The above structure definition instructs the C compiler that the age variable is going to
use only 3 bits to store the value. If you try to use more than 3 bits, then it will not
allow you to do so.
Example 2:
struct example_bitField {
int val1;
int val2;
}b1;
struct example_bitField2 {
int val1: 1;
int val2: 1;
}b2;
int main(void) {
printf(" \n Size of memory engaged by example_bitField : %zu ", sizeof(b1));
printf(" \n Size of memory engaged by example_bitField2: %zu ", sizeof(b2));
return 0;
}
Output:
Size of memory engaged by example_bitField : 8
Size of memory engaged by example_bitField2 : 4

Signature of the Course Coordinator Signature of the HoD

You might also like