Reputation: 145
I want to write a program that gets input in separate lines (2 integers on each line) and calculates the sum of those 2 integers on each line This is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *numbers;
int i, j;
numbers = malloc(100 * sizeof(int));
for (i = 1; i <= 100; i++)
{
for (j = 1; j <= 2; j++)
{
scanf("%d", &numbers[j]);
}
printf("%d\n", numbers[1]+numbers[2]);
}
return 0;
}
My problem is that this program gives sum right after writing 2 numbers and doesn't stop until 100 lines is reached. But I want it like this:
example input:
10 5
6 8
67 2
example output:
15
14
69
100 is just max lines an user can input. How do I do that?
Upvotes: 0
Views: 106
Reputation: 331
There are two options to solve this 1) You need to have the 'n' number of inputs user is going to give 2) You should read it from the file to detect the end of line. Below code is for first option.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *numbers;
int i, j,n;
scanf("%d", &n);
numbers = malloc(n * sizeof(int));
for (i = 0; i < n; i++)
{ int s1,s2;
scanf("%d", &s1);
scanf("%d", &s2);
numbers[i]= s1+s2;
}
for (i = 0; i < n; i++)
{
printf("%d",numbers[i]);
}
return 0;
}
Upvotes: 1