Home > Software design >  how to print a condition at last after executing all the if else code
how to print a condition at last after executing all the if else code

Time:03-02

I want to check the input if the input is in the string names then print the number of the given name. If the given name is not in the string names then print "your name is not here" but I'm getting "your name is not here" every time I run my code.

#include<stdio.h>
#include<cs50.h>
#include<string.h>

int main(void)
{
string userinput;
string names [] = {"david", "mark"};
string numbers[] = {"123456789","987654321"};
userinput = get_string("name: ");

for(int i = 0; i<2 ;i  )
{
    if(strcmp(names[i], userinput) == 0)
    {
        printf("your number is %s ", numbers[i]);
    }
}
printf("your name is not here\n");
}




 **ACTUAL OUTPUT**

 name: david
 your number is 123456789 your name is not here

CodePudding user response:

A very simple solution would be creating a variable to keep track if the name has been found:

int found = 0;
for(int i = 0; i<2 ;i  )
{
    if(strcmp(names[i], userinput) == 0)
    {
        printf("your number is %s ", numbers[i]);
        found = 1;
        // Break so we don't have to iterate over the rest
        // of the items if we already found our name.
        break;
    }
}
if (!found) printf("your name is not here\n");

CodePudding user response:

This is naturally very simple code, but you should already start to think about program design early on. Your code does three different, separate things:

  1. Prompt for input/take user input (I/O).
  2. Search if input matches a value (search algorithm).
  3. Present the results (I/O).

Ideally keep parts 2) and 3) separate not to mix up I/O with algorithms, so:

#include <stdbool.h>
...

bool found = false;
for(int i=0; i<2; i  )
{
  if(strcmp(names[i], userinput) == 0)
  {
    found = true;
    break;
  }
}

if(found)
{
  printf("your number is %s \n", numbers[i]);
}
else
{
  printf("your name is not here\n");
}

We could split up these parts in separate functions if we wish. For example if the amount of strings is expanded, we'll want to implement a better search algorithm than this "brute force" loop.

  • Related