PPSC Unit 3 Part B
PPSC Unit 3 Part B
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.
scanf() This function is used to read one or multiple inputs from the user at the console.
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;
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
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()
{
// 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
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];
/* 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 (;).
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
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.
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
#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;
};
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.
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.
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
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
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.
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