Array In C

Ad Code

Array In C

 




Array in c performs to store related data under a single variable name with an index, also known as a subscript. It is easiest to think that it is a list of ordered grouping for variables of the same type. Actually we can store more than one value in a single variable.
Declaration of Array:
We can declare an array by specifying its type and size or by initializing it or by both. type arrayName [ arraySize ];
int array[5] = {5, 9, 6, 3, 7};

Q: Put five array elements then print those elements.

#include<stdio.h>

int main()

{

int n[5],i;

   for(i=0;i<5;i++)

   {

         printf(“\nEnter Number”);

         scanf(“%d”,&n[i]);

   }

  for(i=0;i<5;i++)

   {

       printf("%d  “,n[i]);

  }

return 0;

}

Output:

Enter Number
5
Enter Number
7
Enter Number
8
Enter Number
4
Enter Number
3
5 7 8 4 3



Example 2: Enter Five numbers in array then according to user choice search number, if number is available then print found otherwise print not found

#include<stdio.h>

int main()

{

 int n[ 5 ]; /* n is an array of 10 integers */

   int i,ch,f=0;

 

   /* initialize elements of array n to 0 */         

   for ( i = 0; i < 5; i++ ) {

        printf("\nEner Number");

        scanf("%d",&n[ i ]); /* set element at location 0 */

   }

   printf("\nEnter Number to search");

  scanf("%d",&ch);

   /* output each array element's value */

   for (i=0; i<5;i++ ) {

      printf("Element[%d] = %d\n", i, n[i] );

      if(n[i]==ch){

         f=1;

}

      }

      if(f==1){

       printf("\nSearching Number %d found",ch);

      }

      else

      {

      printf("\nSearching Number %d Not found",ch);

   }

return 0;

}

Output:


Example 3: Enter Five numbers in array then according to user choice search number, if number is available then print found otherwise print not found using binary search method.

#include<stdio.h>
#include<conio.h>
int main()
{
 int c, first, last, middle, ch, search, n[50];
 
   printf("Enter number of elements\n");
   scanf("%d",&ch);
 
   printf("Enter %d integers\n", ch);
 
   for (c = 0; c < ch; c++)
      scanf("%d",&n[c]);
 
   printf("Enter value to find\n");
   scanf("%d", &search);
 
   first = 0;
   last = ch - 1;
   middle = (first+last)/2;
 
   while (first <= last) {
      if (n[middle] < search)
         first = middle + 1;    
      else if (n[middle] == search) {
         printf("%d found at location %d.\n", search, middle+1);
         break;
      }
      else
         last = middle - 1;
 
      middle = (first + last)/2;
   }
   if (first > last)
      printf("Not found! %d isn't present in the list.\n", search);
getch();
return 0;
}

Output:






Post a Comment

0 Comments

Ad Code