KEMBAR78
Unit 4 Notes | PDF | String (Computer Science) | Computer Program
0% found this document useful (0 votes)
3 views21 pages

Unit 4 Notes

The document provides an overview of strings and user-defined data types in C, including string handling operations, manipulations, and examples of using structures and unions. It explains how to declare, initialize, and manipulate strings, as well as how to define and access structures and unions. Additionally, it highlights the differences between structures and unions in terms of memory allocation and member access.

Uploaded by

kanimozhi
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)
3 views21 pages

Unit 4 Notes

The document provides an overview of strings and user-defined data types in C, including string handling operations, manipulations, and examples of using structures and unions. It explains how to declare, initialize, and manipulate strings, as well as how to define and access structures and unions. Additionally, it highlights the differences between structures and unions in terms of memory allocation and member access.

Uploaded by

kanimozhi
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/ 21

Unit -IV

Strings and User Defined Data Types


String:
String is a collec on of characters called as character array.
String is enclosed within double quotes (“ “).
String handling opera ons:
1. Declare the string variables.
2. Ini alize the string variables.
3. Read an input for the string variables.
4. Print the value that is stored in the string variable.
String Manipula ons:
1. Find the length of the string.
2. Compare two strings.
3. Copy from one string to another.
4. Convert the string from lowercase to uppercase.
5. Convert the string from uppercase to lowercase.
6. Joining two strings into one string.
7. Reverse a string.

Declare the String Variables:


It is a process of defining a string variable. The size of the string and its type.
String stores as an array of characters.
Syntax:
Datatype string _variable_name(size);
Example:
Char c[10];
scanf(“%s”,&c);

Ini alizing String Variable:


Ini alizing is assigning a value to string variable either character by character or as a whole string.
Example:
char str[10]={“n”,”a”,”m”,”e”};
char str[10]=”name”;
char str1[]=”name1”;
Example Program:
#include <stdio.h>
int main()
{
char name[10];
prin ("Enter Name:");
scanf("%s",&name);
prin ("your name is:%s",name);
}
Output:
Enter Name: CProgram
CProgram

Reading a String:
Reading single character or series of character from the input string.
scanf()
getchar()
gets()
scanf():
To read a single character or a word from input device.
Format specifier: %s
It automa cally terminates when it reads with a null character.

Disadvantages:
1. Terminates if white space
2. Not more than a word.

getchar():
1. Reads alphanumeric character.
2. unforma ed func on.
3. next character is scanned a er enter key.
Disadvantages:
Terminates when new line is entered.
gets():
unforma ed func on it reads a group of character and alphanumeric character from the standard input
device.
Disadvantages:
It reads string from input device and stores it in a character array.
Prin ng a String:
Process of displaying a character or series of character.
prin ()
putchar()
puts()
prin ():
Forma ed output func on.
To print a word or a single character.
Format specifier: %s
Syntax:
Char variable name;
Prin (control variable, variable name);
Example:
char name[10];
scanf(“%s”,&name);
prin (“%s”,name);

putchar():
unforma ed output func on.
To print alphanumeric character on output device.
Prints one char at a me.
Syntax:
char variable name[s];
putchar(variable name);

puts():
unforma ed output func on with a header file <stdio.h>.
To print alphanumeric character on output device.
Syntax:
char variable name[s];
puts(variable name);

String Opera ons:


1.String Copy- strcpy
2.String concatena on- strcat
3.String to lowercase – strlwr()
4.String to uppercase – strupr()
5.String length- strlen()
6.String compare – strcmp()
String reverse – strrev()

