0% found this document useful (0 votes)
2 views44 pages

Unit IV

The document provides an overview of arrays in C programming, detailing their types, declaration, initialization, and usage. It explains one-dimensional and two-dimensional arrays, including how to create and manipulate them, as well as the concept of strings in C. Additionally, it covers string initialization, reading, writing, and string handling functions available in C.

Uploaded by

abolimes4444
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views44 pages

Unit IV

The document provides an overview of arrays in C programming, detailing their types, declaration, initialization, and usage. It explains one-dimensional and two-dimensional arrays, including how to create and manipulate them, as well as the concept of strings in C. Additionally, it covers string initialization, reading, writing, and string handling functions available in C.

Uploaded by

abolimes4444
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 44

UNIT IV

ARRAY

Presented by :
Prof.Supriya Jadhav-Deshmukh
Introduction

An array is a fixed size sequenced collection of elements of the same data type.

An array is a linear and homogeneous data structure

In its simplest form, an array can be used to represent a list of numbers, or a list of
names.

Some examples where the concept of an array can be used:

List of temperatures recorded every hour in a day, or a month, or a year.

List of employees in an organization.

List of products and their cost sold by a store.

List of customers and their telephone numbers.

Table of daily rainfall data.
Cont...

Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.


To create an array, define the data type (like int) and specify the
name of the array followed by square brackets [].


To insert values to it, use a comma-separated list inside curly
braces, and make sure all values are of the same data type:

int myNumbers[] = {25, 50, 75, 100};
C supports a rich set of derived and user-defined data types in
addition to variety of fundamental types.

10

0
Cont...

We can use arrays to represent not only simple
lists of values but also tables of data in two,
three or more dimensions.

Arrays is of have following types:
One-dimensional arrays
Two-dimensional arrays
Multidimensional arrays
One-dimensional arrays

A one-dimensional array can be viewed as a
linear sequence of elements.

We can only increase or decrease its size in a
single direction.
Cont…

Only a single row exists in the one-dimensional
array and every element within the array is
accessible by the index.

In C, array indexing starts zero-indexing i.e. the
first element is at index 0, the second at index
1, and so on up to n-1 for an array of size n.
1D Array Declaration Syntax

In declaration, we specify then name and the size of
the 1d array.

elements_type array_name[array_size];

In this step, the compiler reserved the given amount of
memory for the array but this step does not define the
value of the elements.

They may contain some random values.

So we initialize the array to give its elements some
initial value.
1D Array Initialization Syntax

In declaration, the compiler reserved the given amount
of memory for the array but does not define the value
of the element.

To assign values, we have to initialize an array.

elements_type array_name[array_size] = {value1,
value2, ... };

This type of The values will be assigned sequentially,
means that first element will contain value1, second
value2 and so on.
Cont…
Example of One Dimensional Array in C for compile time
initilization

// C program to illustrate how to create an array, 
}

// initialize it, update and access elements 
printf("\n");

#include <stdio.h> 
// updating elements

int main() 
arr[3] = 9721;

{ 
// printing again

// declaring and initializing array 
for (int i = 0; i < 5; i++) {

int arr[5] = { 1, 2, 4, 8, 16 }; 
printf("%d ", arr[i]);

// printing it 
}

for (int i = 0; i < 5; i++) 
Return 0;

{ 
}

<

printf("%d ", arr[i]);

// C program to illustrate how to create an OUTPUT:
array,

// initialize it, update and access elements 1 2 4 8 16
1 2 4 9721 16
Example of One Dimensional Array in C for run time initilization
#include <stdio.h> scanf("%d", &arr[i]);
sum += arr[i]; // Adding each element to sum

int main() { }

int n, sum = 0;
float average; // Calculating the average
average = (float)sum / n;

// Asking the user for the number of elements


printf("Enter the number of elements: "); // Printing the average
printf("The average of the elements is: %.2f\n", average);
scanf("%d", &n);

return 0;
int arr[n]; // Declare an array of size n
}

OUTPUT:
// Asking the user to input the array elements
Enter the number of elements : 4
printf("Enter %d elements:\n", n);
Enter a value:7
Two-Dimensional Array (2D Array)

A two-dimensional array or 2D array is the
simplest form of the multidimensional array. We
can visualize a two-dimensional array as one-
dimensional arrays stacked vertically forming a
table with ‘m’ rows and ‘n’ columns.

In C, arrays are 0-indexed, so the row number
ranges from 0 to (m-1) and the column number
ranges from 0 to (n-1).
2-D Array
Declaration of 2D Array

A 2D array with m rows and n columns can be created as:
type arr_name[m][n];

Where,

type: Type of data to be stored in each element.

arr_name: Name assigned to the array.

m: Number of rows.

n: Number of columns.

For example, we can declare a two-dimensional integer array with name
‘arr’ with 10 rows and 20 columns as:
Initialize a 2D Array in C

In C, a 2D Array is a type of multidimensional
array in which data is stored in tabular form
(rows and columns).

It has two dimensions so it can store the data
and can expand in two directions.

In this article, we will learn how to initialize a 2D
array in C.
There are three main ways to
initialize the 2D array in C:

List Initilization

Initilization with Zero

Runtime Initilization using loops.
List Initialization

To initialize a 2D array, we can use a list of values enclosed inside the
braces '{ }' and separated by a comma. Each value in this list
corresponds to an element in the array.

Syntax:

int arr[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}

The first 4 elements from the left will be filled in the first row, the next 4
elements in the second row, and so on. We can also explicitly do this as:

int arr[3][4] = {{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 10, 11}};
C Program to Initialize 2D Array Using Initializer Lists
Initialization with Zero

We can initialize all the elements of a numeric,
character or binary 2D array to the value 0
using the below syntax:

