Module 2
Module 2
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
}
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
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
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‟};
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?
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.
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
}
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
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.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char *str;
if(str== NULL )
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
strcpy( str,"Welcome to KCE");
}
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
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.
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
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
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;