0

I'm trying to write a program that asks the user to enter digits between 0 and 1000000 and it outputs the occurrence of a certain number (that the user entered as well)

I've wrote this program and I believe it works well, but I have one issue which is if the while expression is not true, I want to cout a certain message but I don't know where to place it.

Here's my program:

#include <iostream> 
using namespace std;
int main()
{ 
 int n,j=0,key; 
 cout << "Pleaser enter digits\n";
 cin >> n;
 cout << "please enter key number\n";
 cin >> key;

 while (n>0 && n<1000000)
 {
   if(n%10==key)j++; 
      n= n/10;
 }

 cout << "The number " << key << " was found " << j << " time(s)" << endl;
 return 0;  
}

Thanks in advance!

i alarmed alien
  • 9,412
  • 3
  • 27
  • 40
Noor AIH
  • 25
  • 3
  • You could just wrap the while loop in an `if` `else` condition block, so `if (n <=0 || n >= 1000000) cout << "invalid params"; else { while...}` – EdChum Oct 06 '14 at 11:18
  • You **do** cout a certain message if the while condition is not true. Do you meant "if the while expression is not true *the first time*"? – TobiMcNamobi Oct 06 '14 at 11:18
  • @TobiMcNamobi Yes, he meant when user enters value of n not in range (0, 1000000) – Ashwani Oct 06 '14 at 11:26

3 Answers3

2

Use

if(n>0 && n<1000000)
{
    while(n)
    {
       if(n%10==key)
       j++; 
       n= n/10;
    } 
}
else 
cout<<"n is supposed to be between 0 and 1000000";
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
0

Write a if statement before while loop.

     if(!(n>0 && n<1000000))
        {
           cout << "....";
           return -1;
        }

      while(..)
user966379
  • 2,823
  • 3
  • 24
  • 30
0

As there are no breaks (or no other piece of code that can jump) inside the bucle, everything after the while structure is executed because the expression returned false.

while (n>0 && n<1000000)
{
   if(n%10==key)j++; 
   n= n/10;
}
cout << "While expression not anymore true" << endl;
cout << "The number " << key << " was found " << j << " time(s)" << endl;
return 0;  
}

UPDATE

Based on the comments, it seems that you want to check if the number entered is valid or not. Simply, just check it before the while:

if(not (n>0 and n<1000000)) cout << "Number must be between 0 and 1000000" << endl;
else {
    while (n)
    {
        if(n%10==key)j++; 
        n= n/10;
    }
}
cout << "The number " << key << " was found " << j << " time(s)" << endl;
return 0;  
}
otorrillas
  • 4,357
  • 1
  • 21
  • 34