Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions and arrays

Tags:

c

My little program below shall take 5 numbers from the user, store them into an array of integers and use a function to print them out. Sincerly it doesn't work and nothing is printed out. I can't find a mistake, so i would be glad about any advice. Thanks.

#include <stdio.h>


void printarray(int intarray[], int n)

{
    int i;

    for(i = 0; i < n; i ++)
    {
        printf("%d", intarray[i]);
    }
}

int main ()

{
    const int n = 5;
    int temp = 0;
    int i;
    int intarray [n];
    char check;

    printf("Please type in your numbers!\n");

    for(i = 0; i < n; i ++)
    {
        printf("");
            scanf("%d", &temp);         
        intarray[i] = temp;

    }

    printf("Do you want to print them out? (yes/no): ");
        scanf("%c", &check);

        if (check == 'y')
            printarray(intarray, n);

    getchar();
    getchar();
    getchar();
    getchar();
    return 0;
}
like image 650
Ordo Avatar asked Dec 12 '22 16:12

Ordo


1 Answers

Change your output in printarray() to read:

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

              ^^

That will add a newline after each number.

Normally, output written to the console in C is buffered until a complete line is output. Your printarray() function does not write any newlines, so the output is buffered until you do print one. However, you wait for input from the user before printing a newline.

like image 51
Greg Hewgill Avatar answered Jan 04 '23 06:01

Greg Hewgill