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

POP Unit 4

Uploaded by

rottenpotato404
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

POP Unit 4

Uploaded by

rottenpotato404
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

PRINCIPLES OF PROGRAMMING

IN C
22CS2ESPOP - UNIT 4
Prof. SNEHA S BAGALKOT
Assistant Professor, Dept. of CSE
UNIT – 4: Strings and Structures

▪Strings: Introduction
▪Operations on Strings (Length of a String,
▪Converting Lowercase to Uppercase and Vice Versa
▪String Concatenation, String Comparison)
▪Example Programs
Strings: Introduction
• A string is a null-terminated character array.
• Declaration Syntax: char str[size];
• Example: char str[] = “HELLO”; H E L L O \0
• Char str[]=“H”; H \0
• Char ch=‘H’; H
• Char str[]=“ ”; \0
• The name of the character array (or the string) is a pointer to the
beginning of the string.
• If we declare str as, char str[5] = “HELLO”;
• The size of the string should be equal to maximum number of
characters in the string plus one.
Introduction (Contd..)
• Similar to arrays, subscripts are used to access the elements of the
character array. The subscript starts with a zero.
• The other way to initialize a string :
char str[ ]={‘H’,’E’,’L’,’L’,’O’,’\0’};
• We can also declare a string with size much larger than the number of
elements that are initialized.
• char str[10]=”HELLO”;
H E L L O \0 \0 \0 \0 \0 \0

• Consider the following declaration:


