Why are my if and else both executing?

I have a function with an if and else statement inside a for loop but both the if and else are both executing.
What am I doing working?

Thank You.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
int removeStudent( int Iarray[], double dArray[], string sArray[], int removeID, 
string &name, double &grade, int &size )
 {
  int index;
  char done;

  cout << endl;

  cout << "Enter remove student ID number : ";
  cin >> removeID;

  for( index = 0; index < size; index++ )
   {
       if( removeID == Iarray[index] )
         {
           cout << "Present Student Name : " << 
           sArray[index] << endl;
           cout << "Present Student Grade : " << 
           dArray[index] << endl;
           cout << endl << endl;
           cout << "Complete student editing process <y/n>: ";
           cin >> done;

           if( toUpperCaseLetter(done) == 'Y' )
             {
               Iarray[index] = '\0';
               sArray[index] = '\0';
               dArray[index] = '\0';
             }
           } 

       else
         {
           cout << endl;
           cout << "ERROR: Student ID not found, Remove Student Module aborted" << endl;
           cout << endl;

         } 

       }


    }
Last edited on
I don't think your else statement is part of an if statement.
How can you tell?
@buffbill How?
It looks like
1
2
3
4
5
6
7
8
9
if(...)
 {
   if(...)
   {
   }
  }
else
  {
  }
Last edited on
That indentation needs a bit of work. Have you tried stepping through with a debugger to see what's happening?
Debugger? I am pretty new to c++. This function is for a class assignment.
Let me ask again: What makes you think both branches are executing?
@ L B I guess if the remove id is in the array then it does something
else it shows error

I don't think it's that complicated.
Last edited on
closed account (D80DSL3A)
He's probably seeing the output from the 'if' branch in one iteration of the for loop followed by the output from the 'else' branch in the next iteration. This could make it appear that both branches are executing.

@JazzyJeff. If you don't want to use a debugger, just output the value of index in each branch. The values would be the same if both the 'if' and the 'else' really are (somehow) executing.
Last edited on
Seriously, this kind of indentation is terrible. I mean, I've seen people use 8 spaces indents, 4-space indents and even 2-space indents. But using 1-space dual-indent per nesting level... OMG.

It was simple. I set the function to a Boolean.
Topic archived. No new replies allowed.