பாடம் 6 / 6 · Control Flow · படிக்க 3 min · புதுப்பிக்கப்பட்டது
break, continue, goto
Loop-ல இருந்து சீக்கிரமா வெளிய வர்றது, ஒரு சுத்தை விடுறது, goto இன்னும் ஏத்துக்கக்கூடிய ஒரே இடம்.
continue — இந்த சுத்துல மீதியை விடுறது
#include <stdio.h>
int main(void)
{
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
continue; /* skip multiples of 3 */
}
printf("%d ", i);
}
printf("\n");
return 0;
}
1 2 4 5 7 8 10
continue நேரா அடுத்த சுத்துக்கு தாவும். for loop-ல step (i++) அப்பவும் ஓடும்; while loop-ல variable ஏற்கனவே மாறியிருக்கான்னு உறுதி பண்ணுங்க — இல்லன்னா loop முடியவே முடியாது.
break — இப்பவே loop-ஐ விட்டு வெளிய வாங்க
#include <stdio.h>
int main(void)
{
int nums[] = {4, 9, 15, 7, 22};
for (int i = 0; i < 5; i++) {
if (nums[i] > 10) {
printf("First over 10: %d at position %d\n", nums[i], i);
break; /* no need to look further */
}
}
return 0;
}
First over 10: 15 at position 2
goto — nested loops-ல இருந்து வெளிய வர மட்டும்
#include <stdio.h>
int main(void)
{
int grid[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
if (grid[r][c] == 5) {
printf("Found 5 at row %d, column %d\n", r, c);
goto done; /* leaves BOTH loops */
}
}
}
printf("Not found\n");
done:
printf("Search finished\n");
return 0;
}
Found 5 at row 1, column 1
Search finished
goto label; label:-ன்னு குறிச்ச line-க்கு தாவும். break உள் loop-ல இருந்து மட்டும் தான் வெளிய வரும்; அதனால ரெண்டு loops-ல இருந்து ஒரே நேரத்துல வெளிய வர்றது தான் goto மத்த வழிகளை விட தெளிவா இருக்கிற பழைய உதாரணம்.
Warning
goto-ஐ loop-ஆவோ, பின்னாடி தாவவோ use பண்ணாதீங்க. இஷ்டத்துக்கு தாவுற code ("spaghetti code") பின்தொடரவும் திருத்தவும் ரொம்ப கஷ்டம். Nested loops-ல இருந்து முன்னோக்கி வெளிய வரவோ, function-ஓட கடைசில இருக்கிற ஒரே clean-up பகுதிக்கு போகவோ மட்டும் use பண்ணுங்க.
ரெண்டு nested loops-க்குள்ள break எதை விட்டு வெளிய வரும்?
இப்போ இதை செஞ்சு பாருங்க
- continue வெச்சு, 5 அல்லது 0-ல முடியுற numbers-ஐ விட்டுட்டு 1-ல இருந்து 50 வரைக்கும் print பண்ணுங்க.
- User negative number கொடுக்கிற வரைக்கும் numbers படிச்சு, அப்புறம் total-ஐ print பண்ணுங்க (break use பண்ணுங்க).
- goto search-ஐ
foundflag வெச்சு மாத்தி எழுதி, எது தெளிவா இருக்குன்னு முடிவு பண்ணுங்க.
Create a free account to save your progress, or sign in.