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

PPSC Unit 3 Part B

Strings in C are arrays of characters terminated by a null character '\0'. Strings can be declared and initialized like character arrays. The null character indicates the end of the string. Common string operations include reading, writing, combining, copying, comparing, and extracting portions of strings. Standard library functions like strlen(), strcat(), strcpy(), strcmp() allow manipulating strings. Formatted functions like scanf() and printf() are used for string input/output along with format specifiers like %s. Unformatted functions getchar(), putchar() are also used for basic I/O.

Uploaded by

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

PPSC Unit 3 Part B

Strings in C are arrays of characters terminated by a null character '\0'. Strings can be declared and initialized like character arrays. The null character indicates the end of the string. Common string operations include reading, writing, combining, copying, comparing, and extracting portions of strings. Standard library functions like strlen(), strcat(), strcpy(), strcmp() allow manipulating strings. Formatted functions like scanf() and printf() are used for string input/output along with format specifiers like %s. Unformatted functions getchar(), putchar() are also used for basic I/O.

Uploaded by

Hermione Granger
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Programming for Problem Solving using C (R20)

STRINGS

Strings: The string is a one-dimensional array of characters terminatedby a null character '\0'. Since
string is an array, the declaration of a string is the same as declaring a char array.
Declaration of a String
char string_name[size];
Initialization of a String
char string_name[size]= “string”;
Example of Declaration and Initialization of a String
char greeting []={'H‟, 'E', 'L', 'L', 'O', '\0'};
or
char greeting []="HELLO";
NULL Char “\0”: '\0' represents the end of the string. It is also referred as String terminator & Null
Character.

Fig.: Memory Representation of String


Note: The C compiler automatically places the '\0' at the end of the string when it initializes the
array. The terminating null („\0‟) is important, because it is the only way the functions that work
with a string can know where the string ends.
Operations on Strings:
 Reading and writing strings
 Combining strings together
 Copying strings i.e., one string to another
 Comparing strings for equality
 Extracting a portion of a string
//Example program for string
#include <stdio.h>
int main ()
{
char string[20] = "hello";
printf("The string is : %s \n", string );
return 0;
}
Output: The string is hello
//Program to demonstrate printing of a string
#include<stdio.h>
int main( )
{
char name[ ] = "Srinadh" ;
int i = 0 ;
while ( i<= 6 ) //without NULL character

Pragati Engineering College (Autonomous) Page 1


Programming for Problem Solving using C (R20)
{
printf( "%c", name[i]) ;
i++ ;
}
}
OUTPUT: Srinadh
Following program illustrates printing string using „\0‟.
#include<stdio.h>
main( )
{
char name[ ] = "Srinadh" ;
int i = 0 ;
while ( name[i] != '\0' ) //using NULL character
{
printf ( "%c",name[i]);
i++;
}
}
OUTPUT: Srinadh
Difference between char array and string literal: There are two main differences between char
array and literal.
1. We need to add the null character '\0' at the end of the array by ourself whereas, it is appended
internally by the compiler in the case of the character array.
2. The string literal cannot be reassigned to another set of characters whereas, we can reassign the
characters of the array.
/#include<stdio.h>
#include <string.h>
int main()
{
char ch[11]={'s', 'r', 'i', 'r', 'a', 'j','\0'};
char ch2[11]="sriraj";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
return 0;
}
Output: Char Array Value is: sriraj String Literal Value is: Sriraj
String input output functions: C language provide us console input/output functions. As the name
says, the console input/output functions allow us to read the input from the keyboard by the user
accessing the console. Display the output to the user at the console. There are two kinds of console
input/output functions -
1. Formatted input/output functions
2. Unformatted input/output functions.
1. Formatted input/output functions: Formatted console input/output functions are used to take
one or more inputs from the user at console and it also allows us to display one or multiple values
in the output to the user at the console Some of the most important formatted console input/output
functions are:

scanf() This function is used to read one or multiple inputs from the user at the console.

Pragati Engineering College (Autonomous) Page 2


Programming for Problem Solving using C (R20)
This function is used to display one or multiple values in the output to the user at the
printf()
console.
sscanf() This function is used to read the charactersfrom a string and stores them in variables.
This function is used to read the values stored in different variables and store these
sprintf()
values in acharacter array.

Formatted console input/output functions: While calling any of the formatted console
input/output functions, we must use a specific format specifiers in them, which allow us to read
or display any value ofa specific primitive data type. Let's see what are these format specifiers.
Example for printf() /scanf() :
#include<stdio.h>
int main()
{
char name[100];
printf("Enter your name:");
scanf("%s",name);
printf("name is %s",name);
}
Output: Enter your name: prem
name is prem ( scanf terminates string when it finds white space)
Note: %s format specifier is used for strings input/output
Example for printf() /scanf() :
#include<stdio.h>
int main()
{
char ch;
int i;
float f;
/* Reading values using scanf() */
printf("Reading the values -");
printf("\n");
printf("Enter a char value : ");
scanf("%c",&ch); /* Reading a char value with format specifier %c */
printf("Enter an int value : ");
scanf("%d",&i); /* Reading an int value with format specifier %d */
printf("Enter a float value : ");
scanf("%f",&f); /* Reading an float value with format specifier %f */
printf("Display the values you've entered -"); /* Displaying values using printf() */
printf("\n");
printf("The char value you entered : %c", ch); /* Displaying a char value with format
specifier %c */
printf("\n");
printf("The int value you entered : %d", i);/* Displaying an int value with format specifier
%d */
printf("\n");
printf("The float value you entered : %f", f);/* Displaying a float value withformat specifier
%f */
printf("\n");
return 0;

Pragati Engineering College (Autonomous) Page 3


Programming for Problem Solving using C (R20)
}
Output:
Reading the values - Enter a char value : s
Enter an int value : 9
Enter a float value : 9.9
Display the values you've entered -The char value you entered : s
The int value you entered : 9
The float value you entered : 9.900000
2. Unformatted input/output functions: Unformatted console input/output functions are used to
read a single input fromthe user at console and it also allows us to display the value in the output to
the user at the console. Some of the most important formatted console input/output functions are -

Functions Description
getch() Reads a single character from the user at theconsole, without echoing it.
getche() Reads a single character from the user at theconsole, and echoing it.
Reads a single character from the user at the console, and echoing it, but needs an
getchar()
Enter key to bepressed at the end.
gets() Reads a single string entered by the user at the console.
puts() Displays a single string's value at the console.
putch() Displays a single character value at the console.
putchar() Displays a single character value at the console.

puts() and gets() functions: The gets() function reads a line or multiword string from stdin into the
buffer pointed to by s until either a terminating newline or EOF (end of file).The puts() function
writes the string s and a trailing newline to stdout.
Example:
#include<stdio.h>
int main()
{
char name[100];
printf("Enter your name:");
gets(name);
puts(name);
}
OUTPUT: Enter your name: ravi
ravi

Difference between scanf() and gets():

S.No. scanf() puts()


1 It reads single word strings It reads multi-word strings
It stops reading characters when it It stops reading characters when itencounters a
2
encounters a whitespace newline or EOF
3 Example: Sai Example: Sai Ram

Example to demonstrate putch() and putchar() to display the a char value


#include<stdio.h>
#include<conio.h>
Pragati Engineering College (Autonomous) Page 4
Programming for Problem Solving using C (R20)
int main()
{
int ch = 'a';
printf("The character value printed using putch() : ");
putch(ch);
printf("\n");
printf("Another character value printed using putch() : ");
putch('B');
printf("\n");
printf("The character value printed using putchar() : ");
putchar(ch);
printf("\n");
printf("Another character value printed using putchar() : ");
putch('D');
return 0;
}
OUTPUT: The character value printed using putch() : a
Another character value printed using putch() : B
The character value printed using putchar() : a
Another character value printed using putchar() : D
String Library/Standard/Handling Functions: With every C compiler a large set of useful
string handling library functions are provided. For using these functions, we need to include the
header file string.h.
The following are some of the useful string handling functions supported by C.
String Function Description
strlen(string) Gives the length of string
strcat(str1,str2 ) Concatenates str2 at the end of str1
strncat( str1,str2,n) Appends a portion of string to another
strcpy(str1,str2) Copies str2 into str1
strncpy(str1,str2,n) Copies given number of characters of one string to another
Returns 0 if str1 is same as str2.Returns <0 if strl< str2. Returns >0 if str1
strcmp( str1,str2)
> str2.
Same as strcmp() function. But, this function negotiates case.“A” and “a” are
strcmpi(str1,str2)
treated as same.
strrev(string ) Reverses the given string
strlwr(string ) Converts string to lowercase
strupr(string ) Converts string to uppercase
strchr(str1,‟c‟) Returns pointer to first occurrence of char in str1
strrchr(str1,‟c‟ ) last occurrence of given character in a string is found
strstr(str1,str2 ) Returns pointer to first occurrence of str2 in str1
strrstr(str1,str2 ) Returns pointer to last occurrence of str2 in str1
strdup(string ) Duplicates the string
strset(string,‟c‟ ) Sets all character in a string to given character
strnset(string,‟c‟,n ) It sets the portion of characters in a string to given character
strtok( ) Tokenizing given string using delimiter

Pragati Engineering College (Autonomous) Page 5


Programming for Problem Solving using C (R20)
Strlen(): Gives the length of str1
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "hello world";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
OUTPUT:
Length of string str1: 11
strcmp(): strcmp() function is use two compare two strings. strcmp() function does a case sensitive
comparison between two strings. The Destination_String and Source_String can either be a string
constant or a variable.
Syntax: int strcmp(string1, string2);
 This function returns integer value after comparison.
 Value returned is 0 if two strings are equal.
 If the first string is alphabetically greater than the second string then, it returns a positive value.
 If the first string is alphabetically less than the second string then, it returns a negative value
Example:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char s1[20] = "hello";
char s2[20] = "hallo";
if(strcmp(s1,s2)==0)
{
printf("string 1 and string 2 are equal");
}
else
{
printf("string 1 and 2 are different");
}
return 0;
}
OUTPUT:
string 1 and 2 are different
strncmp:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char s1[20] = "jai";
char s2[20] = "jai ram";
if(strncmp(s1,s2,3)==0)

Pragati Engineering College (Autonomous) Page 6


Programming for Problem Solving using C (R20)
{
printf("string 1 and string 2 are equal");
}
else
{
printf("string 1 and 2 are different");
}
return 0;
}
OUTPUT: string 1 and string 2 are equal
Strcat():
#include<stdio.h>
#include<string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return0;
}
OUTPUT: Output string after concatenation: HelloWorld
Strncat():
#include<stdio.h>
#include<string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}
OUTPUT: Concatenation using strncat: HelloWorld
Strcpy():
#include<stdio.h>
#include<string.h>
int main()
{
char s1[30] = "hello";
char s2[30] = "world";
strcpy(s1,s2); //copiews s2 into s1
printf("String s1 is: %s", s1);
return 0;
}
OUTPUT: String s1 is: world
Strlwr(), strupr():
#include<stdio.h>
#include <string.h>
int main()
Pragati Engineering College (Autonomous) Page 7
Programming for Problem Solving using C (R20)
{
char s1[30] = "HELLO world";
printf("String s1 is: %s\n", s1);
printf("String s1 lower case is: %s\n", strlwr(s1));
printf("String s1 upper case is: %s\n", strupr(s1));
return 0;
}
OUTPUT: String s1 is: HELLO world
String s1 lower case is: hello world
String s1 upper case is: HELLO WORLD
Example programs for strstr(),strset(),strnset(),strchr():
#include <stdio.h>
#include <string.h>
#include<stdlib.h>
int main()
{
char s3[20]="hai";
char s4[20]="good is always good";
printf("String s3 is: %s\n", s3);
printf("String s3 with symbol * is: %s\n", strset(s3,'*'));
printf("String s4 set with upto 3 charaters with * is: %s\n",strnset(s4,'*',3));
printf("String s4 substring character o occurred is: %s\n",strchr(s4,'o'));
printf("String s4 substring string occurred is: %s\n", strstr(s4,"is"));
return 0;
}

