Posts Tagged c programming

Contoh #1 C Programming

Ini adalah contoh mudah C programming yang saya bantu rakan untuk subjek asas C Programming.

Write program using both if/else n switch to convert two MKS derived unit to CGS derived units. Selection of units can be your own choice.

#include //standard input output function
#include //to use the getch() function
#include //to use exit() function

//declare functions
void unit1(void); //void becouse function will not return any value
void unit2(void);

//declare global variables
float accInMKS, accInCGS;
double areaInMKS, areaInCGS;

void main(){
//declare local variables
char choice; //declare local variable

for(;;){ // infinate loop. system will keep on looping untill user insert EOF

select:
clrscr(); //clear the screen
printf (”===========================\n”);
printf (”Data convertion application\n”);
printf (”===========================\n\n”);

printf(”Please select\n”);
printf(”Enter 1 for converting 1st unit : Acceleration\n”);
printf(”Enter 2 for converting 2nd unit : Area\n”);
printf(”Enter EOF for exit\n”);

printf(”Choice : “);
scanf(”%c”, &choice); //get user selection

//switch between user selection
switch(choice) {
case ‘1′: unit1(); //call function 1
break; //stop current operation
case ‘2′: unit2(); //call function 1
break;
//user will exit if they insert “eof” or “EOF”
case ‘eof’:
case ‘EOF’ : exit(0); // 0 means system terminat without error
break;
default : goto select; // go back to first screen for user input

}
printf (”\n\nPress any key\n\n”);
getch(); //get user input or can use to freeze the screen
}

}

void unit1(){
printf(”\nEnter Acceleration in MKS unit (M/S^2) :”);
scanf (”%f”, &accInMKS);
accInCGS = accInMKS*100;
printf (”\nAcceleration in CGS unit : %.3f cm/s^2″,accInCGS);

}

void unit2(){
getarea:
printf(”\nEnter area in MKS unit (m^2) :”);
scanf (”%lf”, &areaInMKS);
// check if user insert -ve value for area
if (areaInMKS <=0){
printf(”\nPlease only use posotif value for area\n”);
goto getarea; // request back input from user
}else{
areaInCGS = areaInMKS*10000;
printf (”\nArea in CGS unit : %.3lf (cm^2)”,areaInCGS);
}
}

1 Comment