Reputation: 27
I'm new to C programming, I'm confused why my code not working. So I have case where every time the value is true on IF statement, it will add 1 value to variable and either if false too, it will add value.
int i,n,nilai,kelulusan,lulus,tidaklulus;
printf("Berapa banyak nilai yang ingin dimasukkan?: ");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
printf("Masukkan nilai: ");
scanf("%d",&nilai);
if(nilai>=60)
{
printf("Nilai ini lulus\n");
lulus++;
printf("\n");
}
else
{
printf("Nilai ini tidak lulus\n");
tidaklulus++;
printf("\n");
}
}
printf("Dari %d nilai, ada %d yang lulus, dan %d yang tidak lulus.",n,kelulusan,tidaklulus);
The input is going to be like this for example:
Berapa banyak nilai yang ingin dimasukkan?: 3
Masukkan nilai: 2
Nilai ini tidak lulus
Masukkan nilai: 2
Nilai ini tidak lulus
Masukkan nilai: 60
Nilai ini lulus
Dari 3 nilai, ada 10425344 yang lulus, dan 2 yang tidak lulus.
I get wrong output
Dari 3 nilai, ada **10425344** yang lulus, dan 2 yang tidak lulus.
The right output should be like this
Dari 3 nilai, ada 1 yang lulus, dan 2 yang tidak lulus.
How do I solve this?
Upvotes: 0
Views: 1249
Reputation: 347
I corrected that code. Works as Lord desired. Has all mistakes marked with comments. Anyway I recommend using -Wall flag for your compiler. It will turn on all warnings.
#include <stdio.h>
int main()
{
int i; //"Initialized" by for(...) loop
int n,nilai; //"Initialized" by scanf
int lulus=0,tidaklulus=0; //Definitly need initialization
//You define `kelulusan` and than print it with out using it storage potential?
/*Use
#define kelulusan ⟦any value⟧
if you need a compile-time constant*/
printf("Berapa banyak nilai yang ingin dimasukkan?: ");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
printf("Masukkan nilai: ");
scanf("%d",&nilai);
if(nilai>=60)
{
printf("Nilai ini lulus\n");
lulus++;
printf("\n");
}
else
{
printf("Nilai ini tidak lulus\n");
tidaklulus++;
printf("\n");
}
}
//Asumed that `kelulusan` was in place of `lulus` and corrected that.
printf("Dari %d nilai, ada %d yang lulus,"
"dan %d yang tidak lulus.",n, lulus,tidaklulus
);
}
Upvotes: 1