Fill vector in C
I have an exercise that asks the teacher to type 5 notes, and display the typed notes, I wrote the code, but it is not running in the correct way, can anyone help?
Follows Code
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int main()
{
setlocale(LC_ALL, "Portuguese");
int i = 0;
float nota[5];
float total = 0, media = 0;
for(i = 0; i < 5; i++)
{
printf("Digite a nota do usuário!\\n");
scanf("%f", &[i]);
}
printf("As notas digitadas foram %.2f\\n", nota[i]);
return 0;
}
4 answers
Missing a loop to print. Note that after the reading loop the variable i will contain the value 5, which is outside the vector limits.
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int main() {
setlocale(LC_ALL, "Portuguese");
int i = 0;
float nota[5];
float total = 0, media = 0;
for(i = 0; i < 5; i++) {
printf("Digite a nota do usuário!\\n");
scanf("%f", ¬a[i]);
}
for(i = 0; i < 5; i++)
printf("As notas digitadas foram %.2f\\n", nota[i]);
return 0;
}
In this line where you take the value typed from the keyboard by the user is missing the name of your array of Notes
scanf("%f", &[i]);
Correct:
scanf("%f", ¬a[i]);
And on the line you print the Notes
printf("As notas digitadas foram %.2f\\n", nota[i]);
Is speaking a For
for you to scroll through the array indices again to print the same.
Follows the code: code
I made only two changes to your code:
I changed the line that was written scanf("%f", &[i]);
to scanf("%f", ¬a[i]);
and
I implemented a loop for
surrounding the line printf("As notas digitadas foram %.2f\n", nota[i]);
.
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int main()
{
setlocale(LC_ALL, "Portuguese");
int i = 0;
float nota[5];
float total = 0, media = 0;
for(i = 0; i < 5; i++)
{
printf("Digite a nota do usuário!\n");
//Primeira alteração de &[i] para ¬a[i]
scanf("%f", ¬a[i]);
}
//Segunda alteração um laço for para imprimir as notas coletadas
for(i = 0; i < 5; i++)
{
printf("As notas digitadas foram %.2f\n", nota[i]);
}
return 0;
}
Code rolling No Repl.it
Friend the mistake made was something very simple, your " scanf ("%f", & [i]);" is wrong variable declaration, the correct would be "scanf("%F", ¬e[I]);" because of this you are signaling the vector correctly. I noticed tbm an error when showing the notes that it is, you did not make it rotate the vector correctly to show each note written, in case it would replace your "printf("the notes typed were %.2f\n", note[i]); " by a for and the printf in.
This way in the case:
For (i = 0; i