Home > Mobile >  if....else executing in the same time . Looking this problem for first time. Please anybody make me
if....else executing in the same time . Looking this problem for first time. Please anybody make me

Time:04-06

I was solving a problem . Where i was comparing two array ,one is int and other is string . inside for loop everything was fine until i inserted a else condition.Before else condition for loop was just fine . it was giving equel index for two array . But after else condition it was giving both the condition together. here are my code-

#include <iostream>
#include <string>
using namespace std;
int main()
{
 int last_digit[] = {61, 71, 11, 21, 32, 19, 27, 31};
 string places[] = {"Brasilia", "Salvador", "Sao Paulo", "Rio de Janeiro", "Juiz de Fora",                       "Campinas", "Vitoria", "Balo Horizonte"};
int digit;
 cin >> digit;
for (int i = 0; i <= 7; i  )
 {
 if (digit == last_digit[i])
cout << places[i]<< endl;
 else
cout << "Sorry! no number." << endl;
}

Now i want to print the array values as index which is right without the else condition. But i when an input isn't in the array the program should give else condition once. But it is giving both if else condition. Here are my output .

emamulhaqueemon@Emams-MacBook-Air snake % cd "/Users/emamulhaqueemon/main/snake/" && g   test.cpp -o test && "/Use
rs/emamulhaqueemon/main/snake/"test
11
Sorry! no number.
emamulhaqueemon@Emams-MacBook-Air snake %

now why this is happening and how can i make this right .Please anybody give the answers.

CodePudding user response:

Your loop currently does too much:

  • find digit in last_digit
  • print corresponding element according to found digit
  • print no matching elements (whereas you want to print when find fails).

You might split that in smaller parts.

With functions from std, you might do:

const auto it = std::find(std::begin(last_digit), std::end(last_digit), digit);

if (it == std::end(last_digit)) { // Not found
    std::cout << "Sorry! no number." << std::endl;
} else { // Found
    const auto index = std::distance(std::begin(last_digit), it);
    std::cout << places[index] << std::endl;
}

Demo

CodePudding user response:

Just place the output statement in the else part of the if statement outside the for loop. For example

bool found = false;

for (int i = 0; i <= 7; i  )
{
    if ( digit == last_digit[i])
    {
        found = true;
        cout << places[i]<< endl;
    }
}
 
if ( !found )
{
    cout << "Sorry! no number." << endl;
}

If the array last_digit does not contain duplicate values and you need to find only the first occurrence of the value digit in the array then the loop can look the following way

for (int i = 0; !found && i <= 7; i  )
{
    if ( digit == last_digit[i])
    {
        found = true;
        cout << places[i]<< endl;
    }
}
 
if ( !found )
{
    cout << "Sorry! no number." << endl;
}
  • Related