int arr[3][4] = {0}
C Program to Zero Initialize 2D
Array
Runtime Initialization Using Loops

All the above methods were static initialization, i.e. element
values are defined before the compilation.

When we want to initialize the 2D array elements one by one at
runtime with the values that have some sequential relation or
taking input from any source, it is better to use loops.

We use two loops, one nested inside other. The outer loop is
used to go from row to row and the inner loop is used to
initialize each element in that row.
C Program to Initialize 2D Array Using Loops
Strings in C

A String in C programming is a sequence of
characters terminated with a null character ‘\0’.
The C String is stored as an array of
characters.

The difference between a character array and a
C string is that the string in C is terminated with
a unique character ‘\0’.
C String Declaration Syntax

Declaring a string in C is as simple as declaring a one-
dimensional array. Below is the basic syntax for declaring a
string.

char string_name[size];

In the above syntax string_name is any name given to the string
variable and size is used to define the length of the string, i.e
the number of characters strings will store.

There is an extra terminating character which is the Null
character (‘\0’) used to indicate the termination of a string that
differs strings from normal character arrays.
C String Initialization

A string in C can be initialized in different ways.
We will explain this with the help of an example.
Below are the examples to declare a string with
the name str and initialize it with “MESWCOE”.
We can initialize a C string in 4 different
ways which are as follows:

1. Assigning a String literal without Size

2. Assigning a String literal with a Predefined
Size.

3. Assigning Character by Character with Size

4. Assigning Character by Character without
Size
1. Assigning a String literal without
Size

String literals can be assigned without size.
Here, the name of the string str acts as a
pointer because it is an array.


char str[] = "MESWCOE";
2. Assigning a String with a
Predefined Size

String literals can be assigned with a predefined
size. But we should always account for one
extra space which will be assigned to the null
character. If we want to store a string of size n
then we should always declare a string with a
size equal to or greater than n+1.

char str[50] = "MESWCOE";
3. Assigning Character by Character
with Size

We can also assign a string character by
character. But we should remember to set the
end character as ‘\0’ which is a null character.

char str[10] = { 'M','E','S','W','C','O','E','M','\0'};

4. Assigning Character by
Character without Size

We can assign character by character without
size with the NULL character at the end. The
size of the string is determined by the compiler
automatically.

char str[] = { 'M','E','S','W','C','O','E','M','\0'};
Example
#include <stdio.h>
#include<string.h>
int main()
{
char str[]="MESWCOE";
printf("%s\n",str);
int length=0;
length = strlen(str);
printf("Length of string is %d",length);
return 0;
}

Output:

MESWCOE
Length of string is 7
Reading string from terminal

Using scanf function:


-The familiar input function scanf can be used with %s format
spcification to read in a string of character.
Char address[10];
Scanf(“%s”,address);
Using getchar & gets function

Can read entire line of text and also can stored in


an array by using getchar & gets function.
Char ch;
ch=getchar();
WRITING STRINGS TO SCREEN

Using printf function:


We have used extensively the printf function with %s format to print strings
to the screen. The format %s can be used to display an array of characters
that is terminated by the null character.
1) For example,the statement printf(“%s”, name);
2)can be used to display the entire contents of the array name.
Using putchar and puts Functions:
-Like getchar ,c supports another character handling function
putchar to output the values of character variable.
char ch = ‘A’;
putchar (ch);
The function putchar requires one parameter. This statement
is equivalent to:
» printf(“%c”, ch);
PUTTING STRINGS TOGETHER
We cannot join two string together by simple arithmetic function such as,
string3 = string1 + string2;
string2 = string1 + “hello”;
are not valid. The characters from string1 and string2 should be copied
into the string3 one after the other.
The size of the array string 3 should be large enough to hold the total
characters.
The process of combinning two strings together is called concatenation.
Example
The names of an employyes of an organization
are stored in three arrays namely
first_name,second_name & last_name.Write a
program to concatenate the three parts into one
string to be called name.
main() /* End second_name with a space */
{ name[i+j+1] = ‘ ‘ ;
int i, j, k ; /* Copy last_name into name */
char first_name[10] = for( k = 0 ; last_name[k] != ‘\0’; k++ )
{“VISWANATH”} ; name[i+j+k+2] = last_name[k] ;
char second_name[10] = /* End name with a null character */
{“PRATAP”} ; name[i+j+k+2] = ‘\0’ ;
char last_name[10] = {“SINGH”} ; printf(“\n\n”) ;
char name[30] ; printf(“%s\n”, name) ;
/* Copy first_name into name */ }
for( i = 0 ; first_name[i] != ‘\0’ ; i++ )
name[i] = first_name[i] ;
/* End first_name with a space */
name[i] = ‘ ‘ ;
COMPARISON OF TWO STRINGS
C does not permit to campare two strings directly,That is the statements
such as,
if(name1 == name2)
if(name == “ABC”)
Are not permitted.
It is therefor neccessary to compare the two strings to be tested, character
by character.
The comparison is done until there is a mismatch or one of the strings
terminates into a null character, whichever occur first.
example
i=0;
while(str1[i] == str2[i] && str1[i] != ‘\0’
&& str2[i] != ‘\0’)
i = i+1;
if (str1[i] == ‘\0’ && str2[i] == ‘\0’)
printf(“strings are equal\n”);
else
printf(“strings are not equal\n”);
STRING-HANDLING FUNCTIONS
C supports a large no. Of string handling functions that
can be used to carry many of the string manuplation.
Strlen() :Gives the length of str1lculates
Strncpy ( ):Copies given number of characters of one string
to anothert
strcmp ( ) : Returns 0 if str1 is same as str2. Returns <0 if
strl < str2. Returns >0 if str1 > str2
Strcat ( ):Concatenates str2 at the end of str1he length of
stringcalculates the length of string

You might also like