Introduction To Problem Solving Using C - Unit 4
Introduction To Problem Solving Using C - Unit 4
Introduction To Problem Solving Using C - Unit 4
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]
Here we are learning the different ways of compile time initialization of an array.
Ways of Array Initializing 1-D Array:
1. Size is Specified Directly
2. Size is Specified Indirectly
Method 1: Array Size Specified Directly
In this method, we try to specify the Array Size directly.
int num [5] = {2,8,7,6,0};
In the above example we have specified the size of array as 5 directly in the initialization
statement. Compiler will assign the set of values to particular element of the array.
num[0] = 2; num[1] = 8; num[2] = 7; num[3] = 6; num[4] = 0;
As at the time of compilation all the elements are at specified position So This initializationscheme is
Called as “Compile Time Initialization“.
Graphical Representation:
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
scanf("%d", &loc);
/* loop for the deletion */
while (loc < num)
{
arr[loc - 1] = arr[loc];
loc++;
}
num--; // No of elements reduced by 1
//Print Array
for (i = 0; i < num; i++)
return (0);
}
Output:
Enter no of elements: 5 Enter 5 elements:
34178
3478
1. C Program to delete duplicate elements from an array
int main()
{
int arr[20], i, j, k, size;
scanf("%d", &size);
scanf("%d", &arr[i]);
}
printf("\nArray with Unique list: ");
for (i = 0; i < size; i++)
{
for (j = i + 1; j < size;)
{
if (arr[j] == arr[i])
{
for (k = j; k < size; k++)
{
arr[k] = arr[k + 1];
}
size--;
}
else
j++;
}
}
for (i = 0; i < size; i++)
return (0);
}
Output:
Enter array size: 5 Accept Numbers: 1
3453
Array with Unique list: 1 3 4 5
2. C Program to insert an element in an array
#include<stdio.h>int main()
{
printf("\nEnter no of elements:");
scanf("%d", &num);
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
printf("\nEnter the element to be inserted:");
scanf("%d", &element);
printf("\nEnter the location");
scanf("%d", &location);
//Create space at the specified location
for (i = num; i >= location; i--)
{
arr[i] = arr[i - 1];
}
num++;
arr[location - 1] = element;
//Print out the result of insertion
for (i = 0; i < num; i++)
printf("n %d", arr[i]);
return (0);
}
Output:
Enter no of elements: 51 2 3 4 5
Enter the element to be inserted: 6
Enter the location: 2
162345
3. C Program to search an element in an array
#include<stdio.h>int main()
{
int a[30], ele, num, i;
printf("\nEnter no of elements:");
scanf("%d", &num);
printf("\nEnter the values :");
for (i = 0; i < num; i++)
{
scanf("%d", &a[i]); }
//Read the element to be searched
printf("\nEnter the elements to be searched :");
scanf("%d", &ele);
//Search starts from the zeroth location
i = 0;
while (i < num && ele != a[i])
{
i++;
}
//If i < num then Match found
if (i < num)
{
printf("Number found at the location = %d", i + 1);
}
else
{
printf("Number not found");
return (0);
}
Output:
Enter no of elements: 5
11 22 33 44 55
Enter the elements to be searched: 44
Number found at the location = 4
4. C Program to copy all elements of an array into another array
#include<stdio.h>int main()
{
int arr1[30], arr2[30], i, num;
printf("\nEnter no of elements:");
scanf("%d", &num);
//Accepting values into Array
printf("\nEnter the values:");
for (i = 0; i < num; i++)
{
scanf("%d", &arr1[i]);
}
/* Copying data from array 'a' to array 'b */
for (i = 0; i < num; i++)
{
arr2[i] = arr1[i];
}
//Printing of all elements of array
{
res[k] = arr1[i];i++;
k++;
}
Else
{
res[k] = arr2[j];
k++;
j++;
}
}
/*Some elements in array 'arr1' are still remaining where as the array'arr2' is exhausted*/
while (i < n1)
{
res[k] = arr1[i];
i++;
k++;
}
/*Some elements in array 'arr2' are still remaining where as the array'arr1' is exhausted */
while (j < n2)
{
res[k] = arr2[j];
k++;
j++;
}
//Displaying elements of array 'res'
11 22 33 44
Enter no of elements in 2nd array: 3
10 40 80
Merged array is: 10 11 22 33 40 44 80
Multidimensional arrays
/* Output */
Large = 136
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
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.
Index 0 1 2 3 4 5 6 7 8
Value c o m p u t e r \0
ch
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++;
}
Output
printf("The number of vowels %d",count);
}
Output :The number of vowels 3
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
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<st
dio.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
Example
main()
{
struct student
{
int rollno; int
attendance;
};
struct student s1={786, 98};struct
student s2={123, 97};
}
Note:
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 a
separate 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.basicpay
e1.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