0% found this document useful (0 votes)
25 views20 pages

R23 CP Unit-3

This document covers arrays and strings in C programming, detailing their properties, advantages, and disadvantages. It includes syntax for declaring and initializing one-dimensional and two-dimensional arrays, along with examples of operations like addition and multiplication of matrices. Additionally, it discusses string declaration, initialization, and various string functions available in the C library.

Uploaded by

kataruraj9
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)
25 views20 pages

R23 CP Unit-3

This document covers arrays and strings in C programming, detailing their properties, advantages, and disadvantages. It includes syntax for declaring and initializing one-dimensional and two-dimensional arrays, along with examples of operations like addition and multiplication of matrices. Additionally, it discusses string declaration, initialization, and various string functions available in the C library.

Uploaded by

kataruraj9
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/ 20

Programming for Problem Solving using C UNIT-3

Array:
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which can
store the primitive type of data such as int, char, double, float, etc.
Syntax: datatype arrayname[size];
The array contains the following properties.
➢ Each element of an array is of same data type and carries the same size, i.e., int = 2
bytes.
➢ Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
➢ Elements of the array can be randomly accessed.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn
later.
Declaration of C Array:
We can declare an array in the c language in the following way.
Syntax: data_type array_name[array_size];
Now, let us see the example to declare the array.
Example: int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of array:
int marks[ ] = { 80, 60, 70, 85, 75 };
or
int marks[5] = { 80, 60, 70, 85, 75 };
or
int marks[5];
marks[0] = 80;
marks[1] = 60;
marks[2] = 70;
marks[3] = 85;
marks[4] = 75;
80 60 70 85 75
marks[0] marks[1] marks[2] marks[3] marks[4]
Example:
#include<stdio.h>
void main( )
{
int i=0;
int marks[5] = { 80, 60, 70, 85, 75 };
for(i=0;i<5;i++)
{
printf("%d " , marks[ i ] );
}
}

Page 1
Programming for Problem Solving using C UNIT-3

Example:
#include<stdio.h>
void main()
{
int i=0;
int marks[5];
marks[0] = 80;
marks[1] = 60;
marks[2] = 70;
marks[3] = 85;
marks[4] = 75;
for(i=0;i<5;i++)
{
printf("%d " , marks[ i ] );
}
}
Example:
#include<stdio.h>
void main()
{
int i=0;
int marks[5] = {80, 60, 70, 85, 75};

printf("%d ",marks[0]);
printf("%d ",marks[1]);
printf("%d ",marks[2]);
printf("%d ",marks[3]);
printf("%d ",marks[4]);
}

// Program to find the sum of n numbers using arrays


#include <stdio.h>
int main()
{
int marks[10], i, n, sum;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter value: ");
scanf("%d", &marks[i]);
}
sum=0;
for(i=0; i<n; ++i)
{
sum = sum + marks[i];
}
printf("Sum is %d", sum);
}

Page 2
Programming for Problem Solving using C UNIT-3

// Program to find the average of n numbers using arrays


#include <stdio.h>
int main()
{
int marks[10], i, n, sum;
float avg;

printf("Enter number of elements: ");


scanf("%d", &n);

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


{
printf("Enter value: ");
scanf("%d", &marks[i]);
}
sum=0;
for(i=0; i<n; ++i)
{
sum = sum + marks[i];
}
avg = (float)sum / n;
printf("Average is %.2f", avg);
}
// Program to find the biggest of n numbers using arrays

#include <stdio.h>
int main()
{
int a[10], i, n, big;

printf("Enter number of elements: ");


scanf("%d", &n);

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


{
printf("Enter value: ");
scanf("%d", &a[i]);
}
big= a[0];
for(i=1; i<n; ++i)
{
if(a[i]>big)
big = a[i];
}
printf("Biggest is %d", big);
}

Page 3
Programming for Problem Solving using C UNIT-3

Two Dimensional Array:


