0% found this document useful (0 votes)
8 views17 pages

ppc unit 3 ref material 2022-23

The document provides an overview of arrays and strings in C programming, detailing their declaration, initialization, and operations. It covers one-dimensional and two-dimensional arrays, including examples of how to declare, initialize, and access elements, as well as the importance of avoiding out-of-bounds access. Additionally, it introduces strings as arrays of characters, discusses string handling functions, and emphasizes the use of the string.h library for string manipulations.

Uploaded by

msaturn860
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)
8 views17 pages

ppc unit 3 ref material 2022-23

The document provides an overview of arrays and strings in C programming, detailing their declaration, initialization, and operations. It covers one-dimensional and two-dimensional arrays, including examples of how to declare, initialize, and access elements, as well as the importance of avoiding out-of-bounds access. Additionally, it introduces strings as arrays of characters, discusses string handling functions, and emphasizes the use of the string.h library for string manipulations.

Uploaded by

msaturn860
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/ 17

UNIT-III 06 Hours

Arrays: Introduction, One dimensional array, Declaration of one-dimensional array,


Initialization of one-dimensional array. Declaration of two-dimensional array,
Initialization of two-dimensional array. Operations on array

Strings: Introduction, Declaring and initializing string variables, String-handling


functions, Array of string.

Array:
Introduction, Array is a kind of data structure that can store a fixed-size sequential collection
of elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by
an index. All arrays consist of contiguous memory locations. The lowest address corresponds
to the first element and the highest address to the last element.

An array is defined as finite ordered collection of homogenous data, stored in contiguous


memory locations. In C language, arrays are referred to as structured data types.
finite means data range must be defined.
ordered means data must be stored in continuous memory addresses.
homogenous means data must be of similar data type.

Example where arrays are used,


To store list of Employee or Student names,
To store marks of students, or to store list of numbers or characters etc.

Since arrays provide an easy way to represent data, it is classified amongst the data
structures in C. Other data structures in c are structure, lists, queues, trees etc. Array can be
used to represent not only simple list of data but also table of data in two or three dimensions.

One dimensional arrays, Declaration of one-dimensional arrays, Initialization of one-


dimensional arrays.

A one-dimensional array is a structured collection of components (often called array


elements) that can be accessed individually by specifying the position of a component with a
single index value.

Declaring an Array, Like any other variable, arrays must be declared before they are used.
General form of array declaration is,

data-type variable-name[size];

/* Example of array declaration */

int arr[10];
Here int is the data type, arr is the name of the array and 10 is the size of array. It means
array arr can only contain 10 elements of int type. Index of an array starts from 0 to size-1 i.e
first element of arr array will be stored at arr[0] address and the last element will
occupy arr[9].

Initialization of an Array, After an array is declared it must be initialized. Otherwise, it will


contain garbage value(any random value). An array can be initialized at either compile
time or at runtime.

Compile time Array initialization, Compile time initialization of array elements is same as
ordinary variable initialization. The general form of initialization of array is,

data-type array-name[size] = { list of values };

/* Here are a few examples */


int marks[4]={ 67, 87, 56, 77 }; // integer array initialization

float area[5]={ 23.4, 6.8, 5.5 }; // float array initialization

int marks[4]={ 67, 87, 56, 77, 59 }; // Compile time error

One important thing to remember is that when you will give more initialize (array elements)
than the declared array size than the compiler will give an error.

#include<stdio.h>
void main()
{
int i;
int arr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}

Out put
2 3 4

Runtime Array initialization, An array can also be initialized at runtime


using scanf() function. This approach is usually used for initializing large arrays, or to
initialize arrays with user specified values. Example,

#include<stdio.h>
void main()
{
int arr[4];
int i, j;
printf("Enter array element");
for(i = 0; i < 4; i++)
{
scanf("%d", &arr[i]); //Run time array initialization
}
for(j = 0; j < 4; j++)
{
printf("%d\n", arr[j]);
}
}

