90 likes | 164 Views
Collection of coding exercise solutions for practicing loops, switch statements, and functions in different programming languages. Improve your coding skills with these practical examples.
E N D
REVIEW EXTRAVAGANZA EXERCISE Surie Aziz @ SMKDPM2009
Q1 : Write a while loop that output the numbers 2, 4, 6, 8, ..., 20. Answer : i=2; While(i<=20) { printf(“\n%d “,i); i=i+2; } Surie Aziz @ SMKDPM2009
Q2 : Write a while loop that calculates the sum 2 + 4 + 6 + 8 + ... + 20. Answer : i=2; While(i<=20) { total=total+i; i=i+2; } printf(“\nSum=%d”,total); Surie Aziz @ SMKDPM2009
Q3 : Write a for loop that calculates the sum 22 + 42 + 62 + 82 + ... + 202. Answer : for( i = 2 ; i < =20 ; i = i + 2 ) { total = total + ( i * i ) ; } printf(“\nSum=%d “,total); Surie Aziz @ SMKDPM2009
Q4 : Write a for loop that calculates the sum of the numbers entered by the user. The loop will read numbers entered by the user until the user enters a negative number. . Answer : num=1; while (num>0) { printf(“\nPlease Enter a number “); scanf(“%d”,num); total=total+num; } printf(“Sum=%d”,total); Surie Aziz @ SMKDPM2009
Q5 : Write a switch statement that outputs "vowel" if a character is a vowel ('a', 'e', 'i', 'o', 'u'), "consonant" if a character is a consanant (a letter that is not a vowel), "digit" if the character is a digit ('0', '1', '2', ..., '9'), and "other" if the character is something else. Answer : scanf(“%c”,inputdata); switch (inputdata) { case ‘ a’ , ‘e’, ‘I’, ‘o’, ‘u’: printf(“\nVowel”);break; case ‘b’,’c’,’d’…………:printf(“\nConsonant”);break; case ‘0’,’1’,’2’,’3’,’4’,’5’,’6’,’7’,’8’,’9’:printf(“\nDigit”);break; default : printf”\nOthers”); break; } Surie Aziz @ SMKDPM2009
Q6: Write a loop that calculates 22 + 42 + 52 + 62 + 72 + 82 + 102. Answer : for( i = 2 ; i < =10 ; i = i + 2 ) { total = total + (i*i); } printf(“\nSum=%d “,total); Surie Aziz @ SMKDPM2009
Q7: Write a function that calculates 12 + 22 + 32 + ... + n2 for a given value n. Answer : Void Calculation() { printf(“\nPlease enter a number”); scanf(“%d”,n); for( i = 1 ; i < =n ; i++) { total = total + (i*i); } printf(“\nSum=%d “,total); } Surie Aziz @ SMKDPM2009
Q8: Write a function that reads numbers entered by the user (until the user enters a negative number) and returns the largest number that was entered by the user. Answer : Void Calculation() { printf(“\nPlease enter a number”); scanf(“%d”,num); large=0; While (num>0) { If (num>large) large=num; printf(“\nPlease enter a number”); scanf(“%d”,num); } printf(“\nLargest Number = %d”,large); } Surie Aziz @ SMKDPM2009