weird problem with switch, for, while and do while

First, Spanish student, so sorry for my bad english

i made a program to create an recipt but i have a problem, the text "la suma de los pares hasta" repeats many times, i don´t know why

I hope someone can help me, thanks

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
  #include <iostream>

using namespace std;

int main(){
 char s;
 int b, n, i, a;
 do
 { 
 cout<< "Menu" <<endl;
 cout<< "1- Ciclo For" <<endl;
 cout<< "2- Ciclo While" <<endl;
 cout<< "3- Ciclo Do While" <<endl;
 cout<< "4- Salir del programa" <<endl;
 cin>>b; 
 if(b!=4)
 {
 cout<<"Introduzca hasta que numero desea la suma de los numeros pares"<<endl;
 cin>>n;
 switch(b){
 	
	 case 1:         
	a=0;
 	for(i=2 ; i<=n ; i=i+2)
 	 {
	 	cout<<i+" ";
	 	a= a+i;
	 }
	 break;
 	
	 case 2:          
	 i = 2;
	 a = 0;
	 while(i<=n)
	 {
	 	cout<<i+" ";
	 	a=a+i;
	 	i=i+2;
	 }
	 break;
	case 3:           
	i=2;
	a=0;
	do
	{
		cout<<i+" ";
		a=a+i;
		i=i+2;
	}
	while(i<=n);
	break;
	
	case '4':s='s';           
	break;
	
 }//switch
 cout<<"\n\nla suma de los pares hasta "<<n<<" es igual a "<<a<<endl;

}//if
 cout<<"\n¿Desea volver ejecutar el programa s=si\n n=no?"<<endl;
 cin>>s;
}//do
 while(s=='s'|| s=='S');
return 0;
}
Change cout<<i+" "; to cout<<i<<" ";
read about pointer arithmetic.
Last edited on
Consider checking for bad input, especially at line 19. If the input fails, let's say someone enters a letter instead of a number, all further input will fail and you may find yourself with the problem you described.
Try:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
if(b!=4)
{
	cout<<"Introduzca hasta que numero desea la suma de los numeros pares"<<endl;
	cin>>n;
	if (!cin.good())
	{
		n = 0;
		cin.clear();
	}
	else
	{	
		switch(b){
		
		case 1:         
		...
		...
		}
	}
	
	...
}
Thank you ne555 and tipaye!
Topic archived. No new replies allowed.