Tutorial 7.1: Functions

Introduction
Programs that solve the real-world problem are usually consist of thousands (or more) of lines of code. In that case, it is not easy to develop, maintain and manage a large source code in a single function - main(). So when we are writing a big program, the best way to deal with it is to break the large program into smaller sets of statements (functions) according to their tasks. For example we could define functions that performs the printing of user instructions, reading inputs from user, calculating equation and etc . Whenever we need to do something, we just call the relevant function in the main() that do the specific task. In that case, our program will be neat and tidy and errors can be easily detected and solved. The following figure illustrates the sequence of execution when functions are called.

When a function (function1) is called, in this case within function main(, te statements within the block of function1 are executed. When it reaches at the end of the block, it returns to the main function and continues at the point at which the function1 was called. Similarly, a function can be invoked by another function. The sequence of execution is the same as when the main function calls a function. This is illustrated in the figure where function3 calls function4.

#include <stdio.h>

int main()
{
 int count;
 float score;
 float sum = 0;
 float average;
 printf("Enter scores for");
 printf(" class A (-1 to end input):\n");
 for (count = 0; ; count++) {
  scanf("%f", &score);
  if (score == -1) break;
  else {
   sum += score;
  }
 }
 average = sum / count;
 printf("Class A average is %.2f\n\n", average);
 
 sum = 0;
 printf("Enter scores for");
 printf(" class B (-1 to end input):\n");
 for (count = 0; ; count++) {
  scanf("%f", &score);
  if (score == -1) break;
  else {
   sum += score;
  }
 }
 average = sum / count;
 printf("Class B average is %.2f\n\n", average);
 return 0;
}
B) Program with functions
#include <stdio.h>

void userInstruct(char clsName);
float getSum(float score);
float calcAverage(float sum, int count);
void printAverage(float average, char clsName);

int main()
{
 float score;
 float sum;
 float average;
 
 userInstruct('A') // call userInstruct function for class A
 for (count = 0; ; count++) {
  scanf("%f", &score);
  if (score == -1) break;
  else {
   sum = getSum(score);  // call getSum function
  }
 }
 average = calcAverage(sum, count) // call calcAverage function
 printAverage(average, 'A');   // call printAverage function
 
 userInstruct('B') // class A
 for (count = 0; ; count++) {
  scanf("%f", &score);
  if (score == -1) break;
  else {
   sum = getSum(score);  // call getSum function
  }
 }
 average = calcAverage(sum, count)
 printAverage(average, 'B');
 
 return 0;
}

void userInstruct(char clsName)
{
 printf("Enter scores for");
 printf(" class %c (-1 to end input):\n", clsName);
}

float getSum(float score)
{
 sum += score;
}

float calcAverage(float sum, int count)
{
 return sum / count;
}

void printAverage(float average, char clsName)
{
 printf("Class %c average is %.2f\n\n", clsName, average);
}
Sample output:

Enter scores for class A (-1 to end):
75
85
64
-1
Class A average is 74.67

Enter scores for class B (-1 to end):
37
97
71
-1
Class B average is 68.33


Both program A and B are written to perform the same task which is to calculate average score for two classes. But program A does not use functions and program B uses function. As you can see in program B, the codes of user instructions, read inputs, calculate and display the average are segmented into functions. In function main(), we invoke/call the relevant functions to perform the required tasks.

Next: Variable Scope and Sequence of Execution

Tutorial 6.5: Infinite Loop

Infinite Loop
Infinite loop is a repetition structure that loops forever, either due to it contains no condition that can cause the loop to be terminated or having condition that can never be satisfied. Let us see how while, do while and for loop statement can be set up to get an infinite loop.

Having an expression within the parenthesis of while and do while (second expression of for loop) that always returns true (non-zero value) can result an infinite loop. The following programs are example of infinite loop of while, do while and for repetition structure.
#include <stdio.h>

int main()
{
 int i = 0;
 while(1) { // loop condition is always true
  printf("%d\n", i);
  i++;
 }
 return 0;
}
#include <stdio.h>

int main()
{
 int i = 0;
 do {
  printf("%d\n", i);
  i++;
 }while(1); // loop condition is always true
 return 0;
}
#include <stdio.h>

int main()
{
 int i = 0;
 for(i = 0; 1 ; i++) { // loop condition is always true
  printf("%d\n", i);
 }
 return 0;
}
The loop condition (expression) is set to 1, resulting an infinite loop.