The two-dimensional array can be defined as an array of arrays. The 2D array is
organized as matrices which can be represented as the collection of rows and columns.
However, 2D arrays are created to implement a relational database lookalike data structure. It
provides ease of holding the bulk of data at once which can be passed to any number of
functions wherever required.

Declaration of two dimensional Array in C


The syntax to declare the 2D array is given below.
data_type array_name[rows][columns];
Consider the following example.
int twodimen[4][3];
Here, 4 is the number of rows, and 3 is the number of columns.

Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and
initialization are being done simultaneously. However, this will not work with 2D arrays. We
will have to define at least the second dimension of the array. The two-dimensional array can
be declared and defined in the following way.

int arr[2][3]={{1,2,3},{2,3,4}};

Example:
#include<stdio.h>
void main( )
{
int i,j;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf(" %d" , arr[ i ][ j ]);
}
printf("\n");
}
}

Page 4
Programming for Problem Solving using C UNIT-3

Example:
#include<stdio.h>
void main( )
{
int i,j;
int arr[4][3];

arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[1][0] = 2;
arr[1][1] = 3;
arr[1][2] = 4;
arr[2][0] = 3;
arr[2][1] = 4;
arr[2][2] = 5;
arr[3][0] = 4;
arr[3][1] = 5;
arr[3][2] = 6;

for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf(" %d",arr[i][j]);
}
printf("\n");
}
}

/* program for addition of two matrices */

#include<stdio.h>
void main()
{
int a[10][10], b[10][10], c[10][10];
int i, j, m1, n1, m2, n2;

printf("Enter no. of rows and columsn for matrix A: ");


scanf("%d%d", &m1, &n1);

printf("Enter no. of rows and columsn for matrix B: ");


scanf("%d%d", &m2, &n2);

Page 5
Programming for Problem Solving using C UNIT-3

if(m1!=m2 && n1!=n2)


printf("Addition is Not Possible");
else
{
printf("Enter matrix A value: \n");
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
{
scanf("%d", &a[i][j]);
}
}

printf("Enter matrix B value: \n");


for(i=0;i<m2;i++)
{
for(j=0;j<n2;j++)
{
scanf("%d", &b[i][j]);
}
}

for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
{
c[i][j] = a[i][j] + b[i][j] ;
}
}
printf("Addition is: \n");
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
{
printf("%d ", c[i][j]);
}
printf("\n");
}
}
}

Page 6
Programming for Problem Solving using C UNIT-3

/* program for multiplication of two matrices */


#include<stdio.h>
void main()
{
int a[10][10], b[10][10], c[10][10];
int i, j, k, m1, n1, m2, n2;
printf("Enter no. of rows and columsn for matrix A: ");
scanf("%d%d", &m1, &n1);
printf("Enter no. of rows and columsn for matrix B: ");
scanf("%d%d", &m2, &n2);

if( n1!=m2)
printf("Multiplication is Not Possible");
else
{
printf("Enter matrix A value: \n");
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
{
scanf("%d", &a[i][j]);
}
}

printf("Enter matrix B value: \n");


for(i=0;i<m2;i++)
{
for(j=0;j<n2;j++)
{
scanf("%d", &b[i][j]);
}
}

for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
c[i][j]=0;
for(k=0;k<n1;k++)
{
c[ i ][ j ] = c[ i ][ j ] + ( a[ i ][ k ] * b[ k ][ j ] );
}
}
}

Page 7
Programming for Problem Solving using C UNIT-3

printf("Multiplication is: \n");


for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
printf("%d ", c[i][j]);
}
printf("\n");
}
}
}

Page 8
Programming for Problem Solving using C UNIT-3

Strings:
In C programming, a string is a sequence of characters terminated with a null character \0.

Declaration of Strings:
To declare Strings we must use one dimensional array of characters terminated by null
character \0.
Syntax:
char str_name [ size ] ;
In the above syntax str_name is any name given to the string variable and size is used
define the length of the string, i.e., the number of characters strings will store. Please keep in
mind that there is an extra terminating character which is the Null character („\0‟) used to
indicate termination of string which differs strings from normal character arrays.

