Header Ads

07 - WAP to Print the Average of a given Numbers of a Array.

This Program prints the Average of a given Array Elements.

/*Finding the average of the numbers*/

/*library protype declaration*/
#include 
#include 
#include 
#define max 100

/*Begin of main program*/
int main(int argc , char * argv[], char * envp[])
{
 /*Variable Declaration*/
 int num[max], size, idx, jdx, flag1 = 0, flag = 0, len;
 float avg, sum = 0, count = 0;

 /*checking for normal average(i) and finding it's average*/
 if (argc == 1)
 {
  printf("Enter Total Number of Elements in an Array : ");
  scanf("%d", &size);
  printf("Start Entering the '%d' Elements of Array : ", size);
  for (idx = 0; idx < size; idx++)
  {
   scanf("%d", &num[idx]);
   sum = sum + num[idx];
  }
  avg = sum / size;
  printf("The Average of all Elements is : %.3f", avg);
 }

 /*checking for the condition if argument count  is greater then 1*/
 else 
 {
  /*calculating the lenght of argv[1] so that we can jump to calculate main arguments average after which average will be calculated
    and finally*/
  len = strlen(argv[1]);
  for (idx = 0; envp[idx] != '\0'; idx++)
  {
   if (strncmp(argv[1], envp[idx], len) == 0)
   {
    for (jdx = 1; *(envp[idx] + len + jdx) != '\0'; jdx++)
    {
     if (flag1 == 0)
     {
      sum += atoi(envp[idx] + len +jdx);
      count++;
      flag1 = 1;
     }
     else if (*(envp[idx] + len +jdx) == ' ')
      flag1 = 0;
    }
    flag = 1;
    avg = sum / count;
    break;
   }
  }

  /*argc avergage calculation*/
  if (flag == 0)
  {
   for (idx = 1; idx < argc; idx++)
    sum = sum + atoi(argv[idx]);

   avg = sum / (argc - 1);
  }
  printf("the average of all elements is : %.2f \n", avg);
 }
 printf ("\n");
 return 0;
}

Program Output: 

No comments