0% found this document useful (0 votes)
12 views

Array in C

Uploaded by

ridashaikh215
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Array in C

Uploaded by

ridashaikh215
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Chapter

Arrays and Strings

What is Array?
Arrays 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.

Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the
limit.

Declaring Array -
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows −

datatype arrayName [ arraySize ];

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 −

int salary = a[5];

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

Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize each
element of the array by using the index. Consider the following example.

marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

Two Dimensional Array in C


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. It provides ease of holding the
bulk of data at once which can be passed to any number of functions wherever required.
Declaration of two dimensional Array in C

The syntax to declare the 2D array is given below.


data_type array_name[rows][columns];

Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization are
being done simultaneously. However, this will not work with 2D arrays. We will have to define at least
the second dimension of the array. The two-dimensional array can be declared and defined in the
following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

C Strings (Character Array)

The string can be defined as the one-dimensional array of characters terminated by a null
('\0'). The character array or the string is used to manipulate text such as word or sentences.
Each character in the array occupies one byte of memory, and the last character must always
be 0. The termination character ('\0') is important in a string since it is the only way to identify
where the string ends. When we define a string as char s[10], the character s[10] is implicitly
initialized with the null in the memory.

There are two ways to declare a string in c language.

 By char array
 By string literal

Let's see the example of declaring string by char array in C language.

char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

Accepting string as the input

We have used scanf to accept the input from the user. However, it can also be used in the case of
strings but with a different scenario. Consider the below code which stores the string while space is
encountered.
#include<stdio.h>
void main ()
{
char s[20];
printf("Enter the string?");
scanf("%s",s);
printf("You entered %s",s);
}

C String Functions

There are many important string functions defined in "string.h" library.

No. Function Description

1) strlen(string_name) returns the length of string name.

2) strcpy(destination, source) copies the contents of source string to destination


string.

3) strcat(first_string, concats or joins first string with second string. The


second_string) result of the string is stored in first string.

4) strcmp(first_string, compares the first string with second string. If


second_string) both strings are same, it returns 0.

5) strrev(string) returns reverse string.

6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.

C String Length: strlen() function

The strlen() function returns the length of the given string. It doesn't count null character '\0'.
#include<stdio.h>
#include <string.h>
main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
printf("Length of string is: %d",strlen(ch));
}

C Copy String: strcpy()

The strcpy(destination, source) function copies the source string in destination.


#include<stdio.h>
#include <string.h>
main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
}

C String Concatenation: strcat()


The strcat(first_string, second_string) function concatenates two strings and result is returned to
first_string.
#include<stdio.h>
#include <string.h>
main(){
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);

C Compare String: strcmp()

The strcmp(first_string, second_string) function compares two string and returns 0 if both strings are
equal.
Here, we are using gets() function which reads string from the console.
#include<stdio.h>
#include <string.h>
main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
}

C Reverse String: strrev()


The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev()
function.
#include<stdio.h>
#include <string.h>
main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
}

C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h
header file are given below.

No. Function Description

1) ceil(number) rounds up the given number. It returns the integer


value which is greater than or equal to given
number.

2) floor(number) rounds down the given number. It returns the


integer value which is less than or equal to given
number.

3) sqrt(number) returns the square root of given number.

4) pow(base, returns the power of given number.


exponent)

5) abs(number) returns the absolute value of given number.

Let's see a simple example of math functions found in math.h header file.

#include<stdio.h>
#include <math.h>
main(){
printf("\n%f",ceil(3.6));
printf("\n%f",ceil(3.3));
printf("\n%f",floor(3.6));
printf("\n%f",floor(3.2));
printf("\n%f",sqrt(16));
printf("\n%f",sqrt(7));
printf("\n%f",pow(2,4));
printf("\n%f",pow(3,3));
printf("\n%d",abs(-12));

}
Sample Example of Array

#include <stdio.h>
main()
{
int avg = 0;
int sum =0;
int x=0;

/* Array- declaration – length 4*/


int num[4];

for (x=0; x<4;x++)


{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}

avg = sum/4;
printf("Average of entered number is: %d", avg);
}

You might also like