Initialization of Strings:
There are many number of ways to initialization of strings.
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};

Index 0 1 2 3 4
Value a b c d \0
Address 100 101 102 103 104

Display Strings:
To display strings we can use %s as format Specofier.
Example:
#include<stdio.h>
void main()
{
char c[5] = "abcd"; Output:
printf("The String is %s", c); The String is abcd
}

Page 9
Programming for Problem Solving using C UNIT-3

Read String from the user:


You can use scanf ( ) function to read string from the user.
The scanf ( ) function reads the sequence of characters until it encounters whitespace (space,
newline, tab etc.).
Example:
#include <stdio.h>
void main()
{
char name[20];
printf("Enter name: ");
scanf ( "%s" , name ) ;
printf("Your name is %s", name);
}
Even though Dennis Ritchie was entered in the above program, only “Dennis” was stored in
the name String. Because, there is a space after Dennis.

Read entire line of text:


You can use gets( ) function or fgets ( ) function to read entire line from the user.
Example-1:
#include <stdio.h>
void main()
{
char name[20];
printf("Enter name: ");
gets ( name ) ;
printf("Your name is %s", name);
}
Example-2:
#include <stdio.h>
void main()
{
char name[20];
printf("Enter name: ");
fgets ( name, sizeof(name), stdin );
printf("Your name is %s", name);
}

Page 10
Programming for Problem Solving using C UNIT-3

In Example-2, we have used fgets ( ) function to read a string from the user.
fgets ( name, sizeof(name), stdin );
The sizeof(name) results to 20. Hence, we can take a maximum of 20 characters as input
which is the size of the name string.
String Functions in C library:
There are so many predefined functions regarding string operations. To use these functions
we must include “string.h” header file. And these functions should be write in lowercase.

SNO FUNCTION NAME DESCRIPTION


1 strlen ( string ) It returns length of string
2 strlwr ( string ) It converts string into lowercase
3 strupr ( string ) It converts string into uppercase
It concatenates string_1 to string_2 and then
4 strcat ( string_1, string_2 )
store into string_1.
It concatenates string_1 to specific no. of
5 strncat ( string_1, string_2,size ) characters of string_2 and then store into
string_1.
It compares string_1 with string_2.
➢ If both are equal then it returns 0.
6 strcmp ( string_1, string_2 )
➢ If string_1 < string_2 then it returns –ve.
➢ If string_1 > string_2 then it returns +ve.
It compares string_1 with specific no. of
characters of string_2.
7 strncmp ( string_1, string_2, size ) ➢ If both are equal then it returns 0.
➢ If string_1 < string_2 then it returns –ve.
➢ If string_1 > string_2 then it returns +ve.
8 strcpy ( string_1, string_2 ) It copies string_2 into string_1.
It copies specific no. of characters of
9 strncpy ( string_1, string_2, size )
string_2 into string_1.
It searches first position of character in the
10 strchr ( string, character ) string and prints the string from that
character to the end.
It searches last position of character in the
11 strrchr ( string, character ) string and prints the string from that
character to the end.
12 strrev ( string ) It returns reverse of string

Page 11
Programming for Problem Solving using C UNIT-3

Example-1:
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "WeLcOmE";
printf (" String is %s", mystr);
printf ("\n Length is %d", strlen(mystr));
printf ("\n Uppercase is %s", strupr(mystr));
printf ("\n Lowercase is %s", strlwr(mystr));
return 0;
}
Example-2:
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "welcome";
char mystr2[30] = "WELCOME";
if(strcmp(mystr,mystr2)==0)
{
printf("Both are Equal");
}
else
{
printf("Both are Not Equal");
}
return 0;
}
Example-3:
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30];
char mystr2[30] = "welcome";
strcpy(mystr,mystr2);
printf("%s",mystr);
return 0;
}
Example-4:
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30]="welcome";
char mystr2[30] = " to cse";
strcat(mystr,mystr2);
printf("%s",mystr);
return 0;
}

