Transcript Document

+

CPS125

+

o o

IF … ELSE …

Very similar to the IF statement seen before.

Enhances the decision-making capability.

General Syntax:

if (condition) statement1; else statement2;

o if the condition is TRUE then statement1 is executed.

o Otherwise statement2 is executed.

NOTE:  if and else are C keywords, then is not.

2

+

/* Even vs. Odd */

 #include  int main (void) {  int number, even;  /* ask user for number */  printf ("Enter an integer number: ");  scanf ("%d", & number);  /* determine if number is even and put in variable */  even = (number % 2 == 0);  /* display report */  if (even)  printf ("%d is an even number.\n", number);  else  printf ("%d is an odd number. \n", number);  return (0);  } 3

+

+

  Practice! /* PROGRAM #9*/ /* PROGRAM TO CALCULATE COURSE MARKS */ #include  #define MidTermWeight 0.30  #define ExamWeight 0.50

 #define LabWeight 0.20

 main( ){ float MidTerm, Exam, Lab; float WrittenWork, LabWork, Grade; /* Input the mid-term, exam and lab mark */  printf("Please enter your mid-term mark: ");         scanf("%f", &MidTerm); printf("Please enter your exam mark: "); scanf("%f", &Exam); printf("Please enter your lab mark: "); scanf("%f", &Lab); /* Calculate the grade, test if the grade is A+ and print the result */ WrittenWork = MidTerm * MidTermWeight + Exam * ExamWeight; LabWork = Lab * LabWeight; Grade = WrittenWork + LabWork;  if (Grade >= 90) printf("Definitely A+.\n"); else  printf("Either B or C or D or even F!.\n");} 5

+

Nested if … else

Very similar to if … else … statement seen before  Example: if (exp_1) stat_1; else if (exp_2) stat_2; else stat_3; Description:  If exp_1 is TRUE then stat_1  If exp_1 is FLASE and exp_2 is TRUE then stat_2  If exp_1 is FLASE and exp_2 is FALSE then stat_3 6

+

Practice!

/* PROGRAM #10 */

 /* PROGRAM TO CALCULATE GST AND PST */  #include  #include  #define GST 0.08

 #define PST 0.05

  main( ){ char choice; float Ptax, Gtax; /* Get the selected letter by user */     printf("Use the menu - Select a Letter:\n"); printf("P] Provincial Tax. G] Goods & Services Tax.\n"); printf("Your selection (P or G): "); scanf("%c", & choice); float BTprice, ATprice;  /* Get the price before tax, calculate GST and PST print the result*/  printf("Please enter the Before the Tax price");  scanf("%f", & BTprice);  7

+

PrACTICE! Program: CALCULATE GST AND PST

 if (choice == ‘G’){  ATprice = GST * BTprice;  printf("The Before Tax Price is %f.\n",BTprice);  printf("The After Tax Price is %f.\n”, ATprice);  } else  if (choice == ‘P’){  ATprice = PST * BTprice;  printf("The Before Tax Price is %f.\n",BTprice);  printf("The After Tax Price is %f.\n”, ATprice);  } else{  printf("That was not one of the choices.\n");  printf("Sorry!\n");  } exit(0);  } 8

+

Modes of operation

+

Modes of operation

Interactive mode: User responds to prompts by typing in data. Data is entered with the keyboard.

Batch mode: program takes its data from a data file prepared beforehand.

To read from a file we use

fscanf

instead of scanf.

To write to a file instead of displaying on screen we used

fprintf

.

To create a data file, we can use a simple text editor like notepad.

10

+

Reading Data from a File

 If your input data is

lengthy

and you are planning to

execute your program many times

, it is not convenient to input your data from the keyboard. this is true especially if you want

to make only minor changes

to the input data each time you execute the program.

 You must remember ,though , that when you create your input file using your

editor

that you

give that file the same name

you have specified

in the code

for your program.

File pointer

is a variable whose memory cell contains an address instead of an int ,float, or double value. This address gives the key to accessing the file stored on disk.

11

+

Reading from a file