OUTPUT: String s3 is: hai


String s3 with symbol * is: ***
String s4 set with upto 3 charaters with * is: ***d is always good
String s4 substring character o occured is: ood
String s4 substring string occured is: is always good
Some More Code Examples on String Functions:
strncmp() strcmpi()
char string1[] = "Learn C Online is agreat site"; char string1[] = “Learn C Online”;
char string2[] = "Learn C Online"; char string2[] = “LEARN C ONLINE”;
int ret; int ret;
ret=strncmp(string1, string2,7); ret=strcmpi(string1, string2);
printf("%d",ret); printf("%d",ret);
OUTPUT: OUTPUT:
0 0
strncmpi() strncpy()
char *string1 = "Learn C Online is a greatsite"; char *Destination_String="Visit ";
char *string2 = "LEARN C ONLINE";int ret; char *Source_String = "Learn C OnlineSITE";
ret=strncmpi(string1, string2,7); strncpy(Destination_String,Source_String,14);
printf("%d",ret); puts( Destination_String);
OUTPUT: OUTPUT:
0 Learn C Online

Example for String reverse without string handling functions:


Pragati Engineering College (Autonomous) Page 8
Programming for Problem Solving using C (R20)
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20],str2[20];
int i,j,len;
printf("\n enter a string:");
gets(str1);
len=0;
while(str1[len]!='\0')
len++;
for(i=len-1,j=0;i>=0;i--,j++)
{
str2[j]=str1[i];
}
str2[j]='\0';
printf("\n entered string is %s",str1);
printf("\n reverse of string is %s",str2);
return 0;
}
OUTPUT:
enter a string: satya
entered string is satya
reverse of string is aytas
String Concatenation:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20],str2[20];
int i,j,len;
printf("\n enter a string:");
gets(str1);
printf("\n enter a string:");
gets(str2);
len=0;
while(str1[len]!='\0')
len++;
for(i=len,j=0;str2[j]!='\0';i++,j++)
{
str2[j]='\0';
str1[i]=str2[j];
}
printf("\n concatenation is %s",str1);
return 0;
}
}
OUTPUT: enter a string: jai
enter a string: raj
concatenation is jairaj

