INTRODUCTION TO PROBLEM SOLVING USING C - Unit 4new
INTRODUCTION TO PROBLEM SOLVING USING C - Unit 4new
Array
Array is the group of identical elements organized in a single variable. An array
is a collection of data that holds fixed number of values of same type. For example: if
you want to store marks of 100 students, you can create an array for it.
int mark[100];
Array Declaration:
Array has to be declared before using it in C Program. Array is nothing but the collection of elements of
similar data types.
Syntax: <data type> array name [size1][size2] .......... [sizen];
Valid identifier is any valid variable or name given to the array. Using
Valid Identifier this identifier name array can be accessed.
i. One-dimensional arrays
int mark[5] = {19, 10, 8, 17, 9};
Arrays have 0 as the first index not 1. In this example, mark[0]
If the size of an array is n, to access the last element, (n-1) index is used. In this
example, mark[4]
return 0;
}
Output:
Accessing Array
1. We all know that array elements are randomly accessed using the subscript variable.
2. Array can be accessed using array-name and subscript variable written inside pair ofsquare
brackets [ ].
Consider the below example of an array
Element at arr[1] is 32
Element at arr[2] is 43
Element at arr[3] is 24
Element at arr[4] is 5
Element at arr[5] is 26
So whenever we tried accessing array using arr[i] then it returns an element at the location*(arr
+ i)
Accessing array a[i] means retrieving element from address (a + i).
Example Program2: Accessing array
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++) {
printf("\n%d %d %d %d",arr[i],*(i+arr),*(arr+i),i[arr]);
}
getch();
}
Output:
51 51 51 51
32 32 32 32
43 43 43 43
24 24 24 24
5 5 5 5
26 26 26 26
Multidimensional arrays
In C programming, you can create an array of arrays known as multidimensional array. For
example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the
arrayas table with 3 row and each row has 4 column.
Similarly, you can declare a three-dimensional (3d) array. For example, float
y[2][4][3];
Here, The array y can hold 24 elements.
Example : Each 2 elements have 4 elements, which makes 8 elements and each 8 elements
can have 3 elements. Hence, the total number of elements is 24.
Output :
Enter the array elements : 1 2 3 4 5
Passing entire array .....
After Function call a[0] : 11
After Function call a[1] : 12
After Function call a[2] : 13
After Function call a[3] : 14
After Function call a[4] : 15
int arr[5],i;
clrscr();
printf("\nEnter the array elements : ");
for(i=0;i< 5;i++)
scanf("%d",&arr[i]);
printf("\nPassing array element by element ............................... ");
for(i=0;i< 5;i++)
fun(arr[i]); getch();
}
Output:
Enter the array elements : 1 2 3 4 5
char ch[10]={'c', 'o', 'm', 'p', 'u', 't', 'e', 'r', ''\0'};
or
char ch[10]="computer”
As we know, array index starts from 0, so it will be represented as in the figure given
below.ch
Index 0 1 2 3 4 5 6 7 8
Value c o m p u t e r \0
Example
Let's see an example of counting the number of vowels in a
string. #include<stdio.h>
void main ()
{
char s[11] =
"computer";int i =
0;
int
count =
0;
while(i
<11)
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
STRINGS
A string is a sequence of character enclosed with in double quotes (“”) but ends with
\0. The compiler puts \0 at the end of string to specify the end of the string.
To get a value of string variable we can use the two different types of formats.
Using scanf() function as: scanf(“%s”, string variable);
C library supports a large number of string handling functions. Those functions are stored underthe header
file string.h in the program.
Syntax
strcat (StringVariable1, StringVariable 2);
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
char str1[20],str2[20];clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
printf(‚ Concatenation String is:%s‛, strcat(str1,str2));getch();
}
Output:
Enter First String:Good
Enter Second String
Morning
Concatenation String is: GoodMorning
(iii) strcmp() function
strcmp() function is used to compare two strings. strcmp() function does a case sensitive
comparison between two strings. The two strings are compared character by character until there is a
mismatch or end of one of the strings is reached (whichever occurs first). If the two strings are identical,
strcmp( ) returns a value zero. If they‟re not, it returns the numeric difference between the ASCII values
of the first non-matching pairs of characters.
Syntax
strcmp(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
char str1[20], str2[20];int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
res = strcmp(str1,str2);
printf(‚ Compare String Result is:%d‛,res);
getch();
}
Output:
Enter First StringGood
Enter Second StringGood
Compare String Result is: 0
strcmpi() function is used to compare two strings. strcmpi() function is not case sensitive.
Syntax
strcmpi(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
char str1[20], str2[20];
int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
res = strcmpi(str1,str2);
printf(‚ Compare String Result is:%d‛,res);getch();
}
Output:
Enter First String
WELCOME
Enter Second String
welcome
Compare String Result is: 0
(v) strcpy() function:
strcpy() function is used to copy one string to another. strcpy() function copy the contents ofsecond
string to first string.
Syntax
strcpy(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
char str1[20], str2[20];int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2); strcpy(str1,str2)
printf(‚ First String is:%s‛,str1);printf(‚ Second
String is:%s‛,str2);getch();
}
Output:
Enter First StringHello
Enter Second String
welcome
First String is: welcomeSecond
String is: welcome
(vi) strlwr () function:
This function converts all characters in a given string from uppercase to lowercase letter.
Syntax
strlwr(StringVariable);
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
char str[20];
clrscr();
printf(‚Enter String:‛);gets(str);
printf(‚Lowercase String : %s‛, strlwr(str));getch();
}
Output:
Enter String
WELCOME
Lowercase String : welcome
(vii) strrev() function:
strrev() function is used to reverse characters in a given string.
Syntax
strrev(StringVariable);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
printf(‚Enter String:‛);gets(str);
printf(‚Reverse String : %s‛, strrev(str));getch();
}
Output:
Enter String
WELCOME
Reverse String : emoclew
(viii) strupr() function:
strupr() function is used to convert all characters in a given string from lower case to
uppercase letter.
Syntax
strupr(Stringvariable);
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
char str[20];
clrscr();
printf(‚Enter String:‛);gets(str);
printf(‚Uppercase String : %s‛, strupr(str));getch();
}
Output:
Enter String
welcome
Uppercase String : WELCOME
Structures
A structure is a user defined data type in C. A structure creates a data type that can be used to
groupitems of possibly different types into a single type.
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new
datatype, with more than one member. The format of the struct statement is as follows −
struct [structure
tag] {member
definition;
member
definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition, such
as int i; or float f; or any other valid variable definition. At the end of the structure's
definition, before the final semicolon, you can specify one or more structure variables but it is
optional. Here is the way we would declare the Book structure −
struct Books
{ char
title[50];
char
author[50]
;
char
subject[100];
int book_id;
} book;
How to access structure elements?
Structure members are accessed using dot (.) operator.
Syntax
STRUCTURE_Variable.STRUCTURE_Members
#include<stdio.h>
struct Point
{
int x, y;
};
void main()
{
struct Point p1 = {0, 1};
/* Accessing members of point
p1 */p1.x = 20;
printf ("x = %d, y = %d", p1.x, p1.y);
}
Output:
x = 20, y = 1
Structure Initialization
Like variables, structures can also be initialized at the compile time.
Example
main()
{
struct
{
int rollno; int
attendance;
}
s1={786, 98};
}
The above example assigns 786 to the rollno and 98 to the attendance. Structure
variable can be initialized outside the function also.
Example
main()
{
struct student
{
int rollno;
int attendance;
};
struct student s1={786, 98};
struct student s2={123, 97};
}
Individual structure members cannot be initialized within the template. Initialization ispossible only
with the declaration of structure members.
Example
struct employee
{
int empid;
char empname[20];
int basicpay;
int da;
int hra;
int cca;
} e1;
In the above structure, salary details can be grouped together and defined as aseparate
structure.
Example
struct employee
{
int empid;
char empname[20];
struct
{
int basicpay;
int da;
int hra;
int cca;
} salary;
} e1;
The structure employee contains a member named salary which itself is another structure that
contains four structure members. The members inside salary structure can be referred as below:
e1.salary.basicpay
e1.salary.da; e1.salary.hra;
e1.salary.cca;
However, the inner structure member cannot be accessed without the inner structure variable.
Example
e1.basicpaye1.da
e1.hra e1.cca
are invalid statements
Moreover, when the inner structure variable is used, it must refer to its inner structure member.
If it doesn‟t refer to the inner structure member then it will be considered as an error.
Example
e1.salary (salary is not referring to any inner structure member. Hence it is wrong)
Array of structures
Like other primitive data types, we can create an array of structures.
Example
struct Point
{
int x, y;
};
void main()
{
// Create an array of structures
struct Point p[10];
In the below example student structure having id, name and percentage attributes. record
is the variable to control entire structure.
Example:
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student record)
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.5