user6274708
user6274708

Reputation:

Is there a way to skip a conditional statement in a loop after condition has been satisfied?

Suppose we have a bool variable initialized with the value 0.This variable is to be used in a loop and turn to 1 once a certain condition has been satisfied. Once it acquire the value of 1 it becomes superfluous so is there a way to skip it in a loop for optimization?

My code :

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

int main(void)
{
    bool var = 0;
    char str[] = "          Hello babz what's up with you?!";
    size_t n, len = strlen(str);
    for (n = 0; n < len; n++) {
        if (str[n] != ' ') {
            var = 1;
        }
        if (var) {
            printf("%c", str[n]);
        }
    }
    putchar('\n');
    return 0;
}

Upvotes: 0

Views: 110

Answers (3)

pm100
pm100

Reputation: 50190

drop out of loop once you detect the condition and go to second loop

bool var = 0;
char str[] = "          Hello babz what's up with you?!";
size_t n, len = strlen(str);
for (n = 0; n < len; n++) {
    if (str[n] != ' ') {
        var = 1;
        break;
    }
}

  for (; n < len; n++) {
      printf("%c", str[n]);
  }
putchar('\n');
return 0;

of course you could get much more idiomatic

char *p = str;
while(*p && *p==' ') p++;
puts(p);

Upvotes: 4

chux
chux

Reputation: 153498

Code only prints if str[n] != ' ' is true. len not needed.

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

int main(void) {
    char str[] = "          Hello babz what's up with you?!";
    size_t n;
    for (n = 0; str[n]; n++) {
        if (str[n] != ' ') {
          fputs(&str[n], stdout);
          break;
        }
    }
    putchar('\n');
    return 0;
}

Or use pointers as in @Jean Jung and a puts() which will append the '\n'.

int main(void) {
    char str[] = "          Hello babz what's up with you?!";
    char *ptr = str;
    while (*ptr == ' ') ptr++;
    puts(ptr);
    return 0;
}

Upvotes: 1

Jean Jung
Jean Jung

Reputation: 1210

You can also use pointers:

char str[] = "          Hello babz what's up with you?!";
char *pstr = str;
while (*pstr == ' ') pstr++;
while (*pstr != '\0') 
{
    printf("%c", *pstr);
    pstr++;
}
putchar('\n');

Upvotes: 0

Related Questions