Home > OS >  I'm trying to write a program to accept and display an array using diffrent functions, but I�
I'm trying to write a program to accept and display an array using diffrent functions, but I�

Time:05-30

The code i have written down:

#include<stdio.h>
#include<stdlib.h>


void get()
{
    int i,a[50],limit;
    printf("enter the limit:");
    scanf("%d",&limit); 
    
    printf("enter the array");
    for(i=0;i<limit;i  )
    {
        scanf("%d",&a[i]);
    }
    
}

void display()
{
    int i,a[50],limit;
    printf("the array is");
    for(i=0;i<limit;i  )
    {
        printf("%d\t",a[i]);
    }

}

int main(void)
{
   int i,a[50],limit;
   get(); 
   display(); 
   
}

Output:

enter the limit:5
enter the array1
2
3
4
5
the array is1   2       3       4       5       7143534 7209061   7536756 6488156 7077985 2949228 7471201 3019901633014777  7864421 101     0       0       -707682512      32767     -317320272      573     -690587167      32767   -317320288        573     -317325312      573     47      064       0       0       0       4       0       0       0-317325312       573     -690580068      32767   -31732531573      2       0       47      0       64      51      -1799357088       125     961877721       32758   3       32758     961957944       32758   -317168624      573     -706746576        32767

CodePudding user response:

When you declare int i,a[50],limit; in each of your functions, these variables are local to the functions.

For example the limit variable declared in get is totally unrelated to the limit variable declared in set etc. They just happen to have the same name.

You ether need to declare these variables as global variables (poor design), or redesign your code differently, for example by passing those variables as parameters.

All this is explained in the first chapters of your beginner's C text book.

Example using global variables (poor design)

#include <stdio.h>
#include <stdlib.h>

int i, a[50], limit;   // global variables visible
                       // from all functions

void get()
{
  printf("enter the limit:");
  scanf("%d", &limit);

  printf("enter the array");
  for (i = 0; i < limit; i  )
  {
    scanf("%d", &a[i]);
  }
}

void display()
{
  printf("the array is");
  for (i = 0; i < limit; i  )
  {
    printf("%d\t", a[i]);
  }
}

int main(void)
{
  get();
  display();
}
  • Related