Pragati Engineering College (Autonomous) Page 9


Programming for Problem Solving using C (R20)
string comparison:
#include <stdio.h>
#include <string.h>
int main()
{
char Str1[100], Str2[100];
int result, i;
printf("\n Please Enter the First String : ");
gets(Str1);
printf("\n Please Enter the Second String : ");
gets(Str2);
for(i = 0; Str1[i] == Str2[i] && Str1[i] == '\0'; i++);
if(Str1[i] < Str2[i])
{
printf("\n str1 is Less than str2");
}
else if(Str1[i] > Str2[i])
{
printf("\n str2 is Less than str1");
}
else
{
printf("\n str1 is Equal to str2");
}

return 0;
}
OUTPUT 1: Please Enter the First String : cat
Please Enter the Second String : dog
str1 is Less than str2
OUTPUT 2: Please Enter the First String : John
Please Enter the Second String : Ani
str2 is Less than str1
OUTPUT 3: Please Enter the First String : John
Please Enter the Second String : John
str2 is equal to str1
Array of strings: For lists of character strings, such as the list of names of students in a class, a list
of names of employees in an organization, a list of places, etc. A list of names can be treated as a
table of string. To store the entire list we use a 2D array of strings in C language.
The array of characters is called a string. “Hi”, “Hello”, and etc are the examplesof String. Similarly,
the array of Strings is nothing but a two-dimensional (2D) array of characters. To declare an array
of Strings in C, we must use the char datatype.
Example of two dimensional characters or the array of Strings:
char language[5][10]={"Java","Python","C++","HTML","SQL"};
Declaration of the array of strings
syntax:- char string-array-name[row-size][column-size];

Here the first index (row-size) specifies the maximum number of strings in the array, and the
Pragati Engineering College (Autonomous) Page 10
Programming for Problem Solving using C (R20)
second index (column-size) specifies the maximum length of everyindividual string.
For example, char language[5][10];
In the “language” array we can store a maximum of 5 Strings and each String can have a maximum
of 10 characters.
In C language, each character take 1 byte of memory. For the “language” array it will allocate 50
bytes (1*5*10) of memory. Where each String will have 10 bytes(1*10) of memory space.
Initialization of array of strings : Two dimensional (2D) strings in C language can be directly
initialized as shownbelow:
char language[5][10]={"Java","Python","C++","HTML","SQL"};
charlargestcity[6][15]={"Tokyo","Delhi","Shanghai","Mumbai","Beijing","Dhaka"};

The two dimensional (2D) array of Strings in C also can be initialized as,
char language[5][10]=
{
{'J','a','v','a','\0'},
{'P','y','t','h','o','n','\0'},
{'C','+','+','\0'},
{'H','T','M','L','\0'},
{'S','Q','L','\0'}
};
Since it is a two-dimension of characters, so each String (1-D array of characters)must end with null
character i.e. „\0‟

J a v a \0
P y t h o n \0
C + + \0
H T M L \0
S Q L \0

