Array in C Language

Arrays are structures that hold multiple variables of the same data type. The first element in the array is numbered 0, so the last element is 1 less than the size of the array. An array is also known as a subscripted variable. Before using an array its type and dimension must be declared.

Array Declaration :

Like other variables an array needs to be declared so that the compiler will know what kind of an array and how large an array we want.

int marks[30] ;

Here, int specifies the type of the variable, just as it does with ordinary variables and the word marks specifies the name of the variable. The [30] however is new. The number 30 tells how many elements of the type int will be in our array. This number is often called the “dimension” of the array. The bracket ( [ ] ) tells the compiler that we are dealing with an array.

Let us now see how to initialize an array while declaring it. Following are a few examples that demonstrate this.

int num[6] = { 2, 4, 12, 5, 45, 5 } ;
int n[] = { 2, 4, 12, 5, 45, 5 } ;
float press[] = { 12.3, 34.2 -23.4, -11.3 } ;

Accessing Elements of an Array :

Once an array is declared, let us see how individual elements in the array can be referred. This is done with subscript, the number in the brackets following the array name. This number specifies the element’s position in the array. All the array elements are numbered, starting with 0. Thus, marks [2] is not the second element of the array, but the third.

int valueOfSecondElement = marks[1];

Entering Data into an Array :

The for loop causes the process of asking for and receiving a student’s marks from the user to be repeated 30 times. The first time through the loop, i has a value 0, so the scanf() function will cause the value typed to be stored in the array element marks[0], the first element of the array. This process will be repeated until i becomes 29. This is last time through the loop, which is a good thing, because there is no array element like marks[30].

In scanf() function, we have used the “address of” operator (&) on the element marks[i] of the array. In so doing, we are passing the address of this particular array element to the scanf() function, rather than its value; which is what scanf() requires.

for(i = 0;i <= 29;i++)
{
printf(“\nEnter marks “);
scanf(“%d”, &marks[i]);
}

Reading Data from an Array :

The balance of the program reads the data back out of the array and uses it to calculate the average. The for loop is much the same, but now the body of the loop causes each student’s marks to be added to a running total stored in a variable called sum. When all the marks have been added up, the result is divided by 30, the number of students, to get the average.

for ( i = 0 ; i <= 29 ; i++ )
sum = sum + marks[i] ;
avg = sum / 30 ;
printf ( “\nAverage marks = %d”, avg ) ;

Advantages of using an Array :

1. Similar data types can be grouped together under one name.
2. for ex.- int a=1;int b=2;int c=3;int d=4;int e=5; could be represented as- int X[5]={1,2,3,4,5};
3. It allows random accessing of elements using indices which saves a huge time.
4. It can be used to implement other data structures like- stack,queues etc.
5. We can represent 2-D matrices using array.

Multidimensional arrays :

The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size [x][y], you would write something as follows −

type arrayName [x][y];
Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns.

int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to the previous example −

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Lets Do Some exercises on Arrays dont copy code from google :

1. Write a program in C to read n number of values in an array and display it in reverse order.
Input Data :

Input the number of elements to store in the array :3
Input 3 number of elements in the array : (taking input from user )

element – 0 : 2
element – 1 : 5
element – 2 : 7

Expected Output :

The values store into the array are :
2 5 7
The values store into the array in reverse are :
7 5 2


2. Write a program in C to sort elements of array in ascending order.

Ex .
Input Data :
Input the size of array : 5
Input 5 elements in the array :

element – 0 : 2
element – 1 : 7
element – 2 : 4
element – 3 : 5
element – 4 : 9

Expected Output :

Elements of array in sorted ascending order:
2 4 5 7 9

3. Write a program in C to find the sum of all elements of the array .

 

 

C – Strings and String functions

String is an array of characters. In this guide, we learn how to declare strings, how to work with strings in C programming and how to use the pre-defined string handling functions.

We will see how to compare two strings, concatenate strings, copy one string to another & perform various string manipulation operations. We can perform such operations using the pre-defined functions of “string.h” header file. In order to use these string functions you must include string.h file in your C program.

Defining strings:

Strings in C are actually arrays of characters. Although using pointers in C is an advanced subject, fully explained later on, we will use pointers to a character array to define simple strings, in the following manner:

char * name = “John Smith”;
This method creates a string which we can only use for reading. If we wish to define a string which can be manipulated, we will need to define it as a local character array:

char name[] = “John Smith”;
This notation is different because it allocates an array variable so we can manipulate it. The empty brackets notation [] tells the compiler to calculate the size of the array automatically. This is in fact the same as allocating it explicitly, adding one to the length of the string:

char name[] = “John Smith”;
/* is the same as */
char name[11] = “John Smith”;


The reason that we need to add one, although the string John Smith is exactly 10 characters long, is for the string termination: a special character (equal to 0) which indicates the end of the string. The end of the string is marked because the program does not know the length of the string – only the compiler knows it according to the code.

String Length :

The function strncmp compares between two strings, returning the number 0 if they are equal, or a different number if they are different. The arguments are the two strings to be compared, and the maximum comparison length. There is also an unsafe version of this function called strcmp, but it is not recommended to use it.


                        char * name = "John";

                        if (strncmp(name, "John", 4) == 0) {
                            printf("Hello, John!\n");
                        } else {
                            printf("You are not John. Go away.\n");
                        }
                        

 

String comparison :

The for loop causes the process of asking for and receiving a student’s marks from the user to be repeated 30 times. The first time through the loop, i has a value 0, so the scanf() function will cause the value typed to be stored in the array element marks[0], the first element of the array. This process will be repeated until i becomes 29. This is last time through the loop, which is a good thing, because there is no array element like marks[30].

In scanf() function, we have used the “address of” operator (&) on the element marks[i] of the array. In so doing, we are passing the address of this particular array element to the scanf() function, rather than its value; which is what scanf() requires.


                        for(i = 0;i <= 29;i++) 
                        { 
                            printf("\nEnter marks "); 
                            scanf("%d", &marks[i]); 
                        }
                        

 

String Concatenation :

The function ‘strncat’ appends first n characters of src string string to the destination string where n is min(n,length(src)); The arguments passed are destination string, source string, and n – maximum number of characters to be appended. For Example:


                    char dest[20]="Hello";
                    char src[20]="World";
                    strncat(dest,src,3);
                    printf("%s\n",dest);
                    strncat(dest,src,20);
                    printf("%s\n",dest);
                    

Lets Do Some exercises on Strings dont copy code from google :

1. C Program to Find the Frequency of Characters in a String .

Input : Enter a string: This website is awesome.
Enter a character to find the frequency: e

Output :
Frequency of e = 4


2. C Program to Sort Elements in Lexicographical Order (Dictionary Order)

Enter 5 words:
C
Java
Python
JavaScript
PHP

Output In lexicographical order:

C
Java
JavaScript
PHP
Python

3. Write a program in C to separate the individual characters from a string.

Input : ccatcracker

Output :
c c a t c r a c k e r


4. Write a program in C to count total number of vowel or consonant in a string.

Input : Welcome to ccatcracker

Output :

The total number of vowel in the string is : 7
The total number of consonant in the string is : 13