Click here to Skip to main content
15,907,001 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm using "Dev c++"
Here's my code

C++
#include <iostream>
using namespace std;

main()
{
	int c[100];
	int z;
	int i;
	do{
		int z, i=0;
		cout<<"Please enter number(-1 to end)"<<endl;
		cin>>z;
		if(z!=-1)
		{
			c[i]=z;
		}
		i++;
	}	while(z!=-1 && i<100);
	cout<<"the total number of positive integers entered"<<i-1;
}

the problem is its not terminating...
Posted
Updated 16-Jun-15 22:26pm
v4
Comments
U. G. Leander 17-Jun-15 4:34am    
Just take a look where you instantiated 'i'....it is inside the do while loop and therefore the condition 'i<100' will always evaluate to 'true'.
Does termination work when entering '-1'?
Frankie-C 17-Jun-15 5:04am    
As they told you the problem is the scoping of your variable.
If you want understand something more about scoping see my answer:
http://www.codeproject.com/Answers/1000626/doubt-in-usage-of-extern-keyword-in-c-any-one-help#answer2

The problem is one of scope. You got variables named i and z appearing 2 times in the main. Once at the top of the function and again inside the do/while loop.

The problem is that your while condition is checking the values of the first 2,while the code inside the inner loop is working with the second 2.

To fix it, remove the declarations that are inside the loop and initialize the first i to 0.

C++
#include <iostream>
using namespace std;

main()
{
    int c[100];
    int z, i=0;
    do{
        //int z, i=0;
        cout<<"Please enter number(-1 to end)"<<endl;
        cin>>z;
        if(z!=-1)
        {
            c[i]=z;
        }
        i++;
    }   while(z!=-1 && i<100);
    cout<<"the total number of positive integers entered"<<i-1;
}
 
Share this answer
 
Quote:
int z, i=0;
This is a mistake. Variable i should be initialized before (outside) the do loop.


In my opinion, using a break would make your intentions more explicit:

C++
int main()
{
  int c[100];
  size_t n;
  for (n=0; n<sizeof(c)/sizeof(c[0]); ++n)
  {
    cout << "please enter a number (-1 to end)" << endl;
    cin >> c[n];
    if ( c[n] == -1) break;
  }
  cout << "the total number of positive integers entered is " << n << endl;
}
 
Share this answer
 
v3

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