Note 1: the number of characters (column-size) must be declared at the time of the initialization of
the two-dimensional array of strings.
char language[ ][10] = {"Java", "Python", "C++", "HTML", "SQL"};// it is valid
The following declarations are invalid.
char language[ ][ ] = {"Java", "Python", "C++", "HTML", "SQL"}; // invalid
char language[5][ ] = {"Java", "Python", "C++", "HTML", "SQL"}; // invalid
Note 2:- Once we initialize the array of String then we can‟t directly assign a newString.
char language[5][10] = {"Java", "Python", "C++", "HTML", "SQL"};
// we can't directly assign a new String
language[0] = "Kotlin"; // invalid
strcpy(language[0], "Kotlin"); // valid
Example program for array of strings:
#include<stdio.h>
int main()
{

Pragati Engineering College (Autonomous) Page 11


Programming for Problem Solving using C (R20)
// declaring and initializing 2D String
char language[5][10] ={"Java", "Python", "C++", "HTML", "SQL"};
printf("Languages are:\n"); // Displaying strings
for(int i=0;i<5;i++)
puts(language[i]);
return 0;
}
OUTPUT: Languages are:
Java
Python
C++
HTML
SQL

Example for array of strings:


#include<stdio.h>
int main()
{
char name[10][20];
int i,n;

printf("Enter the number of names : ");


scanf("%d",&n);

// reading string from user


printf("Enter %d names:\n",n);
for(i=0; i<n; i++)
scanf("%s[^\n]",name[i]);

// dispaying strings
printf("\nEntered names are:\n");
for(i=0;i<n;i++)
puts(name[i]);
return 0;
}
OUTPUT:
Enter the number of names : 2
Enter 2 names: sai ram
Entered names are: sai ram
String/Data conversion: String/Data Conversion A common set of applications format data by
either converting a sequence of characters into corresponding data types or vice versa. Two such
applications areparsing and telecommunications.
Sscanf() is a one-to-many function. It splits one string into many variables.
Sprint() is a many to one function. It joints many pieces of data into one string

Pragati Engineering College (Autonomous) Page 12


Programming for Problem Solving using C (R20)

Fig: Sscanf() operation

Fig: Sprint() operation

Sscanf()
In this example, we are going to use scanf function to read(linearly) the multiple values present in a
char[] array and store each value in a matching variable using a matching format specifier within
sscanf() function.

#include<stdio.h>
int main()
{
char ar[20] = "PPSC M 90 9.99";
char str[10];char ch;
int i;
float f;

/* Calling sscanf() to read multiple values from a char[] array and store eachvalue in matching
variable */
sscanf(ar, "%s %c %d %f", &str, &ch, &i, &f);
printf("The value in string is : %s \n", str);
printf("The value in char is : %c\n ", ch);
printf("The value in int is : %d\n ", i);
printf("The value in float is : %f \n", f);
return 0;
}
OUTPUT: The value in string is : PPSCThe value in char is : M
The value in int is : 90
The value in float is : 9.990000

Sprintf():
In this example, we are going to use sprintf() function, which reads one or multiple values specified
with their matching format specifiers and store these values in a char[] array.
#include<stdio.h>
int main()
{
char target[20];

Pragati Engineering College (Autonomous) Page 13


Programming for Problem Solving using C (R20)
char name[10] = "samvidh";
char gender = 'M';
int age = 20;
float height = 1.70;
printf("The name is : %s\n", name);
printf("The gender is : %c\n", gender);
printf("The age is : %d\n", age);
printf("The height is : %f\n", height);

/* Calling sprintf() function to read multiple variables and store their valuesin a char[] array i.e.
string.*/
sprintf(target, "%s %c %d %f\n", name, gender, age, height);
printf("The value in the target string is : %s\n", target);
return 0;
}
OUTPUT: The name is : samvidh
The gender is : MThe age is : 20
The height is : 1.700000
The value in the target string is : samvidh M 20 1.700000

STRUCTURES: A structure is a collection of variables of different data types that are stored
consequently in memory locations logically grouped together and referred under a single name.
Structure is a heterogeneous collection of data elements. Structure is a user-defined datatype. User-
defined data type also called as derived data type why because we derived it from the
primary/basic datatypes.
Significance of Structure: A simple variable can store one value at a time. An array can store a
number of variables of the same type. For example, marks obtained by a student in five subjects can
be stored in an array marks[5]. Then marks[0], marks[1], etc..., will store student information like
the marks obtained in various five subjects. Suppose we want to store student information in array
like name, address, htno, marks obtained. We cannot store this information in an array because
name, htno, address are of character type and marks obtained is of integer type. So Arrays are used
to store homogeneous data. To store heterogeneous data elements in a single group, C provides a
facility called structure.
Differences between array and structure: Arrays are used to store homogeneous data elements in
single group Structures are used to store heterogeneous data elements in a single group
Declaration of Structure using struct keyword
struct structure_name
{
data_type member_variable_1;
data_type member_variable_2;
……
data_type member_variable_N;
};
The variables declared inside the structure are known as members of the structure.