To do that you need first to declare the file  FILE *in;  /*notice that FILE is all upper case and the * before the name of the file variable.*/ Then the file must be opened  in = fopen (“mydata.txt”,”r”);  /* must exist on your disk! */ To read from the file,we use fscanf  fscanf(in, “%d” ,&var); The file must be closed when not longer needed  fclose(in); 12

+

Writing to a file To do that you need first to declare the file

 FILE *out;

Then the file must be opened

 Out = fopen (“result.txt”,”w”);  /* w is for write – it will create a new file on your disk */

To write to the file,we use fprintf

 fprintf(out, “%d” ,var);

The file must be closed when not longer needed

 fclose(out); 13

+

Writing to A FILE

 #include  void main(void)  {  double income=123.45, expenses=987.65;  int week=7, year=1996;  FILE *myfile;   myfile = fopen("L3_8.OUT","w");  fprintf(myfile,"Week=%5d\nYear=%5d\n",week,year);  fprintf(myfile,"Income =%7.2lf\n Expenses=%8.3lf\n",  income,expenses);  fclose(myfile);  } 14

+

Practice more!

/* PROGRAM #11 */  /* PROGRAM TO CALCULATE COURSE GRADE*/  #include  main( ){ float Grade;   /* Input the grade */ printf("Pls enter your grade in CMTH140: ");         scanf("%f", & Grade); /* Calculate the grade and print the result*/ if ((Grade <= 100) && (Grade >= 90)) printf("Congratulations! A+ grade.\n"); if ((Grade <= 89) && (Grade >= 85)) printf("Excellent! A grade.\n"); if ((Grade <= 84) && (Grade >= 80)) printf("Excellent! A- grade.\n");     if ((Grade <= 79) && (Grade >= 77)) printf("Very Good! B+ grade.\n"); if ((Grade <= 76) && (Grade >= 74)) printf("Very Good! B grade.\n");  15

+

CALCULATE COURSE GRADE

 if ((Grade <= 73) && (Grade >= 70)) printf("Very Good! B- grade.\n");   if ((Grade <= 69) && (Grade >= 67))  printf("Good! C+ grade.\n");  if ((Grade <= 66) && (Grade >= 64))    printf("Good! C grade.\n"); if ((Grade <= 63) && (Grade >= 60)) printf("Good! C+ grade.\n");         if ((Grade <= 59) && (Grade >= 57)) printf("Acceptable! D+ grade.\n"); if ((Grade <= 56) && (Grade >= 54)) printf("Acceptable! D grade.\n"); if ((Grade <= 53) && (Grade >= 50)) printf("Acceptable! D- grade.\n"); if ((Grade <= 49)) printf("Sorry! F grade.\n");  } 16

+

Practice!

The traffic light program (nested ifs)

 A program that displays the recommended actions depending on the color of a traffic light.  This program uses nested if statements. 17

/* The traffic light program (nested ifs) */  #include  int main (void)  { char colour; /* ask user for colour */  printf ("Enter the colour of the light (R, G or Y): ");  scanf ("%c", & colour); /* test if colour is red */  if (colour == 'r' || colour == 'R')  printf ("STOP! \n");  else  if (colour == 'y' || colour == 'Y') /* yellow colour test */  printf ("CAUTION! \n");  else if (colour == 'g' || colour == 'G') /* green colour test */  printf ("GO! \n");  else /* if not Y or G or R then invalid colour */  printf ("INVALID COLOUR! \n");  return (0);  } 18

+

SWITCH

19

+

C Switch  C has built in multiple-branch selection statement, called switch, which successively tests the value of an expression against a list of integer or character constants floating point and double are not allowed.

 Switch statement is often used to process keyboard commands, such as menu selection.

 When a match is found ,the statements associated with that constant are executed. The value of expression is tested against the values, one after another, of the constants specified in the case statements.

 When a match is found, the statement sequence associated with that case is executed, until the break statement or the end of the switch statement is reached.

 The default statement is executed if no matches are found. The default is optional, and if it is not present, no action takes place if all matches fail.

20

+

C Switch

