Everything works in this code, except for case 4. The if
statement where it checks if name
and array
are empty works. However, if array
and char name
are not empty, the while
loop and the entire program just quit. Basically it doesn't print the summary. If I take away the "name" in my printf
statement it runs fine. Once I insert it back, it causes me the same problem.
Am I calling the string wrong?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define true 1
#define false 0
float calculate_percent( float score, float max_score );
float getAvg( float num1, float num2, float num3 );
char getGradeLetter( float score );
void print_line( char symbol, int count );
int main()
{
char name[20] = { 0 };
int scores[3] = { 0 };
float avg = 0;
int reply;
print_line( '*', 10 );
while ( true )
{
print_line( '*', 10 );
printf( "\nChose an option.\n" );
printf( "1.Enter user name.\n2.Enter exam scores.\n3.Display average exam scores.\n4.Display Summary.\n5.Quit\n" );
scanf( "%d", &reply );
switch ( reply )
{
case 1:
printf( "Enter name.\n" );
scanf( "%s", &name[20] );
break;
case 2:
for ( int i = 0; i < 3; i++ )
{
printf( "Enter a score.\n" );
scanf( "%d", &scores[i] );
}
break;
case 3:
if ( name[20] == 0 && scores[0] == 0 || scores[1] == 0 || scores[2] == 0 )
{
printf( "You havent entered the scores.\n" );
}
else
{
avg = getAvg( scores[0], scores[1], scores[2] );
printf( "Your average is %.2f\n", avg );
}
break;
case 4:
if ( name[20] == 0 && scores[0] == 0 || scores[1] == 0 || scores[2] == 0 )
{
printf( "Name and scores are empty.\n" );
}
else
{
printf( "Hello %s, your scores are %d %d %d.\n", name[20], scores[0], scores[1], scores[2] );
printf( "your average is %d with a letter of grade %c.\n", avg, getGradeLetter( avg ) );
}
break;
case 5:
exit( 0 );
}
}
getchar();
return 0;
}
float calculate_percent( float score, float max_score )
{
return score / max_score * 100;
}
float getAvg( float num1, float num2, float num3 )
{
return ( num1 + num2 + num3 ) / 3;
}
char getGradeLetter( float score )
{
char grade_letter;
if ( score >= 90 )
{
grade_letter = 'A';
}
else if ( score >= 80 )
{
grade_letter = 'B';
}
else if ( score >= 70 )
{
grade_letter = 'C';
}
else if ( score >= 60 )
{
grade_letter = 'D';
}
else if ( score > 0 && score < 59 )
{
printf( "you failed the test.\n\n" );
}
return grade_letter;
}
void print_line( char symbol, int count )
{
for ( int i = 0; i < count; i++ )
{
printf( "%c", symbol );
}
}