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

Module 4

Get aware of concepts like Strings and Structures in C!

Uploaded by

ushashank720
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)
27 views

Module 4

Get aware of concepts like Strings and Structures in C!

Uploaded by

ushashank720
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/ 27

Unit 4

Ch 13: 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 #include <stdio.h>
the following pattern. main()
H {
int i, p;
HE
char str[] = "HELLO";
HEL
HELL for(i=0;i<5;i++)
HELLO {
HELLO p = i+1;
HELL printf("\n %-5.*s", p, str);
HEL }
for(i=4;i>=0;i--)
HE
{
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
of a String Write a program to find the
length 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> upper_str[j] = '\0';
int main() printf("\n The string converted
{ into upper case is : ");
char str[100], upper_str [100]; puts(upper_str);
int i=0, j=0; return 0;
printf("\n Enter the string:"); }
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++;
}
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 of a
string into lower case.
#include <stdio.h>
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>
int main() i=0;
while(str2[i] != '\0')
{
char str1[100], str2[100],str3[100]; {
str3[j] = str2[i];
int i=0, j=0;
printf("\n Enter the first string:"); i++;
gets(str1); j++;
}
printf("\n Enter the second
string:"); str3[j] = '\0';
printf("\n The concatenated
gets(str2);
while(str1[i] != '\0') string is:");
{ puts(str3);
return 0;
str3[j] = str1[i];
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
Step 2: SET Len1=Length(STR1),
order S1 will come after S2
Len2=Length(STR2)
Step 3: IF len1 != len2, then
iii) S1 < S2 , when in dictionary
Write “Strings Are Not Equal” order S1 precedes S2
ELSE Step 4: IF SAME = 0, then
Repeat while I<Len1 IF STR1[I] >
IF STR1[I] == STR2[I]
SET I = I + 1 STR2[I], then
ELSE Write “String1 is
Go to Step 4 greater than
[END OF IF] String2”
[END OF LOOP] ELSE IF STR1[I]<STR2[I],then
IF I = Len1, then
SET SAME =1 Write “String2 is
Write “Strings are equal” greater than
[END OF IF] String1”
[END OF IF]
Write a program to compare two strings.
if(i==len1)
#include <stdio.h>
{ same=1;
#include <string.h>
printf("\n The two strings are
equal");
main()
}
{
}
char str1[50], str2[50];
if(len1!=len2)
int i=0, len1 = 0, len2 = 0, same = 0;
printf("\n The two strings are not
printf("\n Enter the first string : ");
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
len2 = strlen(str2);
string2");
if(len1 == len2)
else if(str1[i]<str2[i])
{ while(i<len1)
printf("\n String2 is greater than
{ if(str1[i] == str2[i])
string1");
i++;
}
else break;
return 0;
}
}
Unit 4
Ch 15: STRUCTURES
Structures
• 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.
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
{
int id;
char name[10];
float salary;
};
struct employee emp1;

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

• 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;
• 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 initialisation)
• 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);
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;
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

You might also like