Accessing Array Elements, An element is accessed by indexing the array name. This is done
by placing the index of the element within square brackets after the name of the array. For
example double salary = balance[9];

The above statement will take the 10th element from the array and assign the value to salary
variable.

The following example shows how to use all the three above mentioned concepts viz.
declaration, assignment, and accessing arrays,

#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;

/* initialize elements of array n to 0 */


for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}

/* output each array element's value */


for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}

When the above code is compiled and executed, it produces the following result,
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
#include <stdio.h>

int main()
{
int values[5];

printf("Enter 5 integers: ");

// taking input and storing it in an array


for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of an array


for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}

Output
Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3

Here, we have used a for loop to take 5 inputs from the user and store them in an array. Then,
using another for loop, these elements are displayed on the screen.
// Program to find the average of n numbers using arrays

#include <stdio.h>
int main() {

int marks[10], i, n, sum = 0, average;

printf("Enter number of elements: ");


scanf("%d", &n);
for(i=0; i < n; ++i) {
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);

// adding integers entered by the user to the sum variable


sum += marks[i];
}
average = sum / n;
printf("Average = %d", average);

return 0;
}

Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39

Here, we have computed the average of n numbers entered by the user.

Access elements out of its bound!


Suppose you declared an array of 10 elements. Let's say, int testArray[10]; You can access the
array elements from testArray[0] to testArray[9].

Now let's say if you try to access testArray[12]. The element is not available. This may cause
unexpected output (undefined behavior). Sometimes you might get an error and some other
time your program may run correctly. Hence, you should never access elements of an array
outside of its bound.

Arrays in Detail
Arrays are important to C and should need a lot more attention. The following important
concepts related to array should be clear to a C programmer,

Sr.No. Concept & Description


1 Multi-dimensional arrays
C supports multidimensional arrays. The simplest form of the
multidimensional array is the two-dimensional array.
2 Passing arrays to functions
You can pass to the function a pointer to an array by specifying the
array's name without an index.
3 Return array from a function
C allows a function to return an array.
4 Pointer to an array
You can generate a pointer to the first element of an array by simply
specifying the array name, without any index.

Declaration of two-dimensional arrays, Initialization of two-dimensional arrays.

Two dimensional Arrays, C language supports multidimensional arrays also. The simplest
form of a multidimensional array is the 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. Both the row's and column's index
begins from 0.

Two-dimensional arrays are declared as follows,

data-type array-name[row-size][column-size]

/* Example */
int a[3][4];

An array can also be declared and initialized together. For example,

int arr[][3] = { {0,0,0}, {1,1,1}};

Note: We have not assigned any row value to our array in the above example. It means we
can initialize any number of rows. But, we must always specify number of columns, else it
will give a compile time error. Here, a 2*3 multi-dimensional matrix is created.
Runtime initialization of a two dimensional Array
#include<stdio.h>

void main()
{
int arr[3][4];
int i, j, k;
printf("Enter array element");
for(i = 0; i < 3;i++)
{
for(j = 0; j < 4; j++)
{
scanf("%d", &arr[i][j]);
}
}
for(i = 0; i < 3; i++)
{
for(j = 0; j < 4; j++)
{
printf("%d", arr[i][j]);
}
}
}
// C program to find the sum of two matrices of order 2*2

#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}

// Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}

// Displaying the sum


printf("\nSum Of Matrix:");

for (int i = 0; i < 2; ++i)


for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", result[i][j]);

if (j == 1)
printf("\n");
}
return 0;
}

Output
Enter elements of 1st matrix
Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;

Sum Of Matrix:
2.2 0.5
-0.9 25.0

// C program to store temperature of two cities of a week and display it.

#include <stdio.h>

const int CITY = 2;


const int WEEK = 7;

int main()
{
int temperature[CITY][WEEK];

// Using nested loop to store values in a 2d array


for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d: ", i + 1, j + 1);
scanf("%d", &temperature[i][j]);
}
}
printf("\nDisplaying values: \n\n");

