310 likes | 430 Views
C Programming. Getting Started Hello World Data types and variables main() I/O routines Program Module Basics of C Programming Advanced C Programming. Hello World. #include < stdio.h > Header file for I/O routines int main() Main entry point for all C programs
E N D
C Programming • Getting Started • Hello World • Data types and variables • main() • I/O routines • Program Module • Basics of C Programming • Advanced C Programming
Hello World #include <stdio.h> Header file for I/O routines int main() Main entry point for all C programs { Start of function body printf(“Hello World\n”); Display the message Hello World on screen return 0; Exit code for program (0 means no error) } End of function body Above is the first program a student will write in any programming language. It illustrates some of the basics that must be mastered to write a program. Note that each line is terminated with a semicolon (;) and that the function body is enclosed is a set of matching braces {}. These are key features of the syntax of the C language.
Data Types • Simple Data Types • char single byte used for character & strings • int integer default 4 bytes • float single precision floating point • double double precision floating point • Complex Data Types • struct • unions • enum
Data Constants • integer • 123 • +123 • -123 • floating point • 1.23 • -1.23e+11 -1.23×1011 • 4.56e-8 4.56×10-8 • character • ‘a’ lower case a – note use of single quote ‘ • char(43) plus sign + • string • “this is a string” note strings are enclosed in double quotes “ • “a” this is a string containing the single character a not a single character constant (see above for a character constant)
Variable Declaration All variables must be declared prior to their use. Variables must have a type. In C, all tokens are case sensitive id, ID and Id are three different tokens. Examples: inti, j, k; float x, y; double a, b, c;
Variable Initialization • int n=10; • float pi=3.141592654; • char oper=‘+’; • struct { char suit, rank;} card = {0,11}; • char vowels[5] = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’};
main() The function main() is the entry point for all C programs. Every program must have exactly one function called main. Typically this is the first function listed in a file. All actions performed by the program must be initiated from main or a function that main invokes. The function declaration for main should be: int main()
I/O Routines • Output • printf(fmt, val_list); • fprintf(FILE, fmt, val_list); • fwrite(buffer, size, count, FILE); • Input • scanf(fmt, var_list); • fscanf(FILE, fmt, var_list); • gets(); • fread(buffer, size, count, FILE);
C Program Module Header Files External files containing additional data types, variables and functions. Data Type Definitions Application specific data types Function Prototypes Declaration of function type, name, list of argument name and type. Variable Declarations Global - available externallyStatic - available internally Function Bodies Code for each declared function
Header Files • Data Type Declarations • Function Prototypes • Global Variable Reference Example: #include <stdio.h>
Data Type Definitions Declare new data types to make your code more readable and flexible. A new data type begins with a typedefkeyword then is followed by the definition. Example typedefstruct {byte suit;byte rank; } cardtype; In the above we have defined a new data type called cardtype. We can use this to declare new variables of this type. Example cardtype card, deck[52];
Function Prototypes Declaration of function type, name, list of argument name and type. typefName(arg_list);arg_list: type vName, … Example void deal(cardtype *hand, intnumCards);
Variable Declarations Declare both global and local variables. Example static intcurrCard; Local variable available only in file cardtype deck[52]; Global variable available in any file
Functions • Function Declaration • Body Example void deal(cardtype*hand, intNumCards) {inti;for (i=0; i < NumCards; i++) hand[i] = deck[currCard++]; } Function Declaration Function Body
Basics of C Programming C programs consists of a series of statements that perform the necessary calculations to accomplish the intended process. Statements may be grouped together inside a set of matching braces {}. Statements enclosed within these braces are called a statement block and are treated as a single statement.
Statements • Assignment • card = hand[topCard]; • I/O • printf(“Slope = %f\n”, m); • Branching • if (x != 0) y=5.0/x; • switch (oper) { • Loops • while (*x != 0) printf(“%f\n”, *x++); • do {} while(cond);
Assignment Statements Assignment statements are of the form var = expr; Where var is the variable to be assigned the value of expr. The expression expr is a combination of variables, constants and operators.
Operators • Arithmetic • + Addition 12+5→17 • - Subtraction 12-5→7 • * Multiplication 12*5→60 • / Division 12/5→2 • % Modulo 12%5→2 • = Assignment
Operators • Increment • ++ Suffix • ++ Prefix • Decrement • -- Suffix • -- Prefix x is 4 y=x++, y is 4 & x is 5 x is 4 y=++x, both x & y will be 5 x is 4 y=x--, y is 4 & x is 3 • x is 4 y=--x, both x & y will be 3
Operators • Bitwise • ~ Ones Complement ~0110→1001 • & And0110&1010→0010 • | Or 0110|1010→1110 • ^ Exclusive Or0110^1010→1100 • >> Shift Right 0110>>1→0011 • << Shift Left0110<<1→1100
Operators • Compound Assignment • += a += b a=a+b • -= a -= b a=a-b • *= a *= b a=a*b • /= a /= b a=a/b • %= a %= b a=a%b • &= a &= b a=a&b • |= a |= b a=a|b • ^= a ^= b a=a^b • <<= a <<= b a=a<<b • >>= a >>= b a=a>>b
Branching If Statement if (cond) stmt;else stmt; Optional else clause Example if (hand.cards[i].rank == 1) {naces++;val++; } else if (hand.cards[i].rank <= 10) {val += hand.cards[i].rank; } else {val += 10; }
Branching Example switch(oper) { case ‘-’: val2 = -val2; falls thru to next case ‘+’: res = val1 + val2; break; drops out of switch case ‘*’: res = val1 * val2; break; case ‘/’: res = val1 / val2; break; default:printf(“Unknown operator\n”);} Switch Statement switch (expr) { case const: default: Optional default} Jumps to case where the value of expr matches const. Jumps to default if no match is found. Will execute code in subsequent case statements unless a break statement is encountered.
Operators • Relational • == Equals • != Not Equals • > Greater than • >= Greater than or Equal • < Less than • <= Less than or Equal • Logical • ! Not !a returns 1 if a is 0 otherwise returns 1 • && And a&&b returns 1 if both a and b are not 0, otherwise returns 0 • || Or a||b returns 0 if both a and b are 0, otherwise returns 1
Pointers A pointer is a variable whose value is a memory address. It specifies where to find a memory location, but does not return the value of the memory location. A pointer may be dereferenced to obtain the value of the memory location. Example: float x, *xp; declare a floating point variable (x) and a pointer to a floating point variable (xp) x=3.0; assign the value 3 to x xp=&x; assign the address of x to xp printf(“The value at %x is %f\n”, output the address of x and its valuexp, *xp); outputs The value at 12ff00 is 3.000000
Pointers There are four main uses of pointers • Passing a value to a function by reference so that the value of the variable may be changed • Accessing elements of an array • Dynamic execution using function pointers • Dynamic allocation of variables
Arrays An array is a contiguous region of memory containing equal sized blocks. Each block is called an element. Think of an array as apartment cluster mailbox. Each Mailbox in the cluster is an element. The contents of the mailbox is the value of the element. The apartment number on the mailbox is the address. Arrays are 0 based, i.e., the first element is index 0. If the array is named a then a[4] refers to the value of the 5th element of the array (contents of the mailbox). The expression a+4 refers to the address of the 5th element of the array (the apartment number).
Array Operators • a[n] returns value of n+1st element in array a[3]4 n is called the index • *a returns value of address pointed to by a *a1 same as a[0] • a+nreturns the address of the n+1st element same as &a[n] • *(a+n) returns value of n+1stelement in array *(a+2)3 same as a[n]
Structures User defined data type grouping other data types into a single data type. Members occupy contiguous memory locations. In the example below a struct is defined with 3 members: name, id and exams all grouped together as a single variable student. Example: struct { char name[80], id[10];int exams[10];} student;
Unions User defined data type grouping other data types into a single data type. All members occupy the same memory location. In the example below a union is defined with 3 members: oper, varand valgrouped together as a single variable token. Changing the value of any one member changes the value of all members. Example: union {char oper;intvar;float val;} token;
Member & Pointer Operators • s.breturns the value of member b in struct s s.b2 • sp->creturns the value of member c in pointer sp. Same as (*sp).c sp->c3 • &s returns the address of s • *spreturns the value of the memory address sp typedefstruct{ int a, b, c; } stype; stype *sp, s = {1, 2, 3}; sp = &s;