row vector

Hello. I am using C and I want to create a row vector and display it. I mean the user will enter each number for the row vector and the program will show it. I am new to C and I am not sure how to do it. Here is my code:
I am getting some other numbers that I don't enter. Also, can anyone please explain what are these numbers and why they appear? Thank you

# include <stdio.h>

main()
{
int a [5];
printf("Please enter the row vector\n");
scanf("%d%d%d%d%d", &a,&a,&a,&a,&a);

printf("Your vector is %d\n", a);

return 0;
}
When you're printing 'a' your printing the address of the array.
You want to do this -

1
2
3
4
5
6
7
8
9
10
11
12
13
int a[5];
	printf("Please enter the row vector\n");

	for (int i = 0; i < 5; i++)
	{
		scanf("%d", &a[i]); // use a for-loop to input 5 numbers
		
	}

	for (int i = 0; i < 5; i++)
	{
		printf("Your vector is %d\n", a[i]); // use a for-loop to output the row
	}
Last edited on
Thank you. I got this error: Segmentation fault core dumped.
Why do you use for loop for the output? Doesn't it give me the output 5 times?
Segmentation fault means that you are trying to access a memory (element in the array) that you dont have access to. For example.

if you have an array of 5 integers.

int a[5]; The 5 integers will be placed between 0-4. Not 1-5. Which means, if you want to print out the first integer in that array, you would do

printf("%d", a[0]);

That is why we need to use a for-loop. Just like we need a for-loop to input 5, we need it to run 5 times, so it can output all 5 elements.
I typed the code below. I am getting segmentation fault as soon as I insert the first input and press enter. The first input means that it goes to a[0], right? Why am I getting this if this array already defined in the for loop? I am using c, not c++ if it makes any difference.

main ()
{
int a[5];
int i;

printf("Please enter the row vector\n");

for (i = 0; i < 5; i++)
{
scanf("%d", &a[i]);

}

for (i = 0; i < 5; i++)
{
printf("Your vector is %d\n", a[i]);
}
return 0;

}


Last edited on
Works fine for me. And the code looks good. So you shouldnt be getting any segmentation fault.
And yes, the first input goes to a[0].
I think the problem was lack of & sign before a[i] in the last printf.
I think the problem was lack of & sign before a[i] in the last printf.

No. The printf statement is correct. The format descriptor is %d, so printf is expecting an int argument.

@op - main must have type int.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Last edited on
Topic archived. No new replies allowed.