Programming For Problem Solving Using C Unit-Iii: Arrays
Programming For Problem Solving Using C Unit-Iii: Arrays
Programming For Problem Solving Using C Unit-Iii: Arrays
UNIT-III
Arrays:-
An array is a group of related data items that share a common
name. Ex:-Students
The complete set of students are represented using an array
name students.
A particular value is indicated by writing a number called index
number or subscript in brackets after array name.
The complete set of value is referred to as an array, the
individual values are called elements.
Using Array in C:-
to store list of Employee or Student names,
to store marks of students,
or to store list of numbers or characters etc.
WWW.JNTUKNOTES.COM 1
We use two dimensional arrays to create matrix. We can perform
various operations on matrices using two dimensional arrays.
Arrays are used to Perform Matrix Operations
We use two dimensional arrays to create matrix. We can
perform various operations on matrices using two dimensional
arrays.
Arrays are used to implement Search Algorithms
We use single dimensional arrays to implement search
algorihtms like ...
1.
Linear search
2.
Binary search
Arrays are used to implement Sorting Algorithms
We use single dimensional arrays to implement sorting
algorithms like ...
1. Insertion sort
2. Bubble sort
3. Selection sort
4. Quick sort
5. Merge sort
ONE – DIMENSIONAL ARRAYS :-
A list of items can be given one variable index is called single
subscripted variable or a one-dimensional array.
The subscript value starts from 0. If we want 5 elements the
declaration will be
int number[5];
WWW.JNTUKNOTES.COM 2
Ex:- float avg[50]
This array is of type float. Its name is avg. and it can contains 50 elements only.
The range starting from 0 – 49 elements.
Initialization of Arrays :-
Initialization of elements of arrays can be done in same way as
ordinary variables are done when they are declared.
#include<stdio.h>
#include<math.h>
#define ROWS 5
#define COLS 5
main()
{
int row,cols,prod[ROWS][COLS];
int i,j;
printf(“Multiplication table”);
for(j=1;j< =COLS;j++)
printf(“%d”,j);
for(i=0;i<ROWS;i++)
{
row = i+1;
printf(“%2d|”,row);
for(j=1;j < = COLS;j++)
{
WWW.JNTUKNOTES.COM 3
COLS=j;
prod[i][j]= row * cols;
printf(“%4d”,prod*i+*j+);
}
}
}
INITIALIZING TWO DIMENSIONAL ARRAYS:-
They can be initialized by following their declaration with a list of
initial values enclosed in braces.
Initializes the elements of first row to zero and second row to one. The
initialization is done by row by row. The above statement can be written as
int table[2][3] = {{0,0,0},{1,1,1}};
type array_name[d1][d2][d3][d4]………[dn];
WWW.JNTUKNOTES.COM 4
In Example 1:
int designates the array type integer.
table is the name of our 3D array.
Our array can hold 500 integer-type elements. This number
is reached by multiplying the value of each dimension. In this
case: 5x5x20=500.
In Example 2:
Array arr is a five-dimensional array.
It can hold 4500 floating-point elements (5x6x5x6x5=4500).
Initializing a 3D Array in C:-
Like any other variable or array, a 3D array can be initialized at
the time of compilation. By default, in C, an uninitialized 3D array
contains “garbage” values, not valid for the intended use.
Let’s see a complete example on how to initialize a 3D array:-
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, k;
int arr[3][3][3]=
{
{
{11, 12, 13},
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
},
};
clrscr();
printf(":::3D Array Elements:::\n\n");
for(i=0;i<3;i++)
WWW.JNTUKNOTES.COM 5
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
printf("%d\t",arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
getch();
}
Programming Example – Calculate Averages:-
This program takes n number of element from user (where, n is
specified by user), stores data in an array and calculates the average of
those numbers.
int main()
{
int n, i;
float num[100], sum = 0.0, average;
average = sum / n;
printf("Average = %.2f", average);
return 0;
WWW.JNTUKNOTES.COM 6
}
Output
Enter the numbers of elements: 6
1. Enter number: 45.3
2. Enter number: 67.5
3. Enter number: -45.6
4. Enter number: 20.34
5. Enter number: 33
6. Enter number: 45.6
Average = 27.69
Strings:-
A String is an array of characters. Any group of characters (except
double quote sign )defined between double quotes is a constant string.
1. By char array
2. By string literal
WWW.JNTUKNOTES.COM 7
C also permits us to initializing a String without specifying size.
gets():
Declaration:
Reads a line from stdin and stores it into the string pointed to
by str. It stops when either the newline character is read or when the end-of-
file is reached, whichever comes first. The newline character is not copied to
the string. A null character is appended to the end of the string.
WWW.JNTUKNOTES.COM 8
puts:
Declaration:
STRING HANDLING/MANIPULATION FUNCTIONS:-
strcat( ) Concatenates two Strings
strcmp( ) Compares two Strings
strcpy( ) Copies one String Over another
strlen( ) Finds length of String
strcat() function:
strcat(string1,string2);
string1 = VERY
string2 = FOOLISH
strcat(string1,string2);
string1=VERY FOOLISH
string2 = FOOLISH
WWW.JNTUKNOTES.COM 9
strcmp(string1,string2);
Ex:- strcmp(name1,name2);
strcmp(name1,”John”);
strcmp(“ROM”,”Ram”);
strcpy(string1,string2);
string2 can be array or a constant.
n= strlen(string);
n integer variable which receives the value of length of string.
String/ Data Conversion:-
atof :- convert a string to a double precision number.
Usage
Double_Type atof (String_Type s)
atoi:- convert a string to an integer
WWW.JNTUKNOTES.COM 10
Usage
Int_Type atoi (String_Type str)
atol:- convert a string to an long integer.
Usage
Long_Type atol (String_Type str)
char:- convert a character code to a string.
Usage
String_Type char (Integer_Type c)
A Programming Example – Morse Code:-
WWW.JNTUKNOTES.COM 11
We're gonna make an array with these values. Actually , just for the
alphabet (a through z). The rest don't really matter that much.
int main()
{
int i;
char input[255], morse['o ---', '--- o o o', '--- o --- o', '--- o o', 'o',
'o o --- o', '--- --- o', 'o o o o', 'o o', 'o ----------- ',
'--- o ---', 'o --- o o', '--- ---', '--- o', ' ---------- ',
'o --- --- o', '--- --- o ---', 'o --- o', 'o o o', '--- ',
'o o ---', 'o o o ---', 'o --- ---', '--- o o ---', '--- o ---
---',
' ------ o o']
gets(string);
return 0;
}
The Type Definition (Type def):-
WWW.JNTUKNOTES.COM 12
The C programming language provides a keyword called
typedef, which you can use to give a type a new name.
Following is an example to define a term BYTE for one-
byte numbers –
typedef unsigned char BYTE;
After this type definition, the identifier BYTE can be used as
an abbreviation for the type unsigned char, for example..
You can use typedef to give a name to your user defined data
types as well. For example, you can use typedef with structure
to define a new data type and then use that data type to define
structure variables directly as follows –
#include <stdio.h>
#include <string.h>
int main( ) {
Book book;
strcpy( book.title, "C Programming");
strcpy( book.author, "Nuha Ali");
strcpy( book.subject, "C Programming
Tutorial"); book.book_id = 6495407;
return 0;
}
WWW.JNTUKNOTES.COM 13
When the above code is compiled and executed, it produces
the following result –
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Enumerated Types:-
Enumeration (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.
Here is the syntax of enum in C language
enum enum_name{const1, const2, ......... };
WWW.JNTUKNOTES.COM 14
In the above program, two enums are declared as week and
day outside the main() function. In the main() function, the
values of enum elements are printed.
Structure:-
Arrays allow to define type of variables that can hold several data
items of the same kind. Similarly structure is another user
defined data type available in C that allows to combine data items
of different kinds.
Structures are used to represent a record. Suppose you want to
keep track of your books in a library. You might want to track the
following attributes about each book –
Title
Author
Subject
Book ID
Defining a Structure:-
To define a structure, you must use the struct statement. The
struct statement defines a new data type, with more than one
member. The format of the struct statement is as follows –
WWW.JNTUKNOTES.COM 15
member that we wish to access. You would use the keyword
struct to define variables of structure type.
The following example shows how to use a structure in a
program −
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
WWW.JNTUKNOTES.COM 16
When the above code is compiled and executed, it produces
the following result −
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Defining a Union:-
To define a union, you must use the union statement in the same
way as you did while defining a structure.
The union statement defines a new data type with more than one
member for your program.
The format of the union statement is as follows −
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
WWW.JNTUKNOTES.COM 17
The union 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.
union Data {
int i;
float f;
char str[20];
} data;
WWW.JNTUKNOTES.COM 18
between the union variable name and the union member that
we wish to access.
You would use the keyword union to define variables of
union type. The following example shows how to use unions in
a program –
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Programming Application:-
Mainly C Language is used for Develop Desktop application and
system software. Some application of C language are given below.
WWW.JNTUKNOTES.COM 19
To evaluate any kind of mathematical equation use c language.
C programming language can be used to design the compilers.
UNIX Kernal is completely developed in C Language.
For Creating Compilers of different Languages which can take
input from other language and convert it into lower level machine
dependent language.
C programming language can be used to design Operating System.
C programming language can be used to design Network Devices.
WWW.JNTUKNOTES.COM 20