Sometimes infinite loop can be useful, for example when we want to write a program that computes the average of an arbitrary number of integers. A sample program is given below. The program should be able to allow the user to input any number of integers until he is satisfied. In this case, we have to define an infinite loop so as the program can perform the specific task. But what can we do to have the means of exiting the infinite loop? The answer is the statements in the loop's body must contains the means of exiting from the loop. Remember keyword break from Tutorial 5.4. We have seen how break can be used to jump out of switch selection bypassing the following statements. Similarly break can be used to exit a loop from any point of its body.
#include <stdio.h>

int main()
{
 int i = 0;
 float num = 0;
 float sum = 0;
 float average = 0;
 printf("This program computes the");
 printf(" average of any number of integers.\n");
 printf("Enter integers (-1 to stop input): \n");
 while(1) { // loop condition is always true
  scanf("%f", &num);
  if (num == -1)
   break;
  else {
   i++;
   sum += num;
  }
 }
 average = sum / i;
 printf("The average is %.2f\n", average);
 return 0;
}
Sample output:

This program computes the average of any number of integers.
Enter integers (-1 to stop input):
10
5
7
-1
The average is 7.33

 int i = 0;
 float num = 0;
 float sum = 0;
 float average = 0;
Here we declare four (4) variables namely i, num, sum and average. Variable i is used to count the number of integers entered by the user. The entered integer is stored in variable num. The summation of all integers is stored in variable sum and lastly variable average is used to store the average.
 printf("This program computes the");
 printf(" average of any number of integers.\n");
 printf("Enter integers (-1 to stop input): \n");
Then we display the user instruction using printf. We inform the user to input -1 if he wants to end input process.
 while(1) { // loop condition is always true
  scanf("%f", &num);
  if (num == -1)
   break;
  else {
   i++;
   sum += num;
  }
 }
We set up an the loop using while statement. Since loop condition has the value of 1, the block of statements will be repeated forever. In the body of the loop, we have read input from user statement. The input integer is stored in variable num. Then we compare the value of num with -1. If the comparison is true indicating the user wants to end the input process, break statement will be executed. Else the i is incremented and the value entered is added to variable sum.
 average = sum / i;
 printf("The average is %.2f\n", average);
Finally we calculate the average and display the result.

Next: Functions

Tutorial 6.4: Nested Loop

Nested Loop
Remember nested if, the same can be applied to repetition structure. A loop within a loop is called nested loop. Any type of loop can be placed in any type of loop. Its means, you can put a while loop in a for loop, do while loop in a while loop etc. The following is an example of nested loop.
#include <stdio.h>

int main()
{
 int i, j;
 for(i = 1; i < 11; ++i) {
  j = 1;
  sum = 0;
  do {
   sum += j++;
  } while(j <= i);
  printf("%d\t\t%d\n", i, sum);
 }
 return 0;
}
Sample output:

1 1
2 3
3 6
4 10
5 15
6 21
7 28
8 36
9 45
10 55


Explanation:

The program computes the sum of all numbers from 1 up to the value of j which is 10. Lets look at the loop structure.
for(i = 1; i < 11; ++i) {
 j = 1;
 sum = 0;
 do {
  sum += j++;
 } while(j <= i);
 printf("%d\t\t%d\n", i, sum);
}
The for loop is called the outer loop and the do while loop is called inner loop. Each time outer loop is repeated, inner loop will be executed and all its iteration are performed. This means, inner loop is executed or all its iteration are completed 10 in this example since the outer loop is repeated 10 times.

The for loop begins by assigning value of 1 to i. The loop condition is i < 11 thus the for loop will repeat for 10 times. For each iteration of for loop, variable sum is initialise to 0 and the do while is executed.
do {
 sum += j++;
} while(j <= i);
The do while loop computes the sum of all values of j each time j is incremented until the current value of i. You may wonder what is the statement
 sum += j++;
is doing. Actually that statement is equivalent to
 sum = sum + j;
 j++;
Next: Infinite Loop

Tutorial 6.3: for Repetition Structure

for Loop Statement
Unlike while and do while statement, for statement handles all the details such as variable initialisation, variable update and loop condition within single parantheses. If you still confuse with what i mean, lets revise the while loop example.