Page 12
Programming for Problem Solving using C UNIT-3

Example-5:
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30]="welcome to cse";
printf("%s",strchr(mystr,'c'));
return 0;
}

Example-6:
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30]="welcome to cse";
printf("%s",strrchr(mystr,'c'));
return 0;
}

Example-7:
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30]="welcome to cse";
printf("%s",strrev(mystr));
return 0;
}
MORSE CODE:
Morse code is a method of transmitting text information as a series of on-off tones,
lights, or clicks that can be directly understood by a skilled listener or observer without
special equipment. It is named for Samuel F. B. Morse, an inventor of the telegraph.
The algorithm is very simple. Every character in the English language is substituted
by a series of „dots‟ and „dashes‟ or sometimes just singular „dot‟ or „dash‟ and vice versa.
Every text string is converted into the series of dots and dashes. For this every
character is converted into its Morse code and appended in encoded message. Here we have
copied space as it is. And we have not considered numbers, only alphabets.

Page 13
Programming for Problem Solving using C UNIT-3

Program:
#include<stdio.h>
#include<string.h>
void main()
{
char name[50],morse[250];
int i;

printf("Input: ");
gets(name);

printf("\nOutput : ");
for(i=0;i<strlen(name);i++)
{
switch(name[i])
{
case 'A': printf(".-");break;
case 'B': printf("-...");break;
case 'C': printf("-.-.");break;
case 'D': printf("-..");break;
case 'E': printf(".");break;
case 'F': printf("..-.");break;
case 'G': printf("--.");break;
case 'H': printf(". .. ");break;
case 'I': printf("..");break;
case 'J': printf(".---");break;
case 'K': printf("-.-");break;
case 'L': printf(".-..");break;
case 'M': printf("--");break;
case 'N': printf("-.");break;
case 'O': printf("---");break;
case 'P': printf(".--.");break;
case 'Q': printf("--.-");break;
case 'R': printf(".-.");break;
case 'S': printf("...");break;
case 'T': printf("-");break;
case 'U': printf("..-");break;
case 'V': printf("...-");break;
case 'W': printf(".--");break;
case 'X': printf("-..-");break;
case 'Y': printf("-.--");break;
case 'Z': printf("--..");break;
}
}
}

Page 14
Programming for Problem Solving using C UNIT-3

The type definition:


A type definition typedef, gives a name to a datatype by creating a new type that can
be used anywhere a type is permitted.
typedef type IDENTIFER;
where typedef is keyword, type is any standard or derived type and IDENTIFER
should be in upper case.
Example:
typedef char* STRING;
STRING stringptrAty[20];

Enumerated types:
The enumerated type is a user defined type based on the standard integer type. In this
each integer is given as identifier called an enumeration constant.
Declaration of enumerated type:
In enumerate type; we declare its identifier and its values. Because it is derived form
the integer type, its operations are the same as for integers.
Syntax: enum typeName {identifier list};
Example: enum color {red, blue, green, white};
Assigning values to enumerated types:
An enumerated variable can hold only declared values for the type.
Example:
#include<stdio.h>
enum week { Mon, Tue, Wed, Thur, Fri, Sat, Sun };

int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}
Output: 2
Structures:
Structure is a collection of related elements, possibly of different types, having a
single name.
Structure Definition in C
Keyword struct is used for creating a structure.

Page 15
Programming for Problem Solving using C UNIT-3

Syntax of structure
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};

Note: Don't forget the semicolon }; in the ending line.


Example:
struct person
{
char name[50];
int citNo;
float salary;
};
Structure variable declaration:
When a structure is defined, it creates a user-defined type but, no storage or memory
is allocated.
struct person
{
char name[50];
int citNo;
float salary;
};
int main( )
{
struct person p1, p2, p3[20] ;
return 0;
}
Another way of creating a structure variable is
struct person
{
char name[50];
int citNo;
float salary;
}p1, p2, p3[20] ;

