help understanding it

can someone please explain how we're getting the n=2, n=4, n=1, n=1, n=3, n=0?

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
#include <iostream>
#include <iomanip>
#include <time.h>
using namespace std;
void main()
{   
	 int n=0;
	  for(int i=11 ; i>5 ; i--)
		{   switch(i)	         {
		case 11: case 7:
			   n+=2;
			      break;
			 case 10:
			 case 8:
				 n*=n;
break;
			 default:
				 n-=3;
	            }
	         cout <<" for i= "  <<i <<"\tn="<<n<<endl;
	       }
	
	  

	system("pause");
}


the for loop is going down from 11 to 6

at i=11 n=0 switch condition +2 => n becomes n=2
at i=10 n=2 switch condition *n => n becomes n=4
at i=9 n=4 switch condition -3 => n becomes n=1
at i=8 n=1 switch condition *n => n becomes n=1
at i=7 n=1 switch condition +2 => n becomes n=3
at i=6 n=3 switch condition -3 => n becomes n=0


hope it helps
Last edited on
thank you, very clear now.
Topic archived. No new replies allowed.