As you can see, the statements to control the loop operation are separated. In the for statement, these statements are combined together. Lets look at the for statement structure to have better understanding.

for ( variable initialisation; loop condition; variable update ) {
...statements...
}


for statement structure has three (3) fields which are variable initialisation, loop condition and variable update. These fields in the for statement are optional. we may omit variable initialisation and place it elsewhere in the program for example before for statement. If loop condition is omitted, C will assume that the condition is true thus resulting an indefinite loop. Variable update may be ommited if we want to place it in the body of for statement.

An example of for statement is given. The purpose of this program is to display zero (0) to nine (9).
#include <stdio.h>

int main()
{
 int count = 0;
 for(count = 0; count < 10; ++count) {
  printf("%d\n", count);
 }
 return 0;
}
Sample output:

0
1
2
3
4
5
6
7
8
9

Explanation:

As usual, we declare an integer variable count which acts as the loop counter. We do not initialise the variable unlike while and do while statement because it will be taken care of in the for statement.
for(count = 0; count < 10; ++count) {
 printf("%d\n", count);
}
Here we have the for repetition structure. The operation of the loop is controlled by the three expression between the for statement parantheses. In the variable initialisation field, we initialise variable to 0. The specified loop condition is count less than 10

Next: Nested Loop

Tutorial 6.2: do while Repetition Structure

do while Loop
The do while loop is similar to the while loop. In the while loop, the loop condition is tested at the beginning of the loop. The do while loop tests the loop condition at the end of the loop structure or after the body of the loop is executed. Thus in do while loop, the compounded statement will be executed at least once.

Lets look at an example of do while loop.
#include <stdio.h>

int main()
{
 int count = 0;
 do {
  printf("%d\n", count);
  ++count;
 }while(count < 10);
 return 0;
}
Sample output:

0
1
2
3
4
5
6
7
8
9

Explanation:

This is also a very simple program of do while loop. The function of the program is exactly the same as the example of while loop. We skip the counter declaration and initialisation since it is already covered in the previous example. We go straight to the do while loop structure.
do {
 printf("%d\n", count);
 ++count;
}while(count < 10);
Similarly, it contains two (2) statements action printing the value of count and ++count. Lets go through it line-by-line. When the do while is executed, it begins by executing the printf() function. Thus count is displayed on the monitor screen. Then count is incremented and it reaches the brace at the end of the loop. Here loop condition is tested and if it is true, it will go back up to the beginning and the body of the loop will be executed again. This action continues until the condition is false.

Next: for loop

Tutorial 6.1: while Repetition Structure

INTRODUCTION
In the previous tutorial, we have learned about sequence and selection structures. We know that selection structure allows us to specify how the computer will react to certain inputs. But there is still a limitation in what we can do in programming. For example what if we want to display numbers from 1 to 100? Of course we can do hundred lines of printf(), but what if we want to repeat a thousand times of 10 statements. We would have to write ten thousand of statements to achieve it and it is possible to do it. But it is not a convenience and it would take a long time to complete. Thus the ability to specify repetition of compound statements is as important in programming. Repetition of statements execution is called loop. Looping in a program is the process of executing series of instruction repeatedly in a given number of times.

There are two types of loop namely definite loop and indefinite loop. Definite loop also called counter-controlled loop is a repetition in which it will continue looping until certain condition is met. On the contrary indefinite loop has no certain condition in which it will continue looping forever. Thus statements enclosed by indefinite loop should contain the means of exiting from the loop. Typically, there are three requirements have to be specified in defining a definite loop. They are counter initialization, increment of counter and loop condition. The counter will determine how many times the loop will be executed. There are three types of repetition structure available in C namely while loop, do while loop and for loop.

But before going further, you should understand the concept of True and False in C. We have covered this concept in Tutorial 5. You might want to look at it if you still have not grasped the basic concept. We begin by discussing the while loop followed by do while loop. Then we will discuss for loop because I believe for loop is a bit complicated compared to the other loops.

while LOOP
while loop allows the repetition of a set of statements execution to continue for as long as a specified expression (condition) is true. When the condition becomes false, the repetition terminates and the first statement after the repetition structure is executed. Basically while loop is similar to if selection in the sense that their set of statements are executed if the condition is true. The different is while loop repeats the statement execution as long as the condition is true and if selection does not have the repetition feature.