Page 16
Programming for Problem Solving using C UNIT-3

Accessing members of structure:


There are two types of operators used for accessing members of a structure.
1. Member operator( ).
2. Structure pointer operator(→)
Any member of a structure can be accessed as:
Structure_var_name.member_name;
Ex: p2.salary;
Example program:
#include <stdio.h>
struct student
{
char *stu_name;
int stu_id;
int stu_age;
};
int main()
{
struct student s1;
s1.stu_name = "Steve";
s1.stu_id = 1234;
s1.stu_age = 30;

printf("Student Name is: %s", s1.stu_name);


printf("\nStudent Id is: %d", s1.stu_id);
printf("\nStudent Age is: %d", s1.stu_age);
return 0;
}

Output: Student Name is: Steve


Student Id is: 1234
Student Age is: 21
Structure Initialization:
We can declare a structure, memory is not allocated for un-initialized variables.
Way1: Declare and Initialize
struct student
{
Char name[20];
float marks;
}std1 = { "Pritesh",67,78.3 };

Page 17
Programming for Problem Solving using C UNIT-3

Way2: Declaring and Initializing Multiple Variables


struct student
{
char name[20]; int roll;
float marks;
}
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
Way3: Initializing single member
struct student
{
int mark1; int mark2; int mark3;
} sub1={67};
Nested structure:
We can take any structure as a member of structure, i.e., called structure with in the
structure or nested structure.
Ex: structure
{
member 1;
member 2;

struct
{
member 1;
member 2;
}name2;

member m;
}name1;
For accessing the member 1 if inner structure we write as, name1.name2.member1;
Size of a Structure:
We normally use structures, and arrays to create variables of large sizes. The actual size
of these variables in terms of bytes may change from machine to machine. We may use the
unary operator sizeof to tell us the size of a structure (or any variable).
Sizeof (struct x)
Will evaluate the number of bytes required to hold all the members of the structure x.

Page 18
Programming for Problem Solving using C UNIT-3

Program: #include<stdio.h>
main()
{
struct stinfo
{
char name[20];
char pin[18];
char address[15];
int total_marks;
}a;
printf(“ The size of the structure is %d:”,sizeof(a));
}

Self referential structure


A self referential structure is one which contains a pointer to its own type. This type of
structure is also known as linked list.
Ex: struct node
{
int data;
struct node *next ptr;
};
A structure of type struct node has two members, integer member data and pointer
member next ptr. Member next ptr points to a structure of type struct node- a structure of
same type as one being declared here, known as self referential structure.
UNION
A union contains members of different data type.
When a union is declared, compiler allocates memory locations to hold largest data type
member in the union. Union is used to save memory. Union is useful when it is not necessary
to assign the values to all the members of the union at a time.
Declaration: union name
{
member 1;
member 2;

member n;
}

Page 19
Programming for Problem Solving using C UNIT-3

Comparison between array and structure:


Array Structure
1. stores homogenous data 1. stores heterogeneous data
2. two arrays of same type cannot be 2. structures of same type can be
assigned to one another directly assigned
3. array is a combination of elements 3. structure is a combination of
4. multi-dimensional arrays are members
possible 4. no in case of structures
5. an element in array referenced by 5. elements in structure will be
specifying array name and its referenced as...
position in the array. structure. member name
ex: arr[5]

Comparison between structure and union:


Structure Union
1. stores heterogeneous data 1. stores heterogeneous data
2. members are stored separately in 2. members are stored in same
memory location memory locations
3. in str 3. in union only one member is
4. structure all members are available at a time
available 4. occupies less memory when
5. occupies more memory when compared with structures
compared to union 5. size of the union is the size of
6. size of the structure is the total the largest data type member
memory space required by its in the union.
members.

Page 20

You might also like