1k likes | 1.21k Views
First Program. Fundamentals. Fundamentals. Compilation and Execution Simplifying Fractions Loops If Statements Writing functions Variables Operations Using Functions Errors. Running a C Program. A C program consists of a series of instructions written in C
E N D
First Program Fundamentals
Fundamentals • Compilation and Execution • Simplifying Fractions • Loops • If Statements • Writing functions • Variables • Operations • Using Functions • Errors
Running a C Program • A C program consists of a series of instructions written in C • Usually broken down into a number of functions • And often in different files • A C program needs to be translated into something that a computer can understand • This process is called compiling • A compiler translates high-level language code into machine code
Processing a C Project run-time errors Debugged Executable Source File (.c) write in a text editor correct errors compile test linker links files Object File (binary) syntax errors link errors Other Object Files Executable File (binary)
Command Line Compilation • Most OSs include C compilers and allow a program to be compiled and run • To compile and run a program in Linux follow these steps • Write the program using a text editor • Compile the program using the gcc compiler • Run the program created by compilation by typing its name
Linux Compilation Example • Assume that we’ve made a C file named test.c • Open a Terminal window in Linux • At the command prompt type • gcc –o test test.c • The –o switch tells the compiler to name the object file that is being created test • test.c is the name of the file to be compiled • To run the newly created file type • ./test
Errors • In reality if we’ve just finished writing our first C file it will fail to compile • Because it contains compilation errors • That is, mistakes in C syntax • The compiler will print a list of errors • That we can then fix • More on this later ...
IDEs • An alternative to using the Terminal to compile programs is to use an IDE • Integrated Development Environment • An IDE combines a text editor, a compiler, a debugger and (many) other tools • There are many IDEs • Visual Studio (Windows) • Code::Blocks (cross-platform) • Xcode (Mac OS) • Eclipse
Simplifying Fractions • Assume we want to simplify fractions • 4/16 = • 1/4 • 105/135 = • 7/9 • To simplify a fraction • Find the greatest common divisor (gcd) of the numerator and denominator • And divide numerator and denominator by gcd
Requirements • Saying that "we want to simplify fractions" is a somewhat vague problem description • We'll clean up the requirements of the program later but let's start with a very specific problem • Write a program to simplify 105/135 • Steps • Find the gcd of 105 and 135 • Which I'll refer to as gcd(105,135) • Print 105/gcd(105, 135) a "/" and 135/gcd(105,135)
Solution /* * Program to simplify a specific fraction * Author: John Edgar * Date: December 2012 */ #include "stdio.h" int main() { inta = 105; intb = 135; // Compute GCD of 105 and 135 using Euclid's algorithm while(a != b){ if(a > b){ a = a-b; }else{ b = b-a; } } printf("%d/%d\n", 105/a, 135/a); // print result return 0; }
Discussion • The program has a number of sections • Introductory comments • That describe the program • An include statement • That imports library functions • A main function • That actually does the work • The main function includes an implementation of Euclid's algorithm (the while statement)
Comments • Comments document programs • They explain what a program does • And how it works • They are ignored by the compiler • A comment starts with /* and ends with */ • And may include more than one line • Writing comments is an important part of writing a maintainable program • And you will lose marks if you don’t write comments in assignments ... /* Program to simplify a fraction Author: John Edgar Date: August 2011 */
More Comments • There are two ways of writing comments in C • Starting with /* and ending with */ • Or single line comments that start with // and continue to the end of the line • These are C++ style comments which can be used with any recent C compiler • Either method of commenting is acceptable • The // style is particularly useful for single line comments
#include stdio.h • The include statement is a pre-processor directive • The pre-processor operates before the compiler • #include tells the pre-processor to include the contents of stdio.h in our program • Opens the stdio.h file • Copies its contents • Pastes it, replacing the include directive
What’s in stdio? • The stdio.h file contains function(s) that our program need • For this program it is the printf function • Which prints text • stdio.h contains input and output functions • Standard input and output • Programs will frequently need functions from library files
Main • C programs have one main function that executes when the program is run • This function has to be named main • We will write (lots of) other functions that we will give different names to • The main function always has the same general form
Skeleton of Main the return type of the function int main() { /* stuff you want to happen */ return 0; } the function’s parameter list (empty) the name of the function, main in this case semi-colon, you’ll see lots of these return statement, more on this later opening and closing curly brackets
Program Flow • Programs are composed of a series of lines separated by semi-colons • Although not all lines end with ;s • When main executes it starts with the first line and ends when it reaches the return statement • Any line after the return statement will not be executed • Other control statements may change program flow to allow loops or branching
Semi-Colons • Semi-colons show the end of C commands • Most C statements are written on one line • However, the newline character does not indicate the end of a command • Don't forget semi-colons • As the program won't compile without them • Generally, you need a semi-colon after each expression that does not start or end with { or }
Variables • The simplify program uses two variables • Variables are used to store data • Values stored in variables can be changed using the assignment operator, = • Both variables have the same type • The type specifies what kind of data is stored • Both a and b are type int - used to store whole numbers • A variable's type is specified when it is declared • Thereafter variables are just referred to name inta = 105; intb = 135;
Declaring Variables identifiers (names) int a, b; type list of integer variables, separated by commas or int a = 213; declaration and initialization Note that it is important to give variables meaningful names. The names a and b are used here because Euclid's algorithm finds the gcd of two arbitrary integers.
Operations on Data • Simplify includes operations on integer data • Subtraction and division • Assignment • An operation requires an operator and at least one operand • a = a – b; assignment is a binary operation since there are two operands, one on the left and one on the right left operand operator right operand? the right operand is the result of a-b note that this one statement contains two binary operations with a distinct order
While Loops • Loops are constructs that perform repetition • That is they repeat code inside the body of the loop until some condition is met • If the condition cannot be met the loop will continue running forever (an infinite loop) • In the simplify program the loop continues to run as long as a and b have different values • The code that is repeated is contained within {}s that come after the condition
While Loop Anatomy keyword (while) and condition while(a != b) { if(a > b){ a = a-b; }else{ b = b-a; } } the condition (a is not equal to b) evaluates to true or false the body of the loop is repeatedly executed until the condition is false the condition compares values stored in the integer variables
While General Form while(condition) { //loop body } the condition is a comparison that evaluates to true or false conditions can be more complex and may not involve comparisons the loop body consists of the statements that to be repeated the condition is tested before each iteration of the loop if it is false the program continues after the loop body's closing bracket
If Statements • If statements are constructs that allow decisions to be made • One set of statements is performed if the condition is true • Another set of statements is performed if the condition is false • Unlike loops, if statements do not perform repetition • One set of statements is performed and the program continues from the end of the if statement
Conditions • Both while loops and if statements use conditions • A condition is a Boolean expression that evaluates to true or false • Boolean expressions compare two values with a comparison operator • One of <, <=, >, >=, == (equal to), != (not equal to) • More complex conditions are possible and these will be discussed later in the course
If Statement Anatomy keyword (if) and condition if(a > b) { a = a-b; }else{ b = b-a; } the condition (a > b) is true if a is greater than b and false otherwise executed if a is greater than b keyword else, i.e. otherwise ... executed if a is not greater than b if statements are not required to have an else clause
Printing Data • The last line prints the result using the printf function • The printf function must be given the text that you want it to print • Text is written as a double-quoted string • e.g. printf("hello world"); • A string is a sequence of characters • Strings can be of any length • And must be enclosed in ""s printf("%d/%d\n", 105/a, 135/a);
Function Arguments • Many functions need input • Data passed to a function are referred to as arguments • The number and type of arguments must match what is expected by the function • Failing to give appropriate arguments results in a compilation error • The printf function usually has a string as an argument but often also takes other arguments
printf and Format Specifications printf("%d/%d\n", 105/a, 135/a); int values format specifications, % and a letter each %d represents an integer and must be matched by an integer argument that follows the string function arguments are separated by commas
Format – Colour • A text editor designed for use with C colours words to aid readers • Different text editors use different colours • The Linux text editor uses different colours from those presented in this presentation • It is common to colour the following • Keywords (blue in presentation) • Strings, i.e. words enclosed by ""s (red) • Comments (green)
Format – Indentation • Indentation is used to indicate flow of control • Everything in the main function is indented underneath main • The body of the while loop is indented under the while statement • Indentation helps the reader, not the compiler • While indentation is ignored by the compiler it is still very important • Our goal is not just to produce programs that work but to produce programs that are easy to maintain • And therefore easy for people to understand
Colours and Indentation /* * Program to simplify a specific fraction * Author: John Edgar * Date: December 2012 */ #include "stdio.h" int main() { inta = 105; intb = 135; // Compute GCD of 105 and 135 using Euclid's algorithm while(a != b){ if(a > b){ a = a-b; }else{ b = b-a; } } printf("%d/%d\n", 105/a, 135/a); // print result return 0; } comments strings keywords indentation
Simpilfy – the Bad Version And here is the same program with no colour or indentation #include "stdio.h"int main(){int a, b;a = 105;b = 135;while(a != b) {if(a > b){a = a-b;}else{b = b-a;}}printf("%d/%d\n", 105/a, 135/a); return 0;} This program compiles and runs but is very difficult to read Important note – if the above program was submitted as a solution to an assignment it would lose a lot of marks, even though it works There is a lot more to writing a good program than producing something that works
Why isn't this program very good? • It only simplifies one fraction • It would be better if the user was asked what fraction should be simplified • Then it could simplify any fraction! • It isn't modular • The calculation of gcd is potentially useful for other purposes • It would be better to separate it from the rest of the program
Improving the Simplify Program • Get user input for the numerator and denominator of the fraction • Put the gcd calculation in a function • We could make other improvements • Which will be discussed later
Functions • The first version of simplify includes two functions • The main function • A call to (use of) the printf function • In addition to main and library functions we can write our own functions • And use them in our programs • It is good design to break a program down into many small functions
GCD Function Definition intgcd(int a, int b) { while(a != b){ if(a > b){ a = a-b; } else{ b = b-a; } } return a; } function header return type, name, parameter list this function needs 2 integers for input and produces a result that is also an integer – its return value exactly the same as the original version
Simplify with GCD Function #include "stdio.h" intgcd(int a, int b) { while(a != b){ if(a > b){ a = a-b; } else{ b = b-a; } } return a; } int main() { int numerator, denominator, divisor; numerator = 105; denominator = 135; divisor = gcd(numerator, denominator); printf("%d/%d\n", numerator/divisor, denominator/divisor); return 0; } the main function is much cleaner the variable names in main have been made more meaningful
User Input only the main function is shown intmain() { int numerator, denominator, divisor; printf("Enter the numerator: "); scanf("%d", &numerator); printf("Enter the denominator: "); scanf("%d", &denominator); divisor = gcd(numerator, denominator); printf("%d/%d = ", numerator, denominator); printf("%d/%d\n", numerator/divisor, denominator/divisor); return 0; } scanf gets keyboard input specifies int variable to store input in, preceded by an & this program will simplify any fraction
Further Improvements • Let’s assume we wanted to perform other fraction related tasks • Such as arithmetic • If so, simplifying fractions is likely to be part of other calculations • The program could be made more useful by creating two more functions • A function to simplify a fraction and return a result • A function to print fractions
Declaring Variables type identifier (name) declares a variable of type int int age; ... age = 23; ... age = age + 1; stores the value 23 in age this compound statement actually does three things: retrieves the value stored in age (23) calculates the sum of 23 and 1 (24) stores 24 in age
Rules for Declaring Variables • A variable is declared only once • Variables must be declared before they are used • By convention variables are declared at the start of a function before other statements • This was required by older C compilers • Variables may be declared in a list • Variables may be assigned a value when declared • Known as initialization
Variable Lists and Initialization declaration and initialization int days = 213; int hours, minutes, seconds; list of integer variables, separated by commas
Duplicating Names • Declaring a variable reserves space for the variable’s data in main memory • A variable can only be declared once • Repeating a declaration is an attempt to declare a new variable with the same name • Which is illegal • Variables with the same name are allowed as long as their scope is different
Initializing Variables • Variables should be initialized before first being used • That is, given sensible starting values • This can be done at the same time as they are declared • Forgetting to initialize variables can result in unexpected and unwanted results • Note that a memory location can never be empty • Since it is a sequence of bits