String Copy:
The strcpy() is used to copy one string to another.
String Concat:
The strcat() is used for string concatena on. It will append a copy of the source string to the end of the
des na on string.
String Lowercase:
The strlwr() is used to convert all the characters of the given string to lowercase.
String Uppercase:
The strupr() is used to convert all the characters of the given string to uppercase.
String Length:
The strlen() calculates the length of a given string. It doesn’t count the null character ‘\0’.
String Compare:
The strcmp() is used to compare two strings.
String Reverse:
The strrev() is the func on used to reverses or changes the order of a given string so that the last
character of the string becomes the first character of the string and so on. we can also check the
Palindrome of the given string by reversing the original string.
Example Program to copy the given String:
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'C', 'P', 'R', 'O', 'G', 'R', 'A', 'M','\0'};
char ch2[]="welcome";
//char ch2[20];
prin ("The value of First String=%s",ch);
prin ("\nThe value of Second String=%s",ch2);
strcpy(ch2,ch);
prin ("\nValue of second string A er copy is: %s",ch2);
return 0;
}
Example program for Concatena on of two Strings:
#include<stdio.h>
#include <string.h>
int main(){
char ch[10]={'W', 'e', 'l', 'c', 'o','m','e', '\0'};
char ch2[10]={'t','o','C','\0'};
strcat(ch,ch2);
prin ("Value of first string is: %s",ch);
return 0;
}
Example program to convert the string from uppercase to lowercase:
#include <stdio.h>
#include <ctype.h>
// Func on to convert a string to lowercase
void to_lowercase(char str[]) {
for (int i = 0; str[i] != '\0'; i++) {
str[i] = tolower(str[i]);
}}
int main() {
char str[100];
// Input string from user
prin ("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Convert string to lowercase
to_lowercase(str);
// Output the converted string
prin ("Lowercase String: %s", str);
return 0;}
Example program to convert the string lowercase to uppercase:
#include <stdio.h>
#include <ctype.h>
// Func on to convert a string to uppercase
void to_uppercase(char str[]) {
for (int i = 0; str[i] != '\0'; i++) {
str[i] = toupper(str[i]);
}
}
int main() {
char str[100];
// Input string from user
prin ("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Convert string to uppercase
to_uppercase(str);
// Output the converted string
prin ("Uppercase String: %s", str);
return 0;
}
Example program to find the Length of the string
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
prin ("Length of string is: %d",strlen(ch));
return 0;
}
Example program to compare two strings:
#include<stdio.h>
#include<string.h>
int main(){
char str1[20],str2[20];
prin ("Enter 1st string: ");
scanf("%s",str1);//reads string from console
prin ("Enter 2nd string: ");
scanf("%s",str2);
if(strcmp(str1,str2)==0)
prin ("Strings are equal");
else
prin ("Strings are not equal");
return 0;
}
Structure:
It is used to group items of possibly different types into a single type and it is a collec on of one or more
related variables of different data types , grouped under single name. The Variables are called members
of the structure.
Syntax:
struct Structure_name
{
Datatype member_variable1;
--------------------------------------;
--------------------------------------;
Datatype member_variableN;
};
Example:
struct MyStructure // Structure declara on
{
int myNum; // Member (int variable)
char myLe er; // Member (char variable)
}; // End the structure with a semicolon
Structure Ini aliza on:
#include <stdio.h>
#include <string.h>
struct Student {
int id;
char name[50];
float percentage;
};
int main()
{
struct Student student1 = { 1, "John Doe", 85.5 };// ini alisa on of structure
// Print the ini alized structure
prin ("ID: %d\n", student1.id);
prin ("Name: %s\n", student1.name);
prin ("Percentage: %.2f\n", student1.percentage);
return 0;
}
Accessing the Structure:
#include<stdio.h>
struct myStructure
{
int myNum;
char myLe er;
};

int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;

// Assign values to members of s1


s1.myNum = 13;
s1.myLe er = 'B';
// Print values
prin ("My number: %d\n", s1.myNum);
prin ("My le er: %c\n", s1.myLe er);

return 0;
}
Nested Structure:
A nested structure in C is a structure within structure. One structure can be declared inside another
structure in the same way structure members are declared inside a structure.
Syntax:
struct name_1
{
member1;
member2;
------------------
membern;
struct name_2
{
member_1;
member_2;
--------------
member_n;
}, var1
} var2;

Example program:
#include <stdio.h>
#include <string.h>
struct Employee
{
int employee_id;
char name[20];
int salary;
};
struct Organisa on
{
char organisa on_name[20];
char org_number[20];
struct Employee emp;
};
int main()
{
struct Organisa on org;
prin ("The size of structure organisa on : %ld\n",sizeof(org));
org.emp.employee_id = 101;
strcpy(org.emp.name, "XXXX");
org.emp.salary = 400000;
strcpy(org.organisa on_name,"Kathir College");
strcpy(org.org_number, "YYY");
prin ("Organisa on Name : %s\n",org.organisa on_name);
prin ("Organisa on Number : %s\n",org.org_number);
prin ("Employee id : %d\n",org.emp.employee_id);
prin ("Employee name : %s\n",org.emp.name);
prin ("Employee Salary : %d\n",org.emp.salary);
}