Note: The members of the structure may be any of the common data type, pointers, arrays or even
the other structures. Structure definition starts with the open brace({) and ends with closing brace(})
followed by a semicolon (;).

Declaring structure variable


Pragati Engineering College (Autonomous) Page 14
Programming for Problem Solving using C (R20)
Structures declaration:
As stated earlier, the compiler does not reserve memory any memory when structure is defined. To
store members of structures in memory, we have to define the structure variables. The structure
variables may be declared in thefollowing ways:
1.In the structure declaration
2.Using the structure tag

In the structure declaration, The structure variable can be declared after the closing brace (}).
Following example shows this.
struct date
{
int day; int month;
int year;
}dob, doj;

Here date is the structure tag, while dob and doj are variables type date.
Using the structure tag: The variables of structure may also be declared separately by using the
structure tag as shown below:
struct date
{
int day;
int month;int year;
};
struct date dob,doj;

structure example 1:
#include<stdio.h>
#include <string.h>
struct student
{
int roll_no;
char name[30];
}s;
void main( )
{
s.roll_no = 1;
strcpy(s.name, "sai");
printf( "Student Enrollment No. : %d\n", s.roll_no);
printf( "Student Name : %s\n", s.name);
}
OUTPUT: Student Enrollment No. : 1
Student Name : sai

Structure example program 2:


#include<stdio.h>
struct student
{
char name[30];
int htno;
char gender;
int marks;
char address[30];
Pragati Engineering College (Autonomous) Page 15
Programming for Problem Solving using C (R20)
};
int main()
{
struct student st={"SAI",999,'M',90,"hyd"};
printf("Student Name:%s\n",st.name);
printf("Roll No:%d\n",st.htno);
printf("Gender:%c\n",st.gender);
printf("Marks obtained:%d\n",st.marks);
printf("Address:%s\n",st.address);
return 0;
}
Student Name: SAI
Roll No:999
Gender:M
Marks obtained:90
Address:hyd

Nested Structure in C : One structure with in another structure is called Nested Structure.
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 //nested structure


#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};

struct employee
{
char name[20];
struct address add;
};
void main ()
{
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.add.pin,
emp.add.phone);
}
OUTPUT: Enter employee information? sai
vijayawada
123123
1234567890
Printing the employee information....
name: sai
Pragati Engineering College (Autonomous) Page 16
Programming for Problem Solving using C (R20)
City: vijayawada
Pincode: 123123
Phone: 1234567890

EXAMPLE 2: NESTED STRUCTURES:


