Objective of this lecture: At the end of this lecture you should be able to have a basic overview of fundamental structures in C and be ready to go into details. Fundamental Programming Structures in C We will briefly tour the fundamental programming structures in C. This lecture is a summary and each subject covered in these notes will be discussed at length throughout the course. Data Types The following are the data types defined in C: char: a single byte that holds one character (A byte is defined as an 8-bit storage unit. One bit could be either 0 or 1. One bit is the smallest storage unit on a computer.) int: an integer number. Size depends on the machine. Typically, it is 4 bytes. float: single-precision floating number. Size depends on the machine. double: double-precision floating number. Size depends on the machine. There are also short int and long int defined for small and large integer numbers, respectively. Variables The C programming language requires you to declare the type of each variable you use. First, the type is placed, then the name of the variable is placed. A semi-column terminates the declaration. For instance: int i; double x; char ch; The first one above declares an integer, the second one declares a double-precision floating point number, and the last one declares a single byte. Note on style: Make it a habit to declare meaningful variable names, even if they end up being long. If a variable name has more than one word in it, my convention is to have the first letter of the first word lowercase and the first letter of next word uppercase. For instance, do not just declare int f; for, say, gravitational force, rather use int gravitationalforce. This style would make your programs more readable by others, and even by yourself, when you need to revisit a program you had written a long while ago.
Assignments After you declare variables, you need to explicitly assign values to them by means of an assignment statement. Never leave a variable un-initialized. An un-initialized variable in C could have any random value and can adversely impact the flow of your programs. Here is a declaration: int i; And here is an initialization: i = 10; Operators Usual arithmetic operators +, -,, and / are used for addition, subtraction, multiplication, and division. The / operator is for integer division if both operators are integers. Note that 3 / 7 would, for instance, produce 0. The % operator is for modular arithmetic. x % y would yield the remainder of division of x by y. The C language allows for shortcuts in arithmetic expressions. For instance, instead of you can write i = i + 2; i += 2; Also, incrementing an integer by 1 (i = i +1) can be expressed as i++ or ++i. Similarly, decrementing an integer could be expressed as i-- or --i. The difference between i++ and ++i is the fact that in a given expression i++ will be evaluated after the value of i is used. In the case of --i, first i will be decremented, then its value will be used. The operator == (double equal sign) is the comparison operator. For instance, a == b will evaluate to true, if a is the same as b. On the other hand, the operator!= is the inequality check. For instance, a!=b will evaluate to true if a is not the same as b. Finally, C has the comparison operators like < (less than), <= (less than or equal to), > (more than), and >= (more than or equal to). The operator && is the logical AND operator and is the logical OR operator. For instance, (a == b && c <= d) will evaluate to true if both a equals b and c is smaller
than or equal to d. Similarly, (a==b c <=d) will evaluate to true if either a is equal to b or c is smaller than or equal to d. Caution: One common mistake is to use the assignment operator = in place of equality operator ==. Some compilers detect that and some others may not be as clever. When working with integer types, one can also deal with bitwise operators: & (and), (or), ^ (xor), and ~ (not). We will discuss these at length later in the course. Control Flow The C programming language has many constructs to impact the flow of execution path in a program. We will discuss conditional statements, indeterminate loops, determinate loops, and the switch statement. Conditional statements The simplest conditional statement in C is the if-statement: if (condition is true) statement1; statement2; statementn; What this statement allows one to do is to execute a set of statements if a particular condition holds true. For instance, let s assume you are trying to get cash from your bank account at an ATM machine, your balance is N YTL and the amount you want to get is K YTL. The software in the ATM machine might be running a conditional statement as if ( K <= N) Allow the operation. The amount asked will be be reduced from the account s balance. N = N K; The more general if-statement typically has an else-block as follows: if (condition is true)
else statement_a1; statement_a2; statement_an; statement_b1; statement_bn; Definition: A block is a statement enclosed within a left and a right curly bracket. The if-statement above has two blocks, one that gets executed if the condition is true and the other gets executed if the condition is false. The scope of a variable is a block. In other words, if you define a variable, say x, in a block, it will not be recognized outside that block. (We will talk about this later too.) To give an example of the general if-statement, let s consider the bank example again. What if you do not have enough cash in your bank account? Well, in our example we will simply print out an error message. See below. if ( K <= N) Allow the operation. The amount asked will be be reduced from the account s balance. N = N K; else Do not allow the transaction. printf( Not enough cash in your account! ); Note that in this example the condition is (K <= N) which evaluates to true or false. The if-statement can be nested with multiple conditions as follows: If (condition-1) block_1;
else if (condition-2) block_2; else if (condition-n) block_n else block_n+1; An example is determining letter grades based on numerical total grade as follows: if (totalgrade >= 90) lettergrade = AA ; else if (totalgrade >=85 && totalgrade < 90) lettergrade = BA ; else if (totalgrade >=80 && totalgrade < 85) lettergrade = BB and so forth. The && sign is the logical AND operation. Remember that both operands should evaluate to true, for the condition in else-if statements to evaluate to true. Suggested exercise: Convert the code piece above to a C program such that given a total numerical grade on the command-line, your program will print the letter grade. You can use the our University s rules to determine the letter grade. Indeterminate Loops In C there are control structures that allow you to repeat statements. There are two types of repeating loops: determinate ones that you would use if you know exactly how many times you will be looping and indeterminate ones that you would use if you do not know
exactly how many times the loop should run. The example for the former is the for-loop that we had seen earlier. For the latter C has two types of while loops, one that allows the execution of the block only if a given condition is true and another that would allow the execution of the block at least once, and then, only if the condition is true. The general form of the first type of indeterminate loop is while (condition) statement1; statementn; Note that this while loop allows execution of the block zero or more times. Here is an example: consider calculating the retirement savings of a person who would contribute a specific amount of money to his/her account every year, has a specific goal for retirement sum, and an interest rate value is given. Question is, can you calculate the number of years that will be required to save the target retirement amount? See Listing 3 below for the program. It is available in my hbar account. Note that the while-loop runs until the number of years is calculated for the target retirement savings. See if you can follow this program. Variable names are chosen explicit enough for this program to be readable easily. The only new function introduced here is atof(), which converts a given string to a floating point number. #include <stdio.h> #include <stdlib.h> This program calculates the number of years that a person needs to save a specific amount of money by contributing a fixed amount every year. A constant interest rate is given. Run it as retirement target contribution interest where target is the targeted savings, contribution is the amount contributed every year, and interest is the interest rate. Author: Yuksel Gunal int main(int argc, char argv) double target; double contribution; double interest; int years;
This is the running balance as years go by. double balance; Get the variables from command line. target = atof(argv[1]); contribution = atof(argv[2]); interest = atof(argv[3]); years = 0; while (balance < target) balance = (balance + contribution) (1 + interest / 100); years = years + 1; printf("it will take %d years to save %f YTL.\n", years, target); return (0); Listing 3. Estimating the number of years it will take person to save a specific amount of money by contributing a fixed amount to his/her bank account every year. The while loop that allows execution at least once has the following form: do statement1; statementn; while (condition); Here is an example. Consider generating random numbers until you hit a number between 0.9 and 1.0: do randomnumber= (1.0 rand()) / RAND_MAX; while (randomnumber < 0.9);
rand() is a C library function that generates a random number between 0 and RAND_MAX. RAND_MAX is defined in C standard library as the maximum possible random number. We do the division in order to produce a number between 0 and 1. The do-while flow above will run until a random number between 0.9 and 1.0 is generated. In order to achieve this task, the random number should be generated at least once, so we use the do-while block. Listing 4 below has a more sophisticated example. In a do-while loop we estimate the square root of a given number. The source code is available under my account at hbar as usual. See if you can follow what this program does. Variables name are chosen long enough to imply what they stand for. #include <stdio.h> #include <stdlib.h> This program calculates the square root of a number given on command line. Run it as squareroot N where squareroot is the executable name and N is the number, the square root of which we will calculate. Author: Yuksel Gunal int main(int argc, char argv) double number; double squarerootofnumber; double newsquarerootestimate; double oldsquarerootestimate; double accuracyofsquarerootestimate = 0.0001; Get the number from command line number = atof(argv[1]); newsquarerootestimate = number / 2; do Iterate until the the last two estimates differ by 0.0001. oldsquarerootestimate = newsquarerootestimate; newsquarerootestimate = (oldsquarerootestimate + number / oldsquarerootestimate) / 2;
printf("the new estimate of square root of %f is %f \n", number, newsquarerootestimate); while (abs(oldsquarerootestimate - newsquarerootestimate) > accuracyofsquarerootestimate); squarerootofnumber = newsquarerootestimate; printf("the estimated square root of %f is %f", number, squarerootofnumber); return (0); Listing 4. A simple estimation of square root using do-while loop. Determinate Loops When one knows the number of times a particular set of statements will be executed, then one could use the for-loop, which has the following form: for(statement1; expression1; expression2) block; We have already seen an example of this kind of loop in the factorial program (see Listing 1). Note that this loop is equivalent to the following while-loop: statement1; while (expression1) block; expression2; Multiple selections the switch statement Controlling flow by multiple if/else statements could be cumbersome. An alternative is to use the switch statement in which one could define different blocks based on various integer or character values of a variable. An example is as follows: switch (choice) case 1: break; case 2:
break; case N: break; default:. break; Things to note: Depending on the value of choice, a block of statements will be executed After each block of statements defined for each case one needs to use the break statement, otherwise statements until the next break will also get executed. If listed cases do not correspond to a value of choice, then the statements under default will be executed. The switch statement only works with integer-valued expressions or constant expressions. Arrays An array in C is a collection of items of the same type. For instance, a program might need to represent the names and grades of all students taking this class. Names of students could be represented in an array of strings and numerical grades of students could be represented in an integer array. Let s consider the case of the numerical grades; this array of integer values could be declared as: int grade[n]; where N will be the number of students in class. An element of this array is referenced as grade[i] where i could be a number starting from 0 to N-1. (A common problem in C is to reference an array element by using an index i which is outside the range of 0 to N-1.) We will discuss arrays in detail later in this course.