Array of Structure:
#include<stdio.h>
#include<string.h>
struct Employee {
char Name[20];
int employeeID;
int WeekA endence[7];
};
int main()
{
struct Employee emp[5];
for (int i = 0; i < 5; i++) {
emp[i].employeeID = i;
strcpy(emp[i].Name, "Amit");
int week;
for (week = 0; week < 7; week++) {
int a endence;
emp[i].WeekA endence[week] = week;
}
}
prin ("\n");
for (int i = 0; i < 5; i++) {
prin ("Emplyee ID: %d - Employee Name: %s\n",emp[i].employeeID, emp[i].Name);
prin ("A endence\n");
int week;
for (week = 0; week < 7; week++) {
prin ("%d ", emp[i].WeekA endence[week]);
}
prin ("\n");
}
return 0;
}

structures and func ons:


#include <stdio.h>
struct rectangle{
float len, brd;
};
int area(float, float);
int main(){
struct rectangle r;
r.len = 10.50; r.brd = 20.5;
area(r.len, r.brd);
return 0;
}
int area(float a, float b){
double area = (double)(a*b);
prin ("Length: %f \nBreadth: %f \nArea: %lf\n", a, b, area);
return 0;
}
Unions:
A Union is a special data type available in C that allows storing different data types in the same memory
loca on.
Example:
#include<stdio.h>
union abc
{
int a;
char b;
}var;
int main()
{
var.a = 66;
prin ("\n a = %d", var.a);
prin ("\n b = %d", var.b);
}
Output:
a = 66
b = 66

Difference Between Structure and Union in C

Parameter Structure Union

Keyword A user can deploy the keyword struct to A user can deploy the keyword union to
define a Structure. define a Union.

Internal The implementa on of Structure in C In the case of a Union, the memory


Implementa on occurs internally- because it contains alloca on occurs for only one member with
separate memory loca ons allo ed to the largest size among all the input
every input member. variables. It shares the same loca on among
all these members/objects.

Accessing A user can access individual members at A user can access only one member at a
Members a given me. given me.

Syntax The Syntax of declaring a Structure in C The Syntax of declaring a Union in C is:
is: union [union name]
struct [structure name] {
{ type element_1;
type element_1; type element_2;
type element_2; .
. .
. } variable_1, variable_2, …;
} variable_1, variable_2, …;

Size A Structure does not have a shared A Union does not have a separate loca on
loca on for all of its members. It makes for every member in it. It makes its size
the size of a Structure to be greater than equal to the size of the largest member
or equal to the sum of the size of its data among all the data members.
members.

Value Altering Altering the values of a single member When you alter the values of a single
does not affect the other members of a member, it affects the values of other
Structure. members.

Storage of Value In the case of a Structure, there is a In the case of a Union, there is an alloca on
specific memory loca on for every input of only one shared memory for all the input
data member. Thus, it can store mul ple data members. Thus, it stores one value at a
values of the various members. me for all of its members.

Ini aliza on In the case of a Structure, a user can In the case of a Union, a user can only
ini alize mul ple members at the same ini ate the first member at a me.
me.

Difference between Structure and Union Program:


#include <stdio.h>
#include <string.h>
// declaring structure
struct struct_example
{
int integer;
float decimal;
char name[20];
};
// declaraing union
union union_example
{
int integer;
float decimal;
char name[20];
};
void main()
{
// crea ng variable for structure and ini alizing values difference six
struct struct_example stru ={5, 15, "John"};
// crea ng variable for union and ini alizing values
union union_example uni = {5,15,"John"};
prin ("data of structure:\n integer: %d\n decimal: %.2f\n name: %s\n", stru.integer, stru.decimal,
stru.name);
prin ("\ndata of union:\n integer: %d\n" "decimal: %.2f\n name: %s\n", uni.integer, uni.decimal,
uni.name);
prin ("\nAccessing all members at a me:");
stru.integer = 163;
stru.decimal = 75;
strcpy(stru.name, "John");
prin ("\ndata of structure:\n integer: %d\n " "decimal: %f\n name: %s\n", stru.integer, stru.decimal,
stru.name);

uni.integer = 163;
uni.decimal = 75;
strcpy(uni.name, "John");
prin ("\ndata of union:\n integeer: %d\n " "decimal: %f\n name: %s\n", uni.integer, uni.decimal,
uni.name);
prin ("\nsizeof structure: %d\n", sizeof(stru));
prin ("sizeof union: %d\n", sizeof(uni));
}
Output:
data of union:
integer: 5
decimal: 0.00
name:
Accessing all members at a me:
data of structure:
integer: 163
decimal: 75.000000
name: John
data of union:
integeer: 1852337994
decimal: 17983765624912253034071851008.000000
name: John
sizeof structure: 28
sizeof union: 20

