shivalika pillai
shivalika pillai

Reputation: 3

Why is break used here to break out of if statement

Why is break used here to break out of if statement? Is it allowed?

And why are x and y made 0 at the end? x = 0; y = 0

https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/vowels-love/submissions/**

#include<stdio.h>
#include<string.h>
 
int main(){
  int i,x=0,j,y=0,T,p,q;
  char s1[1000001], v1[6] ="aeiou", v2[6] = "AEIOU";
  scanf("%d",&T);
  for(q=0;q<T;q++){
    scanf("%s",&s1);
    p=strlen(s1);
    for(i=0;i<5;i++){
       for(j=0;j<p;j++){
        if(v1[i]== s1[j]){
          y++;
          break;
        }
      }
    }
           
    for(i=0;i<5;i++){
      for(j=0;j<p;j++){
        if(v2[i]== s1[j]){
          x++;
          break;
        }
      }
    }
 
    if(y==5 || x==5) 
      printf("lovely string\n");
    else
      printf("ugly string\n");
    
    x=0;
    y=0;
  }
  return 0;
}

Upvotes: 0

Views: 68

Answers (1)

shirleyquirk
shirleyquirk

Reputation: 1598

break doesn't exit the if statement, it exits the inner-most loop. it is most certainly allowed, break is only useful inside an if or switch statement.

x and y need to be reset to zero every time the outermost 'q' loop runs. A clearer way to organize the code would have been to put each local variables inside its smallest possible scope, and name the variables appropriately to help readability. i.e. x=>n_upper_vowels,y=>n_lower_vowels etc.

int main(){
  int T;
  char word[100001], lower_vowels[6] ="aeiou", upper_vowels[6] = "AEIOU";
  scanf("%d",&T);
  for(int q=0;q<T;q++){
    int n_upper_vowels=0,n_lower_vowels=0;
    scanf("%100000s",&word);
    int word_len=strlen(word);

    for(int i=0;i<5;i++){
       for(int j=0;j<word_len;j++){
        if(lower_vowels[i] == word[j]){
          n_lower_vowels++;
          break;
        }
      }
    }
           
    for(int i=0;i<5;i++){
      for(int j=0;j<word_len;j++){
        if(upper_vowels[i] == word[j]){
          n_upper_vowels++;
          break;
        }
      }
    }
 
    if(n_lower_vowels==5 || n_upper_vowels==5) 
      printf("lovely string\n");
    else
      printf("ugly string\n");
  }
  return 0;
}

allocating almost a megabyte on the stack for s1 (the max for a windows process is 1MB i believe) is excessive verging on dangerous. Edit(thanks @Bob__) The problem says the maximum input is 100,000 characters, so it should be char si[100001]: 100K, not 1M. You can(should!) use the width specifier of scanf to prevent a buffer overrun as shown above as well.

Upvotes: 1

Related Questions