6 Example iffound printfs is in the list at row dnstri else printfs is not in

6 example iffound printfs is in the list at row

This preview shows page 6 - 9 out of 9 pages.

6 Example … if(found) printf("%s is in the list at row %d\n",str,i); else printf("%s is not in the list.\n", str); system("pause"); return 0; }
Image of page 6
7 Use of break in loops We saw the use of break to exit from a switch statement. Another use of break is to terminate a loop before it reaches its terminating condition. For example, instead of using the flag, found , as an additional condition for terminating the searching loop in the last example, we could simply break to terminate the loop as follows. while (i<NUM) { if(strcmp(names[i], str) == 0) break; else i++; } We can also use break to terminate a for or do-while loop as shown in the next example.
Image of page 7
8 Example #include <stdio.h> #include <string.h> #define NUM 10 #define LEN 20 int main(void ) { int i = 0; char str[LEN]; char names [NUM][LEN] = {"Abdullah", "Ibrahim", "Husam", "Ahmad", "Hamzah", "Abdul-aziz", "Abdul-majeed", "Nayef", "Akhaled", "Yousef"}; printf("The length of the names are:\n"); for(i = 0; i < NUM; i++){ printf("%-4d%-12s of length %d\n", i+1,names[i], strlen(names[i])); } printf("\nEnter a name to search in the list: "); gets(str); for (i=0; i<NUM; i++) { if(strcmp(names[i], str) == 0) break; } if ( i == NUM ) //the loop terminated because the array is exhausted printf("%s is not in the list.\n", str); else printf("%s is in the list at row %d\n",str,i); system("pause"); return 0; }
Image of page 8
9 Use of continue in Loops continue is another useful construct that allows you break the current iteration of a loop before it finishes and start another one. The next example demonstrate how it works. #include <stdio.h> int main(void) { int i; for (i=0; i<10; i++) { printf("\nMa'assalam "); if (i < 5) continue; printf("Shabab"); } printf("\n"); system("pause"); return 0; }
Image of page 9

You've reached the end of your free preview.

Want to read all 9 pages?

  • Spring '10
  • baleh

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

Stuck? We have tutors online 24/7 who can help you get unstuck.
A+ icon
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes