Download presentation
Presentation is loading. Please wait.
Published byJudith Lane Modified over 9 years ago
1
Introduction to C Creating your first C program
2
Writing C Programs The programmer uses a text editor to create or modify files containing C code. C code is also called source code A file containing source code is called a source file After a source file has been created, the programmer must invoke the C compiler.
3
Invoking the Compiler Example gcc pgm.c where pgm.c is the source file that contains a program
4
The Result : a.out If there are no errors in pgm.c, this command produces an executable file, one that can be run or executed. Both the cc and the gcc compilers name the executable file a.out To execute the program, type./a.out at the Unix prompt. Although we call this “compiling a program”, what actually happens is more complicated.
5
3 Stages of Compilation 1Preprocessor - modifies the source code Handles preprocessor directives Strips comments and whitespace from the code
6
3 Stages of Compilation 2Compiler - translates the modified source code into object code Parser - checks for errors Code Generator - makes the object code Optimizer - may change the code to be more efficient
7
3 Stages of Compilation 3Linker - combines the object code of our program with other object code to produce the executable file. The other object code can come from: The Run-Time Library - a collection of object code with an index so that the linker can find the appropriate code. other object files other libraries
8
Compilation Diagram Editor Compiler Preprocessor Parser Code Generator Optimizer Linker < Source File myprog.c Object File myprog.o Other Obj’s Run-time library Other libraries Executable file a.out
9
An algorithm for writing code Write the algorithm Write the code using vi (pico, emacs) Try to compile the code While there are still syntax errors Fix errors Try to compile the code Test the program Fix any semantic errors Compile the code Test the program
10
Incremental Approach to Writing Code Tips about writing code. Write your code in incomplete but working pieces. For instance: For your project Don’t write the whole program at once. Just write enough that you display the prompt to the user on the screen. Get that part working first. Next write the part that gets the value from the user, and then just print it out.
11
Incremental Approach to Writing Code (continued) Get that working. Next change the code so that you use the value in a calculation and print out the answer. Get that working. Make program modifications: ○ perhaps additional instructions to the user ○ a displayed program description for the user ○ add more comments. Get the final version working.
12
Structure of a ‘C’ program pre-processor directives global declarations function prototypes main() { local variables to function main ; statements associated with function main ; } f1() { local variables to function 1 ; statements associated with function 1 ; } f2() { local variables to function f2 ; statements associated with function 2 ; }.
13
A Simple C Program /* Filename: hello.c Author: Brian Kernighan & Dennis Ritchie Date written: ?/?/1978 Description: This program prints the greeting “Hello, World!” */ #include main ( ) { printf (“Hello, World!\n”) ; }
14
Anatomy of a C Program program header comment preprocessor directives main ( ) { statement(s) }
16
The Program Header Comment All comments must begin with the characters /* and end with the characters */ The program header comment always comes first The program header comment should include the filename, author, date written and a description of the program
17
Preprocessor Directive Lines that begin with a # are called preprocessor directives The #include directive causes the preprocessor to include a copy of the standard input/output header file stdio.h at this point in the code. This header file was included because it contains information about the printf ( ) function that’s used in this program.
18
main ( ) Every program has a function called main, where execution begins The parenthesis following main indicate to the compiler that it is a function.
19
Left Brace A left curly brace -- { -- begins the body of every function. A corresponding right curly brace must end the function. The style is to place these braces on separate lines in column 1.
20
printf (“Hello, World!\n”) ; This is the function printf ( ) being called with a single argument, namely the string “Hello, World!\n” Even though a string may contain many characters, the string itself should be thought of as a single quantity. Notice that this line ends with a semicolon. All statements in C end with a semicolon.
21
Right Brace This right curly brace -- } --matches the left curly brace above. It ends the function main ( ).
23
Common variable types int - stores integers (-32767 to +32768) unsigned int – 0 to 65535 char – holds 1 byte of data (-127 to 128) unsigned char – holds 1 byte (0 to +255) long – usually double int (signed) unsigned long – positive double int float – floating point variable double – twice of a floating point variable Note: local, global and static variables
24
scanf scanf (“conversion specifier”,variable); scanf (“%d”,&i); Usual variable type Display: %c char single character %d (%i) int signed integer %f float or double signed decimal
25
printf printf (“%d”,i); Usual variable type Display %c char single character %d int %i signed integer %e (%E) float or double exponential format %f float or double signed decimal %g (%G) float or double use %f or %e as required %o int unsigned octal value %p pointer address stored in pointer %s array of char sequence of characters %u int unsigned decimal %x (%X) int unsigned hex value
26
Operators + addition - subtraction * multiplication / division % mod or remainder (e.g., 2%3 is 2), also called 'modulo' << left-shift (e.g., i<<j is i shifted to the left by j bits) >> right-shift & bitwise AND | bitwise OR ^ bitwise exclusive-OR && logical AND (returns 1 if both operands are non-zero; else 0) || logical OR (returns 1 if either operand is non-zero; else 0) < less than (e.g., i<j returns 1 if i is less than j) > greater than <= less than or equal >= greater than or equal == equals != does not equal
27
Operators (contd.) Increment and Decrement Operators ++ Increment operator -- Decrement Operator k++ or k-- (Post-increment/decrement) k = 5; x = k++; // sets x to 5, then increments k to 6 ++k or --k (Pre-increment/decrement) k = 5; x = ++k; // increments k to 6 and then sets x to the // resulting value, i.e., to 6
28
Example – total cost calculator #include main() { float cost =0.0; float tax = 0.08; float totalCost = 0.0; printf(“Enter the cost of the item:”); scanf(“%f”, &cost); totalCost = cost *tax + cost; printf(“Total cost is : %f\n”, totalCost); }
30
Exercises Extra Credit – Write a volume and surface area calculator
31
Functions and Prototypes Building blocks of code Group relevant and repetitive actions into functions Variables are usually local (they exist only inside the function) type FunctionName(type declared parameter list) { statements that make up the function }
32
Example function #include int add1(int); void main() { int x; x=5; x=add1(x); printf("%d“,x); } int add1(int i) { int y; y=i+1; return (y); } Returns an integer result Expects an integer parameter
33
Conditional clauses if (expression) statement else statement if (x==1) { printf(“Hello”); printf (“hi\n”); } else { printf(“World’); }
34
Conditional Loops while (expression) statement while (x<1000) x++; while (x<1000) { x++; y=y+10; }
35
Conditional Loops do statement while (expression) x = 0; do { x++; } while (x<1000);
36
Unconditional Loops for( initialization; expression; increment ) statement for (i=0;i<100;i++) { printf("Hi."); }
37
The switch statement The C switch allows multiple choice of a selection of items at one level of a conditional where it is a far neater way of writing multiple if statements switch (expression) { case item1: statement1; break; case item2: statement2; break; case itemn: statementn; break; default: statement; break; }
38
Arrays Declaration: int x[10]; double y[15]; x[5]=10; char c[15]; Note arrays start with 0 element
39
Pointers A pointer in C is the address of something The unary operator `&' is used to produce the address of an object int a, *b, c; // b is a pointer b = &a; // Store in b the address of a c = *b; // Store in c the value at // address b (i.e., a) Pointers to pointers Pointers to functions
40
Character Pointers & Arrays char *y; char x[100]; y = &x[0]; y = x; // Does the same as the line above *(y+1) gives x[1] *(y+i) gives x[i]
41
Structures User defined ‘data type’ struct emprec { char name[25]; int age; int pay; }; struct emprec employee; employee.age=32;
42
Nice to have Add plenty of comments /* */ or // Good layout. main(){printf("Hello World\n");} Use meaningful variable names Use brackets to avoid confusion a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0 Initialize your variables
43
Good Programming Practices C programming standards are available on the Web These standards include: Naming conventions Use of whitespace Use of Braces Comments
44
Examples of Comment Styles /* a comment */ /*** another comment ***/ /*****/ /*A comment can be written in this * fashion to set it off from the * surrounding code. */
45
More Comments /*******************************************\ * If you wish, you can put comments * * in a box. This is typically used for * * program header comments and for * * function header comments * \*******************************************/
46
Use of Whitespace Use blank lines to separate major parts of a source file or function Separate declarations from executable statements with a blank line Preprocessor directives, main(), and the braces are in column 1
47
Use of Whitespace (continued) All executable statements are indented one tab stop. How deep should my tabs be ? Either 3 or 4 spaces. Choose whichever you like and use that same number consistently throughout your program. 2 spaces are not enough for good readability, more than 4 causes the indentation to be too deep.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.