// Using nested loop to display vlues of a 2d array


for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d = %d\n", i + 1, j + 1, temperature[i][j]);
}
}
return 0;
}

Output
City 1, Day 1: 33
City 1, Day 2: 34
City 1, Day 3: 35
City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 7: 30
City 2, Day 1: 23
City 2, Day 2: 22
City 2, Day 3: 21
City 2, Day 4: 24
City 2, Day 5: 22
City 2, Day 6: 25
City 2, Day 7: 26

Displaying values:

City 1, Day 1 = 33
City 1, Day 2 = 34
City 1, Day 3 = 35
City 1, Day 4 = 33
City 1, Day 5 = 32
City 1, Day 6 = 31
City 1, Day 7 = 30
City 2, Day 1 = 23
City 2, Day 2 = 22
City 2, Day 3 = 21
City 2, Day 4 = 24
City 2, Day 5 = 22
City 2, Day 6 = 25
City 2, Day 7 = 26

Strings: Introduction, Declaring and initializing string variables, String-handling


functions, Arrays of string.

String is a sequence of characters that are treated as a single data item and terminated by a
null character '\0'. Remember that the C language does not support strings as a data type.
A string is actually a one-dimensional array of characters in C language. These are often used
to create meaningful and readable programs.

For example: The string "home" contains 5 characters including the '\0' character which is
automatically added by the compiler at the end of the string.

Declaring and Initializing a string variables:

// valid
char name[13] = "StudyTonight";
char name[10] = {'c','o','d','e','\0'};

// Illegal
char ch[3] = "hello";
char str[4];
str = "hello";

String Input and Output:


%s format specifier to read a string input from the terminal. But scanf() function, terminates
its input on the first white space it encounters. edit set conversion code %[..] that can be used
to read a line containing a variety of characters, including white spaces.

The gets() function can also be used to read character string with white spaces

char str[20];
printf("Enter a string");
scanf("%[^\n]", &str);
printf("%s", str);

char text[20];
gets(text);
printf("%s", text);
String Handling Functions:
C language supports a large number of string handling functions that can be used to carry out
many of the string manipulations. These functions are packaged in the string.h library. Hence,
you must include string.h header file in your programs to use these functions. The following
are the most commonly used string handling functions.

Method Description
strcat() It is used to concatenate(combine) two strings
strlen() It is used to show the length of a string
strrev() It is used to show the reverse of a string
strcpy() Copies one string into another
strcmp() It is used to compare two string

strcat() function in C: strcat("hello", "world");

strcat() will add the string "world" to "hello" i.e ouput = helloworld.

strlen() and strcmp() function:


strlen() will return the length of the string passed to it and strcmp() will return the ASCII
difference between first unmatching character of two strings.

int j = strlen("studyhard");
int i=strcmp("study ", "hard");
printf("%d %d",j,i);

output
9 -1

strcpy() function: It copies the second string argument to the first string argument.
Example of strcpy() function:

#include<stdio.h>
#include<string.h>

int main()
{
char s1[50], s2[50];

strcpy(s1, "Studyhard");
strcpy(s2, s1);

printf("%s\n", s2);

return(0);
}

Output

Studyhard

strrev() function: It is used to reverse the given string expression.

#include <stdio.h>

int main()
{
char s1[50];

printf("Enter your string: ");


gets(s1);
printf("\nYour reverse string is: %s",strrev(s1));
return(0);
}

Output
Enter your string: studyhard
Your reverse string is: drahyduts
The following example uses some of the above-mentioned functions,

#include <stdio.h>
#include <string.h>

int main () {

char str1[12] = "Hello";


char str2[12] = "World";
char str3[12];
int len ;

/* copy str1 into str3 */


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */


strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */


len = strlen(str1);
printf("strlen(str1) : %d\n", len );

return 0;
}

When the above code is compiled and executed, it produces the following result