#include <stdio.h>
#include <string.h>
struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
percentage;
// structure within structure
struct student_college_detailclg_data;
}stu_data;
int main()
{
struct student_detailstu_data = {1, "sai", 90.5, 71145,"PRAGATI ENGINEERING
COLLEGE"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);
printf(" College Id is: %d \n", stu_data.clg_data.college_id);
printf(" College Name is: %s \n",stu_data.clg_data.college_name);
return 0;
}
OUTPUT: Id is: 1
Name is: sai
Percentage is: 90.500000
College Id is: 71145
College Name is: PRAGATI ENGINEERING COLLEGE

Array of structures : An array of structures in C can be defined as the collection of multiple


structures variables where each variable contains information about different entities. The array of
structures in C are used to store information about multiple entities ofdifferent data types. The array
of structures is also known as the collection of structures.

EXAMPLE
#include<stdio.h>
#include <string.h>
struct student
{
int rollno;
char name[10];
};
int main()
{
Pragati Engineering College (Autonomous) Page 17
Programming for Problem Solving using C (R20)
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnterRollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
OUTPUT: Enter Records of 5 students
Enter Rollno:1
Enter Name:ravi
Enter Rollno:2
Enter Name:ram
Enter Rollno:3
Enter Name:satya
Enter Rollno:4
Enter Name:kiran
Enter Rollno:5
Enter Name: srija
Student Information List:
Rollno:1, Name:ravi
Rollno:2, Name:ram
Rollno:3, Name:satya
Rollno:4, Name:kiran
Rollno:5, Name:srija

Union: A Union is a user defined data type like structure. The union groups logically related
variables into a single unit. In structure each member has its own memory location; whereas
the members of union has the same memory location. We can assign values to Only one member at
a time can be assigned with values.

When a union is declared, compiler allocates memory locations to holdlargest data type member in
the union. So, union is used to save memory. Union is useful when it is not necessary to assign the
values to all themembers of the union at a time.

Union can be declared as: The union keyword is used to define the union. Let's see the syntax to
define unionin c.

union union_name
{
data_type member1;
data_type member2;
. .
Pragati Engineering College (Autonomous) Page 18
Programming for Problem Solving using C (R20)
data_type memeberN;
};
Example:
union employee
{
int id;
char name[50];
float salary;
};

Union example program:


#include <stdio.h> #include <string.h>
union employee
{
int id;
char name[50];
}e1; //declaring e1 variable for union
int main( )
{
//store first employee informatione1.id=1;
strcpy(e1.name, "jai");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
OUTPUT:
employee 1 id : 6906195
employee 1 name : jai

Note: According to Union id gets garbage value because name has large memorysize. So only name
will have actual value.

Union example 2:
#include<stdio.h>
union student
{
char name[15];
int age;
};
int main()
{
union student st;
printf("Enter student name:");
scanf("%s",st.name);
printf("Student Name: %s & Age= %d\n",st.name,st.age);
st.age=20;
printf("Student Name: %s, age= %d\n",st.name,st.age);
}
OUTPUT: Enter student name: Jai
Student Name: jai & Age= 20
Student Name: Jai, age= 20
Pragati Engineering College (Autonomous) Page 19
Programming for Problem Solving using C (R20)

NOTE: First time union member name has a value which is inputted through the keyboard. So
name is displayed. Next time we were assigned a values to age, union will lost the value in member
name, so this time only student‟s ageis displayed.

We can access only one member of union at a time. We can‟t access all member values at the same
time in union. But, structure can access all member values at the same time. This is because, Union
allocates one common storage space for all its members. Where as Structure allocates storage space
for all its members separately.

Difference between structure and union :


S.No. Structure Union
1. Stores heterogeneous data Stores heterogeneous data
Members are stored separately in
2. Members are stored in same memorylocation.
memory locations.
In structures all the members areavail- In union only one member isavailable at a
3.
able. time.
Occupies more memory whencompared Occupies less memory whencompared
4.
to union with structure.
Size of the structure is the totalmemory Size of the union is the size of thelargest
5.
space required by its members data type member in the union.
struct student union student
{ {
char name[15]; char name[15];
6.
int age; int age;
}; };

fig: Storage in structure

fig: Storage in union


Example program with memory allocation of structure and union:
struct Employee
{
int age;
float Salary;
};
union Person
{
int age;
float Salary;
};

Pragati Engineering College (Autonomous) Page 20


Programming for Problem Solving using C (R20)
int main()
{
struct Employee emp1;union Person Person1;
printf(" The Size of Employee Structure = %d\n", sizeof (emp1) );
printf(" The Size of Person Union = %d\n", sizeof (Person1));
return 0;
}
OUTPUT: The Size of Employee Structure = 8
The Size of Person Union = 4
C Typedef : The typedef is a keyword used in C programming to provide some meaningful names
to the already existing variable in the C program. It behaves similarly as we define the alias for the
commands. In short, we can say that this keyword is used toredefine the name of an already existing
variable.
Syntax of typedef:
typedef <existing_name> <alias_name>;

In the above syntax, 'existing_name' is the name of an already existing variable


while 'alias name' is another name given to the existing variable.
Example
typedef unsigned int unit;
/*In the above statements, we have declared the unit variable of type unsigned int by using a
typedef keyword.
Now, we can create the variables of type unsigned int by writing the followingstatement:*/
unit a, b;
//instead of writing: unsigned int a, b;
TYPEDEF EXAMPLE 1:
#include <stdio.h>
int main()
{
typedef unsigned int unit;
unit i,j;
i=10; j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
return 0;
}
OUTPUT: Value of i is :10
Value of j is :20
TYPEDEF EXAMPLE 2:
#include <stdio.h>
int main()
{
typedef int rectangle; //creating new data type name rectangle using typedef
rectangle length, breadth, area;//declaring variables using new data type namerectangle
printf("\nEnter length and breath of the rectangle ");
scanf("%d %d ", &length, &breadth);
area = length * breadth;
printf("\nArea = %d ", area);

Pragati Engineering College (Autonomous) Page 21


Programming for Problem Solving using C (R20)
return 0;
}
OUTPUT: Enter length and breadth of the rectangle 5 2
Area=10

Example of Typedef with structures:


#include <stdio.h>
typedef struct student
{
char name[20];
int age;
}stud;
int main()
{
stud s1;
printf("Enter the details of student s1: ");
printf("\nEnter the name of the student:");
scanf("%s",&s1.name);
printf("\nEnter the age of student:");
scanf("%d",&s1.age);
printf("\n Name of the student is : %s", s1.name);
printf("\n Age of the student is : %d", s1.age);
return 0;
}
OUTPUT: Enter the details of student s1:
Enter the name of the student: Peter
Enter the age of student: 28
Name of the student is : Peter
Age of the student is : 28

Enumerations (enum): The enum in C is also known as the enumerated type. It is a user-defined
data type that consists of integer values, and it provides meaningful names to these values.

An enum is a keyword; it is a user defined data type. All properties of integer are applied on Enu-
meration data type so size of the enumerator data type is2 byte. It works like the Integer. It is used
for creating a user defined data type of integer. Using enum we can create sequence of integer
constant value.

Syntax: enum tagname {value1, value2, value3,.};

In above syntax enum is a keyword. It is a user defined data type. tagname is our own variable.
tagname is any variable name. value1, value2, value3,. are

creating set of enum values.


It is start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the
Pragati Engineering College (Autonomous) Page 22
Programming for Problem Solving using C (R20)
list. If constant one value is not initialized then by default sequence will be start from zero and next
to generated value should be previous constant value one.
Example:
enum week {sun, mon, tue, wed, thu, fri, sat};enum week today;
In above code first line is creating user defined data type called week.
week variable have 7 value which is inside { }braces.
today variable is declare as week type which can be initialize any data orvalue among 7 (sun, mon,.
).

Enum example:
#include <stdio.h>
enum days{sunday=1, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
int days;
printf("enter a day:");
scanf("%d",&days);
switch(days)
{
case sunday: printf("Today is sunday");
break;
case monday: printf("Today is monday");
break;
case tuesday: printf("Today is tuesday");
break;
case wednesday: printf("Today is wednesday");
break;
case thursday: printf("Today is thursday");
break;
case friday: printf("Today is friday");
break;
case saturday: printf("Today is saturday");
break;
}
return 0;
}
OUTPUT: enter a day: 5
Today is Thursday

Enum example 2(with variable declaration)


#include <stdio.h>
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday,Saturday};
int main()
{
enum weekdays w; // variable declaration of weekdays typew=Monday;
// assigning value of Monday to w.
printf("The value of w is %d",w);
return 0;
}
OUTPUT: The value of w is 2

Pragati Engineering College (Autonomous) Page 23


Programming for Problem Solving using C (R20)
UNIT-III
PPSC PREVIOUS QUETIONS
1.a) Write a C program to read N integers into an array A and to find (i)sum of odd numbers (ii)
sum of even numbers
b) Explain the difference between array and structures

