Click here to Skip to main content
15,879,474 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi every one;
I am trying to add 1 + 1 when ever user inputs number 1 upto 30 times and finally it has to shot the total . but always i use to get the total as number 2 only i am expecting to get 30.
C++
// Student attendence

#include <iostream>
#include <string>
#include <conio.h>
#include <limits>

using namespace std;

int main ()
{

      cout<<"Enter Attendance for CP : ";

      int cptotal;

	   for(int i=0;i<31;i++){
		
           cin>>cptotal;	
		
           if(cptotal==1)
	     cptotal=cptotal+1;

	   }
		
	   cout<<cptotal;

	}

  return 0;

}
Posted

1 solution

When you execute cin>>cptotal and the user enters a valid number, the previous value of cptotal is lost. You can have too different variables for input and accumulation of incremented values.

(By the way, many C++ developers will go furious when they see cptotal=cptotal+1;, which looks way too foreign when ++cptotal or cptotal++ can be used.)

—SA
 
Share this answer
 
v2
Comments
CPallini 26-Sep-13 13:31pm    
5.
zakirox123 26-Sep-13 13:49pm    
this works perfect but another question when ever use input 0 its has to calculate as 0
int cp;
int cptotal=0;


for(int i=0;i<30;i++){

cin>>cp;

if(cp==1){
cptotal=cp+cptotal;

}

}
cout<<"Total : "<<cptotal<<endl;
Sergey Alexandrovich Kryukov 26-Sep-13 15:18pm    
Why "calculate as 0"? Why all that, anyway? As you need only the Yes/no question from the user (to increment or not to increment), as yes/no, and process invalid input as well.
Also, declare cp inside the loop, not outside: scope should be as tight as possible. And write "++cptotal" instead of assignment.
—SA
zakirox123 26-Sep-13 22:13pm    
thank you very much my problem has been solved :)
Sergey Alexandrovich Kryukov 26-Sep-13 23:08pm    
You are welcome.
Good luck, call again.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900