To make selection out of several choices Very Similar to if … else … But probably easier way to code multiple if … else … switch (selection){

case

choice1 :

break;

… (statement1); … …

default :

(statementN); } switch, case, break, default: selection: ‘C’ reserved words A ‘C’ expression, can be either int or char.

choice: required match, must be of same type as expression1. 21

+

Switch Statement

22  The switch statement is a useful alternative for multiple branches (not just true and false).

 It works not with conditions but with control values.

 The control values must be int or char only, never double.

 The control values must be discrete, never ranges.

+

NOTE!!!

 If SELECTION matches any of the CHOICES, then the corresponding statement will be executed.

 DEFAULT is used when no match is made, then this option will be executed.

 BREAK is used to get out of terminate the SWITCH statement.

 Nested switch statements can be used if required.

23

+

/* PROGRAM # 12 */

/* PROGRAM #12 */ /* USE OF IF STATEMENT FOR A MENU SYSTEM */  #include  #define TGPA 4.3

 #define CGPA 3.00

 #define CPS125 'A’  main (){ int choice; /*Get the user's selected option*/  printf("Select one of the following choice:\n");  printf("1)TGPA , 2)CGPA, 3)CPS125\n"); scanf("%d",&choice); /* Print the result based on the input */  if (choice == 1)  printf("Your term GPA is: %3.2f.\n",TGPA);  else  if (choice == 2)   else printf("Your Cumulative GPA is: %3.2f.\n",CGPA);  if (choice == 3)  printf("Your grade in CPS125 is: %c. ",CPS125);  else  printf("The selected option does not exist!"); } 24

+

 

PRACTICE! /* PROGRAM # 13 */

/* PROGRAM #13 */ /* USE OF SWITCH STATEMENT */ #include  #define TGPA 4.3

 #define CGPA 3.00

 #define CPS125 'A'  main (){ int choice;  /*Get the user's selected option*/  printf("Select one of the following choice:\n");  printf("1)TGPA , 2)CGPA, 3)CPS125\n");  scanf("%d", & choice);  /* Using switch statement to print the result based on the input */  switch (choice ){ case 1: printf("Your term GPA is: %3.2f.\n",TGPA);  break;      case 2: printf("Your Cumulative GPA is: %3.2f.\n",CGPA); break; case 3: printf("Your grade in CPS125 is: %c. ",CPS125); break; default: printf("The selected option does not exist!"); } } 25

+

PRACTICE! /* PROGRAM # 14 */

 #include  main( ){   char choice; float course1=0, course2=0, course3=0;   float sum=0, TGPA; /* Make a selection from the menu */ printf("Select one of the following choice:\n");  printf("a)Get the grades for 3 courses, \n”);  printf("b)Calculate the term GPA [CGPA],\n");  printf("c)Print course and GPA information,\n");    scanf("%c", & choice); /* Should work for upper case & lower case */ if ( choice == ‘a’ || choice == ‘A’)   choice= ‘a’; if ( choice == ‘b’ || choice == ‘B’)   if ( choice == ‘c’ || choice == ‘C’)  choice= ‘b’; choice= ‘c’; 26

   

+ switch(choice){

case ‘a’:{

printf("Pls enter the grade for the 1st course: "); scanf("%f",

&

course1); printf("Pls enter the grade for the 2nd course: ");

 

scanf("%f",

&

course2); printf("Pls enter the grade for the 3rd course: ");

 

case ‘b’:{ scanf("%f",

&

course3); }

 

break; if (course1 == 0

&&

course2 == 0

&&

course3== 0 ){

   

}

printf(“You need to provide the grades first and then try to calculate the GPA.\n”); else{

sum=course1+course2+course3; TGPA=sum/3.0; }

 

}

 

case 'c':{

 

break; if (TGPA == 0 ){

printf(“Need to provide the grades first & then calculate the GPA,

&

try this option.\n”);

}

 

break; else{

printf(“Course#1: %f\n”, course1); printf(“Course#2: %f\n”, course2); printf(“Course#3: %f\n”, course3); printf(“Your term GPA is: %f\n”, TGPA); } default: printf("Sorry wrong selection! Pls try again!\n"); }

}

 

}

 27