2. a) Write a C program to find the largest element and smallest element in an array.
b) Write a C program to concatenate two strings without using built-in function.

3.a) What is an array? How a single dimension and two dimension arrays are declared and
initialized?
b) Write a C program to search an integer from the given array of integers

4..a) Define string. How string is declared functions with an example and initialized? Explain string
input/output.
b) Write a C program to copy a string to another string.

5.a Explain the declaration and initialization of one dimensional and two dimensional arrays with
an example.
b) Distinguish between structure and union.

6. a) Write a C program to perform matrix multiplication.


b) Explain about any four string handing functions.

7.a) Write a C program to addition of two matrices.


b) Explain any three string handling functions available in C.

8.a)Define Structure. Illustrate about nested structure with an example.


b) Discuss about typedef with suitable example.

9.a.What is an Array? How do you declare an array? Explain various types of array with examples.
b) What is a string? Explain any four string handling functions.

10. a) Write a C Program to find number of characters in a given string without using library
function.
.b) Write a program to find the smallest of three numbers using structures.

Assignment 3
Bloom‟s
Q.No. Questions CO
Taxonomy Level
SET - 1
Define string. How string is declared functions with an example
1 K2 CO3
and initialized? Explain string input/output.
2 Distinguish between structure and union. K3 CO3

SET - 2

1 Explain any five string handling functions K2 CO3

2 Discuss about typedef with suitable example. K3 CO3

Pragati Engineering College (Autonomous) Page 24


Programming for Problem Solving using C (R20)
SET - 3

1 Define Structure. Illustrate structure with an example K2 CO3

2 Write a C program to copy a string to another string. K3 CO3

Pragati Engineering College (Autonomous) Page 25

You might also like