Self-Referen al Structures:
Self-Referen al structures are those structures that have one or more pointers which point to the same
type of structure, as their member.
Types of Self-Referen al Structures
Self-Referen al Structure with Single Link
Self-Referen al Structure with Mul ple Links
Self-Referen al Structure with Single Link:
These structures can have only one self-pointer as their member. The following example will show us
how to connect the objects of a self-referen al structure with the single link and access the
corresponding data members. The connec on formed is shown in the following figure.

Example:
#include <stdio.h>

struct node {
int data1;
char data2;
struct node* link;
};

int main()
{
struct node ob1; // Node1

// Ini aliza on
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;

struct node ob2; // Node2

// Ini aliza on
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;

// Linking ob1 and ob2


ob1.link = &ob2;

// Accessing data members of ob2 using ob1


prin ("%d", ob1.link->data1);
prin ("\n%d", ob1.link->data2);
return 0;
}
Output:
30
40
Self-Referen al Structure with Mul ple Links:
Self-referen al structures with mul ple links can have more than one self-pointer. Many complicated
data structures can be easily constructed using these structures. Such structures can easily connect to
more than one node at a me. The following example shows one such structure with more than one
links.
The connec ons made in the above example can be understood using the following figure.

Example:
#include <stdio.h>
struct node {
int data;
struct node* prev_link;
struct node* next_link;
};
int main()
{
struct node ob1; // Node1
ob1.prev_link = NULL;
ob1.next_link = NULL;
ob1.data = 10;
struct node ob2; // Node2
ob2.prev_link = NULL;
ob2.next_link = NULL;
ob2.data = 20;
struct node ob3; // Node3
ob3.prev_link = NULL;
ob3.next_link = NULL;
ob3.data = 30;
ob1.next_link = &ob2;
ob2.next_link = &ob3;
ob2.prev_link = &ob1;
ob3.prev_link = &ob2;
prin ("%d\t", ob1.data);
prin ("%d\t", ob1.next_link->data);
prin ("%d\n", ob1.next_link->next_link->data);
prin ("%d\t", ob2.prev_link->data);
prin ("%d\t", ob2.data);
prin ("%d\n", ob2.next_link->data);
prin ("%d\t", ob3.prev_link->prev_link->data);
prin ("%d\t", ob3.prev_link->data);
prin ("%d", ob3.data);
return 0;
}
Output:
10 20 30
10 20 30
10 20 30

Applica ons:
Self-referen al structures are very useful in crea on of other complex data structures like:
Linked lists
Stacks
Queues
Trees
Graphs etc.

C typedef
The typedef is a keyword that is used to provide exis ng data types with a new name. The C typedef
keyword is used to redefine the name of already exis ng data types.
Example:
#include <stdio.h>
typedef long long ll;
int main()
{
ll var = 20;
prin ("%ld", var);
return 0;
}

Use of typedef in C
Following are some common uses of the typedef in C programming:
The typedef keyword gives a meaningful name to the exis ng data type which helps other users to
understand the program more easily.
It can be used with structures to increase code readability and we don’t have to type struct repeatedly.
The typedef keyword can also be used with pointers to declare mul ple pointers in a single statement.
It can be used with arrays to declare any number of variables.
Enumera on:
Enumera on (or enum) is a user defined data type in C. It is mainly used to assign names to integral
constants, the names make a program easy to read and maintain.
The keyword ‘enum’ is used to declare new enumera on types in C and C++. Enums in C allow you to
assign names to integral constants, making code more readable.
Example:
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()
{
enum week day;
day = Wed;
prin ("%d",day);
return 0;
}

You might also like