Lets look at an example to have an idea what is while loop all about.
#include <stdio.h>

int main()
{
 int count = 0;
 while(count < 10) {
  printf("%d\n", count);
  ++count;
 } 
 return 0;
}
Sample output:

0
1
2
3
4
5
6
7
8
9

Explanation:

This is a very simple while loop. It has an expression as the mechanism of repetition and a set of statements. Now lets look at the first statement.
int count = 0;
Here, we declare an integer variable count and initialize it to 0. Variable count acts as the loop counter for the while loop.
while(count < 10) {
 printf("%d\n", count);
 ++count;
}
Now we look at our while loop. It contains two statements action printing the value of count and ++count. If you are not sure what ++count is doing, you might want to look at Tutorial 4 Increment and Decrement Operators.

Lets go through it line-by-line how while loop works in this example. It begins by testing the while loop condition. Variable count has value of 0, thus the condition of count < 10 is true. printf() prints the value of count and count is incremented. When it reaches the close brace, it jump back up to the beginning of the loop and the condition is tested again. This process is repeated until the condition becomes false and the loop is terminated.

Next: do while Loop

Tutorial 5.5: Electricity Bill Problem

PROBLEM
We are going to write a program that computes a customer's electricity bill. The rate of charge for the first 200 unit of electricity used is RM0.218. For the following unit of electricity used is RM0.334. A penalty of 1.5% of the unpaid balance if the unpaid balance is greater than zero. Electricity unit, unpaid balance are inputted by user.

SOLUTION
PROGRAM DATA REQUIREMENT
List of data required in this problem. There are three (3) categories of data.

Constants
RATELESS 0.218 /* rate of charge first 200 unit */
RATEMORE 0.334 /* rate of charge following unit */
PEN 0.015 /* penalty for unpaid balance */


Inputs
int unit /* unit of electricity used */
float UnpaidBal /* unpaid balance */


Outputs
float Penalty /* charge of penalty */
float UseCharge /* charge for the current electricity use */
float TotalBill /* total charge */


PROGRAM ALGORITHM (FLOW OF PROGRAM)
1. Display user instructions
2. Get data: unpaid balance and electricity unit used
3. Determine electricity unit used and compute use charge
4. Determine unpaid balance and compute penalty
5. Compute total charge
6. Display the total bill amount

DESIGN OF COMPUTATION OF USE CHARGE
The data required to compute the use charge are listed. We separate the involved data categories into Input, Process and Output.

Input Data
int unit /* unit of electricity used */

Process Data
RATELESS 0.218 /* rate of charge first 200 unit */
RATEMORE 0.334 /* rate of charge following unit */


Output Data
float UseCharge /* charge for the current electricity use */

Algorithm for Computation of Use Charge
We know that different rate will be used if the electricity unit used is more than 200. Thus we use if else selection to design the algorithm.
if unit > 200
compute use charge for more than 200 unit
else
compute use charge for less than 200 unit


Formula for Use Charge
UseCharge=(unit-200)*RATEMORE+200*RATELESS /* more than 200 */
UseCharge=unit*RATELESS /* less than 200 */


DESIGN OF COMPUTATION OF PENALTY
The data required to compute the penalty are listed. We separate the involved data categories into Input, Process and Output.

Input Data
float UnpaidBal /* unpaid balance */

Process Data
PEN 0.015 /* penalty for unpaid balance */

Output Data
float Penalty /* charge of penalty */

Algorithm for Computation of Penalty
Penalty is dealt when there is an unpaid balance. We use if selection to design the algorithm.
if unpaid balance > 0
compute penalty


Formula for Penalty
Penalty=PEN*UnpaidBal

DESIGN OF ELECTRICITY BILL LAYOUT
Displaying bill involves only input data (variables).

Input Data
float Penalty
float UnpaidBal
float UseCharge.

Algorithm for Displaying Bill
if unpaid balance > 0
compute penalty


IMPLEMENTATION
Begin by writing the #define directives for the constant data. In the main(), declare the input and output variables. Then start coding each program algorithm steps. Use printf() to display the user instruction/prompt and scanf() to read the user inputs (UnpaidBal and unit). Implement the computation of use charge and penalty using if else selection. Then, use relevant arithmetic operators to construct the formulas under their corresponding if else selection. Finally use comments in your program so as you won't get lost. Good luck and Happy Coding!