switch case statement का उपयोग करना सीखेंगे - Tech S K

Latest

Notes of Computers Technology Information,Latest Tech News, O Level Software Notes,RS CIT notes The notes of all the computer's exams are available here

Recent Posts

Translate

बुधवार, 13 जून 2018

switch case statement का उपयोग करना सीखेंगे

आज Hindi के इस C programming language tutorial को आगे बढ़ाते हुए हम switch case statement का उपयोग करना सीखेंगे. इसकी if else statement से बहुत समानता है. वास्तव में बिना switch case statement के भी सारा काम if else के द्वारा भी किया जाता है परन्तु इसके उपयोग से कई बार हमें आसानी हो जाती है. इसे हम एक example द्वारा समझते हैं. नीचे दिए गए example में दो integer दिए गए हैं. हम एक variable की value के द्वारा decide करेंगे कि उनको जोड़ना है या घटाना है...
#include <stdio.h>

int main() {

float v1 = 23;
float v2 = 9;

float result;
char c = 's';

switch(c) {
case 'a':
result = v1 + v2;
printf("Result of addition is %f \n", result);
break;
    case 's':
result = v1 - v2;
printf("Result of subtraction is %f \n", result);
break;
    case 'm':
result = v1 * v2;
printf("Result of multiplication is %f \n", result);
break;
    default:
printf("No operation selected.\n");
}

scanf("%s");
return 1;
}

अब इसे समझते हैं. हमने एक variable c define किया है जिसका type char है और value s है. (char के बारे में जानने के लिए मेरे पिछले लेख में जाएँ) अब code को ध्यान से देखें. switch के अंदर लिखे गए variable c का मान हर एक case लिखे गए मान से compare किया जाता है. जैसे कि इस example में c का मान s है. पहले case में लिखा गया मान a है इसलिए इस case के अंदर लिखे गए statements execute नहीं होंगे. इसी तरह आगे बढते जायेंगे. switch(c) अंदर लिखे गए c का मान case 's': में लिखे s से match हो जायेगा इसलिए result variable में v1 और v2 के  difference का मान आ जायेगा और screen पर print होगा Result of substraction is 14. break statement run होने पर यह switch() { } block  से बाहर आ जायेगा. अगर break नहीं लिखा जाता तो यह किसी एक case match होने के बाद आगे के सारे case execute कर देता चाहे वो switch() के अंदर लिखे variable से match हो या न हो. अगर कोई भी case match न हो तो default के अंदर लिखे statement execute हो जाते हैं. ऊपर दिए program में c के अलग अलग मान देकर program run करे और output देखें.

यहाँ एक और ध्यान देने योग्य बात है कि हमने float को print करने के लिए printf में %f use किया है.
अगले लेख में हम for loop के बारे में जानेंगे.

कोई टिप्पणी नहीं:

एक टिप्पणी भेजें

Friends, if you like this post then please share it on Facebook! Please tell through the comments that these posts will welcome you as well as your suggestions.