Computer Science, asked by Ob69619, 4 months ago

(b) What is an array in C? Explain how arrays can be used for storing and manipulating Multiple values.​

Answers

Answered by jaibadani28
0

Answer:ok

Explanation:Why we need Array in C Programming?

Consider a scenario where you need to find out the average of 100 integer numbers entered by user. In C, you have two ways to do this: 1) Define 100 variables with int data type and then perform 100 scanf() operations to store the entered values in the variables and then at last calculate the average of them. 2) Have a single integer array to store all the values, loop the array to store all the entered values in array and later calculate the average.

Which solution is better according to you? Obviously the second solution, it is convenient to store same data types in one single variable and later access them using array index (we will discuss that later in this tutorial).

How to declare Array in C

int num[35];  /* An integer array of 35 elements */

char ch[10];  /* An array of characters for 10 elements */

Similarly an array can be of any data type such as double, float, short etc.

How to access element of an array in C

You can use array subscript (or index) to access any element stored in array. Subscript starts with 0, which means arr[0] represents the first element in the array arr.

In general arr[n-1] can be used to access nth element of an array. where n is any integer number.

For example:

int mydata[20];

mydata[0] /* first element of array mydata*/

mydata[19] /* last (20th) element of array mydata*/

Example of Array In C programming to find out the average of 4 integers

#include <stdio.h>

int main()

{

   int avg = 0;

   int sum =0;

   int x=0;

   /* Array- declaration – length 4*/

   int num[4];

   /* We are using a for loop to traverse through the array

    * while storing the entered values in the array

    */

   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);

   return 0;

}

Similar questions