char str[3];
str = “HELLO”; //Error
Reading Strings
Strings can be read from the user by using three ways
• using scanf() function
scanf(“%s”, str);
• using gets() function
gets(str);
• using getchar(), getch() or getche() function repeatedly
i=0;
ch = getchar(); //Get a character
while(ch!=’\n’)
{
str[i] = ch; //Store the read character in str
i++;
ch = getchar(); //Get another character
}
str[i] = ‘\0’; //terminate str with null character
• In this method, mandatory to append with a null character.
Writing Strings
The string can be displayed on screen using three ways
• using printf() function
printf(“%s”, str);
• using puts() function
puts(str);
• using putchar()function repeatedly
i=0;
while(str[i] != '\0’)
{
putchar(str[i]); //print the character on the screen
i++;
}
Writing Strings
#include <stdio.h>
int main()
{
int i, p;
char str[] = "HELLO";
printf("\n%s",str); // output HELLO
printf("\n%5s",str); // output HELLO
printf("\n%.5s",str); // output HELLO
printf("\n%.2s",str); // output HE
printf("\n%2.3s",str); // output HEL
printf("\n%-2.3s",str); // output HEL
printf("\n%.4s",str); // output HELL
printf("\n%5.3s",str); // output --HEL
printf("\n%-5.3s",str); // output HEL--
return 0;
}
Write a program to print the #include <stdio.h>
following pattern. main()
H {
HE int i, p;
HEL char str[] = "HELLO";
HELL
HELLO for(i=0;i<5;i++)
HELLO
{
p = i+1;
HELL
printf("\n %-5.*s", p, str);
HEL
}
HE
for(i=4;i>=0;i--)
H
{
p = i+1;
Note:
printf("\n %-5.*s", p, str);
printf(“%*.*s”, w, p, str); }
printf() will print first p return 0;
characters of str in the field }
width of w.
Operations on Strings

• Finding the length of a String

• Converting characters of a String into Uppercase

• Converting characters of a String into Lowercase

• Concatenating two Strings to form a new string

• Comparing two strings


Finding the length
Write a program to find the length
of a String of a string.

Algorithm to calculate the length #include <stdio.h>


int main()
of a string
{
char str[100], i = 0, length;
Step 1: [INITIALIZE] SET I = 0 printf("\n Enter the string :");
Step2:Repeat Step3 while STR[I]!='\0' gets(str);
Step 3: SET I = I + 1 while(str[i] != '\0')
[END OF LOOP] i++;
Step 4: SET LENGTH = I length = i;
Step 5: END printf("\n The length of the
string is : %d", length);
return 0;
}
Converting characters of a String into Uppercase
Algorithm to convert the characters of string into upper case
Step1: [Initialize] SET I=0
Step 2: Repeat Step 3 while STR[I] != ‘\0’
Step 3: IF STR[I] >= ‘a’ AND STR[I] <= ‘z’
SET Upperstr[I] = STR[I] - 32
ELSE
SET Upperstr[I] = STR[I]
[END OF IF]
[END OF LOOP]
Note:
Step 4: SET Upperstr[I] = ‘\0’ ASCII Code
Step 5: EXIT For A-Z - 65 to 91
For a-z - 97 to 123
WAP to convert characters of a string to uppercase.
#include <stdio.h>
int main() upper_str[j] = '\0';
{ printf("\n The string converted
char str[100], upper_str [100]; into upper case is : ");
int i = 0, j = 0; puts(upper_str);
printf("\n Enter the string:"); return 0;
gets(str); }
while(str[i] != '\0')
{
if(str[i] >= 'a' && str[i] <= 'z')
upper_str[j] = str[i] -32;
else
upper_str[j] = str[i];
i++;
j++;
}
Ref : Table of ASCII values
Converting characters of a String into Lowercase
Algorithm to convert the characters of string into
lower case

Step1: [Initialize] SET I=0


Step 2: Repeat Step 3 while STR[I] != ‘\0’
Step 3: IF STR[1] > =‘A’ AND STR[I] <= ‘Z’
SET Lowerstr[I] = STR[I] + 32
ELSE
SET Lowerstr[I] = STR[I]
[END OF IF]
SET I = I +1
[END OF LOOP]
Step 4: SET Lowerstr[I] = ‘\0’
Step 5: EXIT
Write a program to convert characters
#include <stdio.h>
of a string into lower case.
int main()
lower_str[j] = '\0’;
{
printf("\n The string converted into
char str[100], lower_str [100];
lower case is : ");
int i = 0, j=0;
puts(lower_str);
printf("\n Enter the string :");
return 0;
gets(str);
}
while(str[i] != '\0')
{
if(str[i]>='A'&& str[i]<='Z')
lower_str[j]= str[i] + 32;
else
lower_str[j] = str[i];
i++;
j++;
}
Concatenating two Strings to form a
new string
Algorithm to Concatenate Two Strings

1. Initialize I =0 and J=0


2. Repeat step 3 to 4 while I <= LENGTH(str1)
3. Set new_str[J] = str1[I]
4. Set I =I+1 and J=J+1
[END of step2]
5. SET I=0
6. Repeat step 6 to 7 while I <= LENGTH(str2)
7. Set new_str[J] = str1[I]
8. Set I =I+1 and J=J+1
[END of step5]
9. SET new_str[J] = ‘\0’
10. EXIT
WAP to concatenate two Strings.
#include <stdio.h> i=0;
int main() while(str2[i] != '\0')
{ {
char str1[100], str2[100],str3[100]; str3[j] = str2[i];
int i=0, j=0;
i++;
printf("\n Enter the first string:");
j++;
gets(str1);
printf("\n Enter the second string:"); }
gets(str2); str3[j] = '\0';
while(str1[i] != '\0') printf("\n The concatenated string is:");
{ puts(str3);
str3[j] = str1[i]; return 0;
i++; }
j++;
}
Comparing two strings
Note:
Algorithm to compare two strings i) S1 and S2 are equal
Step1: [Initialize] SET I=0, SAME =0 ii) S1 > S2 , when in dictionary order S1 will come
Step 2: SET Len1=Length(STR1),
after S2
Len2=Length(STR2)
Step 3: IF len1 != len2, then iii) S1 < S2 , when in dictionary order S1 precedes S2
Write “Strings Are Not Equal”
ELSE Step 4: IF SAME = 0, then
Repeat while I<Len1 IF STR1[I] > STR2[I], then
IF STR1[I] == STR2[I] Write “String1 is greater
SET I = I + 1 than String2”
ELSE ELSE IF STR1[I]<STR2[I],then
Go to Step 4 Write “String2 is greater
[END OF IF] than String1”
[END OF LOOP] [END OF IF]
IF I = Len1, then [END OF IF]
SET SAME =1 Step 5: EXIT
Write “Strings are equal”
[END OF IF]
Write a program to compare two strings.
#include <stdio.h>
#include <string.h>
if(i==len1)
{ same=1;
main()
printf("\n The two strings are equal");
{
}
char str1[50], str2[50];
}
int i=0, len1 = 0, len2 = 0, same = 0;
if(len1!=len2)
printf("\n Enter the first string : ");
printf("\n The two strings are not equal");
gets(str1);
if(same == 0)
printf("\n Enter the second string : ");
{
gets(str2);
if(str1[i]>str2[i])
len1 = strlen(str1);
printf("\n String1 is greater than string2");
len2 = strlen(str2);
else if(str1[i]<str2[i])
if(len1 == len2)
printf("\n String2 is greater than string1");
{ while(i<len1)
}
{ if(str1[i] == str2[i])
return 0;
i++;
}
else break;
}
PASSING STRINGS TO FUNCTIONS
Basic rules are:
• The string to be passed must be declared as a formal argument of the
function when it is defined.
EX: void display(char item_name[])
{
......
......
}
• The function prototype must show that the argument is a string. Ex: void
display(char str[])
• A call to the function must have a string array name without subscripts as
its actual argument.
Ex: display(names);
• Where names is a properly declared string in the calling function.
#include <stdio.h>

void display(char a[])


{
int x = 0;

while( a[x] )
{ Output:
putchar( a[x]);
x++; This is CG Section, BMSCE!
}
putchar('\n');
}

int main()
{
char string[] = "This is CG Section, BMSCE!";

display(string);

return(0);
}
PART B: LAB PROGRAM 3

Write functions to implement String


operations such as concatenation and String
length without using built-in functions.
UNIT – 4: Strings and Structures

▪Structures: Introduction
▪Arrays of Structures
▪Nested Structures
▪Example Programs
Structures: Introduction
• Structure is a user-defined data type that can store related information.

• Major difference between a structure and an array is that an array


stores the information of the same data type whereas, a structure
stores information of different data types.

• A structure is, therefore, a collection of variables under a single name.


Introduction
• A structure is a collection of dissimilar data elements which belong to
a common entity
• Each variable in the structure is called as a “data member” of the
structure.
• Data members may belong to any data type.
• Note:
• A structure must end with semicolon(;)
• struct : struct is the keyword used to represent structures
Structure Declaration
Syntax of structure declaration:
struct struct_name
{
datatype var_name;
datatype var_name;
................
};
Example of a structure declaration:
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
Declaring a variable of the structure
• In order to use the structure we have to declare the variable of a structure.

Two ways of declaring the variable of the structure are:


1) struct employee 2) struct employee
{ {
int id; int id;
char name[10]; char name[10];
float salary; float salary;
}; }emp1,emp2;
struct employee emp1;

