Here's the code
Write a code to find grade of a student based on the marks obtained by him and as the system given below,
1. 90-100-->A
2. 80-90-->B
3. 70-80-->C
4. 60-70-->D
5. <60-->E
#include <stdio.h>
int main(){
int marks;
printf("Enter your marks(1-100)\n");
scanf("%d\n", &marks);
switch (marks)
{
case 1:
printf("Your Grade is A\n");
break;
case 2:
printf("Your Grade is B\n");
break;
case 3:
printf("Your Grade is C\n");
break;
case 4:
printf("Your Grade is D\n");
break;
case 5:
printf("Your Grade is E\n");
break;
}
return 0;
}
CodePudding user response:
Let's ignore error handling and range trapping for this answer!
Given the mapping, you could just do an integer division
int grade = marks / 10;
Then switch
on grade
and case
accordingly (9,8,7,6, default)
case 10:
case 9: { printf( "Your Grade is A\n" ); break; }
case 8: { printf( "Your Grade is B\n" ); break; }
case 7: { printf( "Your Grade is C\n" ); break; }
case 6: { printf( "Your Grade is D\n" ); break; }
default: { printf( "Your Grade is E\n" ); break; }
Note: There are compilers that support a language extension allowing ranges (eg) case 90 ... 100:
but these are non-standard so should not be encouraged .
For ranges, in C, you will normally need to do an if-elseif-else
ladder.
if ( marks > 100 ) { printf( "You cheated\n" ); }
else if ( marks > 90 ) { printf( "Your Grade is A\n" ); }
else if ( marks > 80 ) { printf( "Your Grade is B\n" ); }
else if ( marks > 70 ) { printf( "Your Grade is C\n" ); }
else if ( marks > 60 ) { printf( "Your Grade is D\n" ); }
else /* marks < 60 */ { printf( "Your Grade is E\n" ); }
CodePudding user response:
You need to transform marks
in a number in the range [1, 5]
. This can be done for example using an array.
Here is a demonstration program.
#include <stdio.h>
int main(void)
{
unsigned int marks = 0;
printf( "Enter your marks(1-100): " );
scanf( "%u", &marks );
unsigned int grades[] = { 0, 60, 70, 80, 90 };
const size_t N = sizeof( grades ) / sizeof( *grades );
size_t i = 0;
while ( i != N && marks < grades[N - i] );
switch ( i )
{
case 1:
puts( "Your Grade is A" );
break;
case 2:
puts( "Your Grade is B" );
break;
case 3:
puts( "Your Grade is C" );
break;
case 4:
puts( "Your Grade is D" );
break;
case 5:
puts( "Your Grade is E" );
break;
}
return 0;
}
CodePudding user response:
#include <stdio.h>
int main(){
int marks;
printf("Enter your marks between 0 to 100\n");
scanf("%d", &marks);
switch(marks/10){
case 10 :
case 9 :
/* Marks between 90-100 */
printf("Your Grade : A\n" );
break;
case 8 :
case 7 :
/* Marks between 70-89 */
printf("Your Grade : B\n" );
break;
case 6 :
/* Marks between 60-69 */
printf("Your Grade : C\n" );
break;
case 5 :
case 4 :
/* Marks between 40-59 */
printf("Your Grade : D\n" );
break;
default :
/* Marks less than 40 */
printf("You failed\n" );
}
return 0;
}```
to find use switch(marks/10) in the switch statement
if your score is 80 then 80/10 so it will jump to case 8.