-3

The output I expect after reading 3 times is the sum of those three numbers, but when reading the numbers there is a problem with the printing.

    for (i = 0; i < TAMANIO; i++) {
            scanf("%d\n",&ar[i]);
            printf("numero: %d\n",ar[i]); //print numbers
    }

If you need full code.

#include <stdio.h>
#define TAMANIO 3

//prototipo de funciones
void pri();
int pro(int a, int b, int c);

int main () {
    pri(); //Ask for numbers
    int i; //counter
    int ar[TAMANIO];

    for (i = 0; i < TAMANIO; i++) {
            scanf("%d\n",&ar[i]);
            printf("numero: %d\n",ar[i]); //print numbers
    }
    printf("suma de numeros: %d\n", pro(ar[0],ar[1],ar[2])); //send number to function and print
return 0;
}

void pri(){
    //write numbers
    printf("Escriba los 3 numeros a ser operados : \n"); 
}

int pro(int a, int b, int c) {
int sum;
sum = a + b + c;
return sum;
}

I expect when reading:

"enter numbers"
1
number : 1
2
number : 2
3
number : 3
sum : 6

[ More Scanf() info ] What is the effect of trailing white space in a scanf() format string?

Nahu
  • 59
  • 9
  • 1
    The 4 numbers problem is because of `scanf("%d\n",&ar[i]);` — see [Trailing white space in `scanf()` format string](http://stackoverflow.com/questions/19499060/what-is-difference-between-scanfd-and-scanfd). I'm tempted to make this a duplicate of that. – Jonathan Leffler Jul 29 '19 at 06:31
  • Note that you should have shown what you actually saw — as well as what you expected to see. – Jonathan Leffler Jul 29 '19 at 06:36

2 Answers2

1

You could try changing scanf("%d\n",&ar[i]); to scanf("%d",&ar[i]);, because it will try to read newline break too in a loop.

Simply remove \n from the scan

buriedalive
  • 380
  • 5
  • 12
0

You need to remove the \n from scanf.

for (i = 0; i < TAMANIO; i++) {
            scanf("%d",&ar[i]);
            printf("numero: %d\n",ar[i]); //print numbers(here is the problem)
}
Damien Baldy
  • 456
  • 2
  • 7