strcpy( str3, str1) : Hello


strcat( str1, str2): HelloWorld
strlen(str1) : 10

Array of string:

Till now we discussed on different aspects of string and dealing with a string, we also know
that an array represents a linear collection of data elements of a similar type, thus an array of
string means a collection of several strings.

The string is a one-dimensional array of characters terminated with the null character i.e.
strings are arrays of characters and the array of string will evolve into a two-dimensional
array of characters.

The general form to define an array of string is as follows:

char variableName[numberOfStrings][maxSizeOfString];

char name[10][50];
name is 1 dimension array of string with 10 elements each of width 50 characters.
Initialization of Array of String
Initialization in C means to provide the data to the variable at the time of declaration. It is
straightforward to initialize an array of strings. Create an array of string with some size and
then place comma-separated strings inside that. For example,

char color[5][20] = {"Orange", "White", "Green", "Blue"};

Explanation: In this example, we have initialized a array of string (two-dimensional character


array) car which can have a maximum of 5 strings of size 20.

Reading and Displaying Array of Strings

/* program to demonstrate working on array of string */

#include <stdio.h>
#include <string.h>

int main()
{
// declaration and initialization of variable color as an array of string
char color[4][10] = {"Red", "Orange", "Green", "Blue"};
int i,j;

for(i=0;i<4;i++) // loop to print each color value


{
printf("%d. %s", i+1,color[i]);
printf("\n");
}

printf("\n");

// loop to print numbers 0 to 9 to represent column index of color array variable


for(j=0;j<9;j++)
printf("\t%d",j);

printf("\n");

// nested loop to print numbers 1 to 5 to represent row index and respective element of color
//variable
for(i=0;i<4;i++)
{
printf("%d",i);
for(j=0;j<strlen(color[i]);j++)
printf("\t%c",color[i][j]);
printf("\n");
}
return 0;
}
Following is result displayed

1. Red

2. Orange

3. Green

4. Blue

0 1 2 3 4 5 6 7 8

0 R e d

1 O r a n g e

2 G r e e n

3 B l u e

/* program to demonstrate to read values for array of string and printf the same*/

#include <stdio.h>
#include <string.h>

int main()
{
char color[4][10]; // declaration of variable color as array of string
int i,j;

printf("Enter any 4 color\n");


for(i=0;i<4;i++)
{
printf("Enter %dth color\n",i+1);
scanf("%s",color[i]); // to read array of string color using scanf()
}

for(i=0;i<4;i++)
{
// to print array of string color using printf()
printf("%d. %s", i+1,color[i]);
printf("\n");
}

printf("\n");

for(j=0;j<9;j++)
printf("\t%d",j);
printf("\n");

for(i=0;i<4;i++)
{
printf("%d",i);
for(j=0;j<strlen(color[i]);j++)
printf("\t%c",color[i][j]);
printf("\n");
}
return 0;
}

Following is result displayed

Enter any 4 color


Enter 1th color
Green
Enter 2th color
Blue
Enter 3th color
White
Enter 4th color
Black
1. Green
2. Blue
3. White
4. Black

0 1 2 3 4 5 6 7 8
0 G r e e n
1 B l u e
2 W h i t e
3 B l a c k

/* program to demonstrate to read N values for array of string and print the same using gets()
and puts()*/

#include <stdio.h>
#include <string.h>

int main()
{
char color[20][10]; // declaration of variable color as array of string
int i,n;

printf("How many colors you want to enter\n");


scanf("%d",&n);

printf("Enter any %d colors\n",n);


for(i=0;i<n;i++)
{
printf("Enter %dth color\n",i+1);
gets(color[i]); // to read array of string color using gets()
}

for(i=0;i<n;i++)
{
printf("%d ",i+1);
puts(color[i]);
printf("\n");
}
return 0;
}

Reference Sites
https://www.tutorialspoint.com
https://www.studytonight.com
https://www.cprogramming.com
https://www.programiz.com

You might also like