1 / 66

Starting C

Starting C. An introduction to programming in ANSI C This material is intended to get people started in writing C code in reasonable style It is intended to be cross-platform and not compiler-specific However there are a few slides about getting started in Visual Studio ( VC++ 6).

dwilks
Download Presentation

Starting C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Starting C • An introduction to programming in ANSI C • This material is intended to get people started in writing C code in reasonable style • It is intended to be cross-platform and not compiler-specific • However there are a few slides about getting started in Visual Studio ( VC++ 6)

  2. Software needed - a C compiler · Microsoft Visual C++ or MS Visual Studio or Watcom or CodeWarrior· Turbo C v.2.01, free from http://community.borland.com/museum/ (just 3 floppies, works in DOS)· Turbo C++ v. 4.5, free on a magazine CD-ROM ( Windows)The GNU C compiler, free from http://www.gnu.ai.mit.edu/software/gcc/ .This is a command line compiler which you may find tricky to set up and use to start with If you use Linux or another version of Unix, you will find you already have a C compiler, either installed or still on the CD.

  3. Books Computer Science A Structured Programming Approach Using C by Forouzan and Gilberg publishers Brooks/Cole The C Programming Language by Kernighan and Ritchie second edition published by Prentice Hall

  4. Using MS Visual C++ IDE - 1 • Start MS VC++ • Click File..New • 3. Set up the dialog box like this project name a console application where it is saved

  5. Using MS Visual C++ IDE - 2 • A wizard starts – choose ‘Empty Project’ • Click OK • 3. You will see this select FileView not ClassView

  6. Using MS Visual C++ IDE - 3 • From the menu, click Project.. Add to Project.. New.. • You will see this.. A filename ending in .c We are actually adding a C source code file

  7. Writing the program to run it

  8. /* A first program */ int main() { int x, y; x = 5; y = x + 7; return 0; } A first program

  9. /* a program with output */ #include <stdio.h> int main() { int x,y; x = 5; y = x + 7; printf(" y is %i \n ", y ); return 0; } Output

  10. 1. Enter the first program into an editor - /* a program with output */ #include <stdio.h> int main() { int x,y; x = 5; y = x + 7; printf(" y is %i \n ", y ); return 0; } Save it and compile it. Correct any syntax errors reported. Run the program. If you do not get the answer 12, fix it! 2. Write a program to work out the area of a rectangle. Have 3 integer variables, called width, length and area. Make the width 5 and the length 10. Calculate the area and use printf to output it. 3. Use printf to output a Christmas tree, like * *** ***** ******* *

  11. 1: int main() 2: { 00401010 push ebp 00401011mov ebp,esp 00401013sub esp,8 3: int x,y; 4: x = 5; 00401016mov dword ptr [x],5 5: y = x + 7; 0040101Dmov eax,dword ptr [x] 00401020add eax,7 00401023mov dword ptr [y],eax 6: return 0; 00401026xor eax,eax 7: } 00401028mov esp,ebp 0040102Apop ebp 0040102Bret What compilers do

  12. Integral data types #include <stdio.h> #include <limits.h> int main() { int i; short s; long x; printf("Biggest integer = %i\n",INT_MAX); /* get 32767 */ i = 255; x = 128000L; printf("i = %i and x = %li\n",i,x); /* get 255 and 128000 */ return 0; } • Variables must be one of a small set of data types. All data is represented internally as binary patterns, but different types are encoded into binary in different ways • The standard data type for an integer (whole number) is int • Often, an int is stored in 2 bytes = 16 bits. In that case, ints are restricted to the range ±32000 • but the range of all data types in C is implementation-dependent ie not defined by C - the opposite to Java • limits.h contains the ranges of these types and will contain different values in different versions • the type short is an integer which is uses the same or less memory than int • long uses at least as much as an int. Often long uses 4 bytes = 32 bits, giving a range of about ±2 500 000 000

  13. Floating point types #include <stdio.h> int main() { float f; double d; f = 1.23456789; printf("%f\n",f); d = 1.2345678912345; printf("%5.13f \n",d); f = 7 / 2; /* f becomes 3.0 */ f = 7.0 / 2.0; /* f becomes 3.5 */ } • Floating point numbers contain decimal parts • Floating point is less precise and slower than integer • The basic type is float which is often stored in 4 bytes • The most often used is double which is extended precision and greater range • Details of ranges and precision (implementation-dependent) is in <float.h> • The formatting sequence for a double or float in printf is %f. A form like %5.13f indicates the number of digits before and after the decimal point. %e gives scientific notation display. • 7 / 2 requests the division of 1 integer by another, so integer division is used, giving the result 3 • 7.0 / 2.0 divides one float constant by another, so floating point division is used, and 3.5 is the result

  14. Arithmetic operators • The arithmetic operators are + - * / and %, which is the remainder eg 11 % 9 = 2. • Each has a precedence level so that BODMAS works and brackets may be needed eg 4 * 2 + 2 is 14, 4 * ( 3 + 2) is 20 • There are floating point and integer versions of these, depending on the types of the operands.eg 7 / 3 gives 2 • For expressions with more than one type, values are converted to the ‘biggest’ typeeg in 3.5 + 7, the 7 is converted to 7.0 and floating point addition is used. • = is also an operator, and the value is the right hand side - for example x = 7; does 2 things - it makes x to be 7 (a side-effect), and it produces a value of 7. • So you can say for example y = x = 7; Set 1-2

  15. 1. Write a program which calculates and outputs the circumference ( 2 r ) and area ( r2 ) of a circle. Use a variable called radius of type double. Take  as 3.1416. Test your program works. 2. Write a program which calculates the average of 3 numbers. Use double type variables called x1, x2 and x3 as the three numbers. Check it works.

  16. Type casting • An expression of one data type can be assigned to a variable of another type • such asint x;long lo;x = 3;lo = x; • This is called a type cast • Casting a value to a ‘bigger’ type, such as char to int, or float to double, produces no data loss - but the reverse potentially can • The example above is an implicit cast - it is up to the compiler to identify that a cast is needed, and provide the code to do it • An explicit cast is like thislo = (long) x;where (long) tells the compiler to convert the type to long • Implicit casts are bad practice - they imply that the programmer is unaware of the type of the data involved • Compiler settings should be such as to generate warnings on implicit casts - then the programmer can write explicit casts where appropriate

  17. if ( x > y ) { x=7; y = 55; } else { y = 9+x; printf(“Hello”); } Conditional - if • The idea is that the machine evaluates an expression and takes different actions depending on whether the result is true or false • Note the round brackets around the condition • The { and } form a block of statements to do. If there is only one statement, they are not needed. • The else part can be missed out if it is not needed. • A value of 0 is 'false', while any non-zero value is 'true' - see later • the relational and logical operators can be used, so that if ( ( x == 4 ) || ( y < x + 7 ) ) ..means if x is 4, or y is less than x+7, do something..

  18. Input - scanf • This is run-time input of data, normally from the keyboard • For example int i; scanf("%i", &i);execution pauses at the scanf, and waits for the user to type in a value for i • Note the &, the address operator, in front of the variable scanf is prototyped in stdio.h • scanf is not usually used in real programs (not even DOS ones) because of the difficulty with validation. In other words if the user does not type in a valid value - its too late.. but scanf is OK for initial teaching programs

  19. 1. Write a program to work out the area of a rectangle, using scanf to input data at run-time. Have 3 integer variables, called width, length and area. Calculate the area and use printf to output it. Can you find data to enter which you crash the program? 2. Write a tax calculator, which inputs a person's salary then outputs the tax, calculated by the following - if they earn less than £10 000, the tax is zero over £10 000, they pay tax at 20% 3. Write some code to input a person's age and validate it. If the age is less than 0 or more than 120, output a message 'Age invalid' - otherwise output 'Age OK'.

  20. Increment, decrement and assignment operators • The need to increase a variable by 1 is so common there is an increment operator - for example x++; is the same as x = x + 1 ; • Similarly there is a decrement operatorx--; is the same as x = x - 1 ; • For both these, there are pre and post versions. For example, post-increment - y = x++; first makes y equal to x, then increases x by 1 - • but pre-increment y = ++x; first increases x by one, then makes y equal this new value of x • Assignment operators are short-hand. For example += x = 7; x += 9; same as x = x + 9 - so x becomes 16 • More examples -

  21. Expressions and statements • An expression is something which has a value. For example assuming the variables have been declared and given values, all of the following are expressions - • 2 + 2 • 5 * x + 4 • 4 + ( y + 3 ) / ( x + 2 ) • sin( 3 * x ) /* sin is a function prototyped in math. h */ • 38 • x = 4 /* remember = is an operator with a side-effect */ • x++ /* post-increment, side-effect, value is the initial value of x */ • An expression becomes a statement if it is followed by a ; • So x + 2; is a syntactically valid statement in C - but a good compiler would warn you that 'code has no effect' • maybe you meant to type x = 2; especially since + and = are on the same key!!!

  22. 1. Look at this piece of code - int a, b, c; a = 4; b = ++a; c = a++; b *= a; c -= 3; What should be the values of a b and c after this? Work it out on paper, then write a program to check. 2. Classify each of the following as an expression, a statement, or as invalid - 1 + 1 x = 3; x + 2 1 + 1; x++ x++; a = b = c; x++2; 2++

  23. if - again • remember 0 is ‘false’, and any non-zero value is ‘true’ • programmers often use this to compress code • egx = 3 * y + 5;if ( x == 0 )…… • would probably be coded asif ( ! ( x = 3 * y + 5 )) …. • this uses the side-effect of = to execute the assignment • and the value is the value of x • if x is 0, !x is 1, which is true, so the if is triggered • bug number 1..y = ….something...;x = y;if (x=0)…..many compilers will warn this

  24. conditional - switch switch (x) { 1: ….. …… break; 2: …. ….. break; default: …. … } • suppose you want to execute various alternative blocks of code, depending on the value of a variable - • you might writeif (x==1) …..else if (x==2) …..else if (x==3) ….. • the switch construct caters for this • switch (x) { 1: ….. …… 2: …. ….. 3: ….. ... default: …. … } • but.. • the 1, 2 ,3 etc must be constant integral expressions • when one case triggers, it falls through all other cases • so the usual form is..

  25. conditional - the ternary operator • if you want to get one value if an expression is something, and an alternative if it is not.. • such asif ( x > 38 ) y = 47;else y = 32; • it is faster to writey = ( x > 38) ? 47 : 38 ; • which is likey is.. is x >38? if so, 47, else 38 Set 1-5

  26. /* char */ #include <stdio.h> int main() { char c; c = 'a'; printf("c = %c or %i\n",c,c); /* a or 97 */ c = 'b'; c = c + 2; printf("c = %c\n",c); /* gives d */ return 0; } char is to be thought of as a character, or as a small integer Traditionally, characters are represented in a machine by codes which are 1 byte long. Most PCs use the ASCII code system, in which A is 65, B is 66, C is 67,.. a is 97, b is 98,.. 0 is 48, 1 is 49, a SPACE is 32 and so on. There are other character codes which are 1 byte long, such as EBCDIC A char variable can be assigned a value like 'a' single quotes 'like' and NOT "double quotes", which delimit strings A char can be displayed using the %c formatting sequence in printf Since chars are small integers, you can do arithmetic with them, like c = c + 2 char type

  27. 1. Use switch to write a simple calculator which would run as follows (sample user input is in italics ) - Input first number: 2 Input second: 3 Choose operation ( + - * or /): + Result = 5 Use scanf for input, and a char variable for the operation. Note : if you try to input the char using scanf("%c",&c); it picks up the previous carraige return – so say scanf(" %c",&c); // space before %c skips over CR

  28. loops - do..while • use a loop if some process is to be repeated • there are 3 basic loop structures in C • the do while structure repeatedly executes a block of code so long as some condition is true • for example to output the numbers 1 to 10.. • x = 1; do { printf(“%i \n”, x); x++; }while (x<11); • or.. x = 1; do printf(“%i \n”, x++);while (x<11);

  29. loops - while • a do..while loop will always execute the loop body at least once, since the condition is checked at the end. Sometimes this is inappropriate eg to delete all files in a directory and the directory is empty • an alternative loop checks the condition at the start • for example to output the numbers 1 to 10..x = 1; while (x<11) { printf(“%i \n”, x); x++; } • or, to output 10 to 1.. x = 11;while (--x) printf("%i \n",x);

  30. Loop templates Task: Output a message 10 times This kind of process just needs an ‘index variable’ which is used to count the number of times the loop should repeat

  31. In C: #include <stdio.h> int main() { int counter; counter = 0; while (counter<10) { printf(“Hello\n”); counter++; } return 0; } Loop Template 1 In pseudo-code initialise counter to 0 while ( counter < 10 ) output message increase counter by 1

  32. Loop template 2 • Task: • Add up the integers from 1 to 100 • There are 2 aspects to this – • Go through the numbers 1 to 100 • Add them up • We need a counter variable to represent the 1 to 100 • and another which is the “running total”

  33. In C #include <stdio.h> int main() { int counter, total; counter = 1; total = 0; while (counter<101) { total += counter; counter++; } printf("Total = %d\n",total); return 0; } Loop template 2 Pseudo-code plan – Initialise counter to 1 Initialise total to 0 while ( counter < ?? ) add counter into total add 1 to counter

  34. Loop template 3 Task Input integers from the keyboard, until a rogue value of –99 is entered Output the average Thoughts – Input using scanf – need a ‘number’ variable We have to add up the numbers – we need a total variable We don’t know (at ‘compile time’) how many times we will loop We have to count them – we need a counter variable We must avoid adding in and counting the -99

  35. #include <stdio.h> int main() { int counter, total, number; double average; counter = 0; total = 0; scanf("%d",&number); while (number!= -99) { total += number; counter++; scanf("%d",&number); } average = (double)total / (double) counter; printf("Average = %lf\n",average); return 0; } Loop template 3 Pseudo-code Initialise total to 0 Initialise counter to 0 Input number while ( number not –99 ) Add number to total Increment counter Input number average = total / counter Output average

  36. 1. Here is a program which outputs the integers 1 to 5 - #include <stdio.h> int main() { int stepper; stepper = 1; while (stepper<6) { printf("%d ",stepper); stepper++; } return 0;  } We will use this as a basis for several more programs. Type it in and run it.  2. Change the program so it outputs integers from 1 to 99 (inclusive). 3. Change it so it outputs from -99 up to 99. 4. Change it so it goes up in steps of 2 ( so you get -99 -97 -95........97 99 ). 5. Change it so it starts at 100 and goes down to 1.

  37. 1. Use a do-while loop to output the even numbers from 2 to 100 inclusive. 2. Input an integer then output 'Hello' that number of times. Include the possibility of 0 iterations. 3. Use a loop to output the sequence 3, 6, 9, 12,..300 4. Add up the integers from 1 to 100. 5. The user inputs a sequence of integers, terminated by a 'rogue value' of -99. Add up the sequence and output the result - Sample input 1, 2, 3, -99 Output 6

  38. An array is a set of data values – not just one Think of an array as a row of boxes Each box is an element The elements have an index – a label for which box is which Arrays array of 10 integers The 10 elements 7 13 42 4 17 22 7 66 3 9 0 1 2 3 4 5 6 7 8 9 index of each element

  39. Arrays • An array is a data structure – a way of arranging a set of data items • An array is a set of numbered boxes, each box holding a value • an array marks[20] could hold the exam marks of 20 students • This would be declared asint marks[20]; < must use square brackets • The boxes are numbered 0 to 19 • Some examples aremarks[0] = 35; store 35 into the first boxmarks[9] = 48; store 48 into the 10th. boxx = marks[0] + marks[1]; add up first 2 boxesk = 34;marks[k] = 17; put 17 into 35th. Boxmarks[20] = 23; !! Array bounds error !!

  40. Arrays and loops • To process arrays loops are often used to go through the different elements • For example, this would declare an array, read values in from the keyboard, then print them out again..int index = 0;int numbers[5];while ( index < 5 ){ printf("Enter a number.."); scanf("%i", &numbers[index]);index++;}index = 0;while ( index < 5 ){printf(“ %i %i \n ", index, numbers[ index ] ); index++; }

  41. Arrays - count zeros Suppose we have an array called numbers, containing 5 integers, and we want to count how many zeros there are - zeroCount = 0; index = 0; while ( index < 5 ) { if ( numbers [ index] == 0 ) zeroCount++; index++; }

  42. Arrays - find largest element biggest = 0; index = 0; while ( index < 5 ) { if ( numbers [ index] > biggest ) biggest = numbers[index]; index++; }

  43. Arrays - find total total = 0;index = 0; while (index < 5 ) total = total + numbers[index++];

  44. Arrays of char • Strings in C are stored as sequences of character codes, and are terminated by a 0 - ASCIIZ • so “ABC” is stored in 4 bytes, with values 65 66 67 0 • this can be done using arrays egchar word[4] = “ABC”; • orchar word[4];word[0]=‘A’;word[1]=‘B’;word[2]=‘C’;word[3]=‘\0’; not word[3]=‘0’; • orchar word[] = “a longer string”; • the problem with this is an array is fixed in length, so you can’t store longer strings in the array. Consequently pointers to chars are more often used..

  45. 1. Fill an array with 5 random integers ( use the function rand() from stdlib.h ). Print them out, together with the average of the 5 numbers. 2. Fill an array with 50 random integers. Print them out, then reverse them, and print them out again

  46. for loops 2 kinds of C loops – while( ) and do..while( ) The 3rd and last kind is a for loop It looks like – for (…………..) { .. .. } There are 3 parts in this bracket This is the loop body – the statements to repeat

  47. for loops Initialise change at the end of each repeat for ( x=0 ; x<5 ; x++ ) { .. .. } loop repeats so long as this is true so this loops with x having the values 0 1 2 3 and 4

  48. for loop – output 1 to 100 (nearly) .. int x; .. for ( x = 0; x < 100; x++) printf(“%d\n”, x);

  49. for loop – counting down .. int x; .. for ( x = 100; x > 0; x = x - 2) printf(“%d\n”, x);

  50. for loop – totalling an array int data[100] int index, total = 0; .. for ( index = 0; index < 100; index++ ) total = total + data[index];

More Related