• Note: memory is allocated when the variable of the structure is declared.


Memory allocation for a structure variable
Typedef declarations

• Typedef is a keyword that enables the programmer to create a new


datatype name for an existing datatype.
• By using typedef, no new data is created but an alternate name is given to a
known datatype.
Syntax for using typedef is:
typedef existing_datatype new_datatype
• Typedef statement doesn’t occupy any memory, it simply defines a new
type.
Example: typedef int INTEGER;
INTEGER num=6;
Typedef declarations
• When we precede a struct with a typedef, then struct variable becomes
a new type.
typedef struct student
{
int roll_no;
char name[20];
};
• We can straight away declare the variable of this new datatype student
as:
student stud1;
Initializing of structures
Syntax of initializing a structure: Example:
struct struct_name struct student
{ {
datatype member_name1; int r_no;
char name[20];
datatype member_name2;
float fees;
}struct_var={constant1,constant2,....};
}stud1={123,”RAJU”,25000};
OR OR
struct struct_name struct student
{ {
datatype member_name1; int r_no;
datatype member_name2; char name[20];
}; float fees;
struct struct_name struct_var = { constant1 };
,Constant2,....}; struct student stud1={123,”RAJU”,25000};
Accessing the members of a structure
• A structure member variable is generally accessed by a ‘.’(dot)operator.
Syntax of accessing a structure or a member of a structure:
Struct_var.member_name
Example(direct initialization)
• stud1.r_no=123;
• stud1.name=“RAHUL”;
• stud1.fees=66000;
Taking the values from the user input for variable stud1:
• scanf(“%d”,&stud1.r_no);
• scanf(“%f”,&stud1.fees);
• scanf(“%s”,stud1.name);
To print the values of structure variable stud1:
• printf(“%f”,stud1.fees);
Write a C Program to define a structure to store book
information with member elements as follows:
To store author name as char array
To store book title as char array
To store year as integer
To store price as float

1) Initialize the values of each struct member for 1


book record(complete initialization). Display the
values.
2) Partially initialize the members of the structure
struct book
{
char author_name[50];
char book_title[50];
float price;
int year;
};
Complete Initialization

