It would help if you said what problem you are getting.
The first change I would make is:
Enclose your loop content in a block. It is always worth doing.
for( int i = 0 ; i< m ; i++ )
if(n>=17 && n<=20)
{
cout << 'A' << endl ;
}
if(n>=13 && n<=16)
{
cout << 'B' << endl;
}
Does this execute one "if" in a loop, or two?
for( int i = 0 ; i< m ; i++ )
{
if(n>=17 && n<=20)
{
cout << 'A' << endl ;
}
if(n>=13 && n<=16)
{
cout << 'B' << endl;
}
}
Is a lot clearer: it executes both "if" inside the loop.
Try it: it may get rid of your problem. If it doesn't, try telling us what your problem is!
"for example in my program if i write 20 , 16 the program give me (B & B)but it is not correct it must be (A & B)"
Ok. It is what I was describing above, but slightly more serious.
Your code:
cout << "plz enter the grades :" << endl ;
for( int i = 0 ; i< m ; i++ )
cin >> n;
for( int i = 0 ; i< m ; i++ )
if(n>=17 && n<=20)
Means that the line
cin >> n;
is exectuted "m" times. Then it moves on to the next
for
loop.
A
for
loop, or an
if
condition, only executes the statement immediately after it.
for (int i = 0; i < 10; i++)
printf("This line prints 10 times\n");
printf("This line prints once\n");
or
if (myInteger == 0)
printf("This prints only when myInteger is zero\n");
printf("This prints every time\n");
If you want to execute more than one statement, you need to make it a statement block by enclosing it in curly braces:
for (int i = 0; i < 10; i++)
{
printf("This line prints 10 times\n");
printf("So does this one\n");
}
printf("This line prints once\n");
or
if (myInteger == 0)
{
printf("This prints only when myInteger is zero\n");
printf("So is this one\n");
}
printf("This prints every time\n");
Change your code: put curly braces in EVERYWHERE you want to execute - even if it is a single line in a
if
condition. You will understand later when you can leave them out - but for now, always put them in.
cout << "plz enter the grades :" << endl ;
for( int i = 0 ; i< m ; i++ )
{
cin >> n;
for( int i = 0 ; i< m ; i++ )
{
if(n>=17 && n<=20)
{
cout << 'A' << endl ;
}
if(n>=13 && n<=16)
{
cout << 'B' << endl;
}
if(n>=10 && n<=12)
{
cout << 'C' <<endl;
}
if(n>=6 && n<=9)
{
cout << 'D' <<endl;
}
if(n>=0 && n<=5)
{
cout << 'E'<<endl;
}
}
}
return 0;
See the difference?