void main()
{
struct book b1={"Reema Thareja", "Programming in C", 516.6, 2016};
printf("\n Book Author is: %s",b1.author_name);
printf("\n Book Name is: %s",b1.book_title);
printf("\n Book price is: %f",b1.price);
printf("\n Year of publication is: %d",b1.year);
}
Partial initialization
void main()
{
struct book b1={"Reema Thareja", "Programming in C"};
printf("\n Book Author is: %s",b1.author_name);
printf("\n Book Name is: %s",b1.book_title);
printf("\n Book price is: %f",b1.price);
printf("\n Year of publication is: %d",b1.year);
}
Write a C Program to define a structure to store book
information with member elements as follows:
To store author name as char array
To store book title as char array
To store year as integer
To store price as float

Initialize the structure members by taking input from


user. Do this for 1 book
void main()
{
struct book b1;
printf("\n enter name of the author");
scanf("%s",b1.author_name);
printf("\n enter the Book Title");
scanf("%s",b1.book_title);
printf("\n enter the price");
scanf("%f",&b1.price);
printf("\n enter publication year");
scanf("%d",&b1.year);
printf("\n Book Author is: %s",b1.author_name);
printf("\n Book Name is: %s",b1.book_title);
printf("\n Book price is: %f",b1.price);
printf("\n Year of publication is: %d",b1.year);
}
Write a C Program to define a structure to store book
information with member elements as follows:
To store author name as char array
To store book title as char array
To store year as integer
To store price as float

Initialize the structure members by taking input from


user. Do this for 2 books

2 July 2024 CSE, BMSCE 44


Copying structures
• We can assign a structure to another structure of the same type.
• For example, if we have two structure variables stud1 and stud2
of type struct student,
Struct student stud1= { 01, ”RAHUL”,”BCA” ,45000};
Struct student stud2;
• Then we can copy the member variables of stud1 to stud2 as:
Struct student stud2 = stud1;
Demonstrate copying one
structure to another [Ex: book]
//Hint
void main()
{
struct book b1;
struct book b2;
b2=b1;
Comparing structures
• C doesn’t permit comparison of 1 structure variable with another.

if(stud1 > stud2) this is wrong

• But individual members of 1 structure can be compared with an


individual member of another structure.

Example: comparison of fees of 2 students:

if (stud1.fees > stud2.fees) //this is right


Write a C program using structure to read and
display student information of 3 students

The structure should have following member


elements

USN of the student: Character array


Name of student: Character array
Marks of the student: Floating point number
Arrays of Structures
ARRAY OF STRUCTURES
We can declare an array of structures, each element of the array representing a
structure variable.
Example:
struct book_bank {
char author[50];
char title[50];
int year;
float price;
};
struct book_bank book[100];

In the above example an array called book is defined, that consist of 100 elements.
Each element is defined to be that of type struct bookbank.
Question
Write a C program using structures to read and display the information
of N students.
The structure should have following member elements
USN of the student: Character array
Name of student: Character array
Marks of the student: Floating point number
Sample Input and Output
Enter N value: 2
Enter USN: 1BM18CS001
Enter Name: Aditya
Enter marks: 40
Enter USN: 1BM18CS002
Enter Name: Bharath
Enter marks: 38

Displaying Information:
USN: 1BM18CS001
Name: Aditya
Marks: 40.00
USN: 1BM18CS002
Name: Bharath
Marks: 38.00
#include<stdio.h>
void main()
{
struct student {
char usn[15];
char name[25];
float marks;
};
struct student s[10];
int i, n;
printf("Enter N value: ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Enter USN: ");
scanf("%s", s[i].usn);
printf("Enter Name: ");
scanf("%s", s[i].name);
printf("Enter marks: ");
scanf("%f", &s[i].marks);
}
printf("\n Displaying Information:\n");
for(i = 0; i<n; i++)
{
printf("USN: %s\n", s[i].usn);
printf("Name: %s\n", s[i].name);
printf("Marks: %f\n", s[i].marks);
}
}
Nested Structures
STRUCTURES WITHIN STRUCTURE
A structure within a structure is called Nested Structure
Syntax:
struct struct_name {
datatype var1;
datatype var2;
Note:
struct struct_name1 {
By using outer structure variable only, it is
datatype var3; possible to access the variables of inner
datatype var4; structure.
}variable1; outer_struct . inner_struct . datamember;
}variable;
struct struct_name variable;
STRUCTURES WITHIN STRUCTURE
Example:
struct bookbank {
char author[50]; It can be accessed as:
char title[50]; book. author
struct bookbank1 { book. title
int year; book. details. year
float price; book. details. price

}details;
}book;
Write a program to demonstrate nested structure.
Create a structure which holds student roll number ,
name and course. Let name be a structure which has
members first name middle name and last name.
Read and display 1 student information
#include<stdio.h>
struct student
{
int r_no;
struct NAME
{
char f_name[20];
char m_name[20];
char l_name[20];
}n;
char course[20];
};
void main()
{
struct student s;
printf("enter roll number");
scanf("%d", &s. r_no);
printf("enter name of the student");
scanf("%s", s. n. f_name);
printf("\n student roll and name is \n%d\n%s", s. r_no, s. n. f_name);
}
Write a program to demonstrate nested structure.
Create a structure which holds student roll number ,
name and course. Let name be a structure which has
members first name middle name and last name.
Read and display 5 student’s information
#include<stdio.h>
struct student
{
int r_no;
struct NAME
{
char f_name[20];
char m_name[20];
char l_name[20];
} n;
char course[20];
};
void main()
{
struct student s[50];
int i, m;
printf("how many student detail you wish to enter?");
scanf("%d", &m);
for(i=0; i<m; i++)
{
printf("enter roll number first name and last name");
scanf("%d%s%s",&s[i].r_no, s[i].n.f_name, s[i].n.m_name);
}

for(i=0; i<m; i++)


printf("\n student roll and name is %d %s %s", s[i].r_no, s[i].n.f_name,
s[i].n.m_name);
}
PART B: LAB PROGRAM 5

Structures
Implement structures to read, write and
compute the average salary for a department
of N employees. (Consider nested structure
for DOB)
Output:
Question
Implement structures to read, write, compute
average- marks and the students scoring above and
below the average marks for a class of N students
Sample Input and Output
Input:
Enter number of students:2
Enter USN: 1BM18CS001
Enter Name: Arjun
Enter Marks: 40
Enter USN: 1BM18CS002
Enter Name: Bharath
Enter Marks: 60

Output:
Arjun scored below average
Bharath scored above average
#include <stdio.h> for(i=0; i<n; i++) {
main() { printf("\n Enter USN: ");
struct student scanf("%s", s[i]. usn);
{ printf("\n Enter Name: ");
char usn[15]; scanf("%s", s[i]. name);
char name[25]; printf("Enter Marks: \n");
float marks; scanf("%f", &s[i]. marks);
}; }
struct student s[20]; for(i=0; i<n; i++) {
int n, i; sum = sum + s[i]. marks;
float avg, sum=0.0; }
avg=sum/n;
printf("Enter number of students:"); for(i=0; i<n; i++)
scanf("%d", &n); {
if(s[i].marks >= avg)
printf("\n %s scored above average", s[i].name);
else
printf("\n %s scored below average", s[i].name);
}
}
Using sizeof operator to find size of a structure
struct book
{
char name[20];
char title[20];
float price;
int year;
};
void main()
{
struct book b1;
printf("Size of the structure is %d", sizeof(b1));
}
Example Programs

Application programs on structures


C Program to Store Information of Students Using Structure
#include <stdio.h>
#include <stdlib.h>
#include <string.h> student[3].roll_number = 4;
struct Student { student[3].name = "Geeks4";
char* name; student[3].age = 12;
int roll_number; student[3].total_marks = 89.78;
int age;
double total_marks; student[4].roll_number = 3;
}; student[4].name = "Geeks3";
int main() student[4].age = 13;
{ student[4].total_marks = 78.55;
int i = 0, n = 5;
struct Student student[n]; // Print the Students information
student[0].roll_number = 1; printf("Student Records:\n\n");
student[0].name = "Geeks1"; for (i = 0; i < n; i++)
student[0].age = 12; {
student[0].total_marks = 78.50; printf("\tName = %s\n", student[i].name);
printf("\tRoll Number = %d\n", student[i].roll_number);
student[1].roll_number = 5; printf("\tAge = %d\n", student[i].age);
student[1].name = "Geeks5"; printf("\tTotal Marks = %0.2f\n\n", student[i].total_marks);
student[1].age = 10; }
student[1].total_marks = 56.84;
return 0;
student[2].roll_number = 2; }
student[2].name = "Geeks2";
student[2].age = 11;
student[2].total_marks = 87.94;
Output
Create a structure to specify data of customers in a bank. The
data to be stored is: Account number, Name, Balance in account.
Assume maximum of 20 customers in the bank. Create a
function to read all customers details and call it in main. Your
program must be menu driven with following options:
1. Print the Account number and name and balance of each
customer.
2. Withdraw money
3. Deposit money
4. Search Customer
Contd..
Contd..
THANK
YOU

You might also like