Presentation is loading. Please wait.

Presentation is loading. Please wait.

C Programming Getting Started Getting Started Hello World Hello World Data types and variables Data types and variables main() main() I/O routines I/O.

Similar presentations


Presentation on theme: "C Programming Getting Started Getting Started Hello World Hello World Data types and variables Data types and variables main() main() I/O routines I/O."— Presentation transcript:

1 C Programming Getting Started Getting Started Hello World Hello World Data types and variables Data types and variables main() main() I/O routines I/O routines Program Module Program Module Basics of C Programming Basics of C Programming Advanced C Programming Advanced C Programming

2 Hello World #include 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 printf(Hello World\n); Display the message Hello World on screen return 0; Exit code for program (0 means no error) 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.

3 Data Types Simple Data Types Simple Data Types charsingle byte used for character & strings charsingle byte used for character & strings intinteger default 4 bytes intinteger default 4 bytes floatsingle precision floating point floatsingle precision floating point doubledouble precision floating point doubledouble precision floating point Complex Data Types Complex Data Types struct struct unions unions enum enum

4 Data Constants integer integer 123 123 +123 +123 -123 -123 floating point floating point 1.23 1.23 -1.23e+11 -1.23e+11-1.23×10 11 4.56e-8 4.56e-84.56×10 -8 character character alower case a – note use of single quote alower case a – note use of single quote char(43)plus sign + char(43)plus sign + string string this is a stringnote strings are enclosed in double quotes this is a stringnote strings are enclosed in double quotes athis is a string containing the single character a not a single character constant (see above for a character constant) athis is a string containing the single character a not a single character constant (see above for a character constant)

5 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: int i, j, k; float x, y; double a, b, c;

6 Variable Initialization int n=10; int n=10; float pi=3.141592654; float pi=3.141592654; char oper=+; char oper=+; struct { char suit, rank; } card = {0,11}; struct { char suit, rank; } card = {0,11}; char vowels[5] = {a, e, i, o, u}; char vowels[5] = {a, e, i, o, u};

7 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()

8 I/O Routines Output Output printf(fmt, val_list); printf(fmt, val_list); fprintf(FILE, fmt, val_list); fprintf(FILE, fmt, val_list); fwrite(buffer, size, count, FILE); fwrite(buffer, size, count, FILE); Input Input scanf(fmt, var_list); scanf(fmt, var_list); fscanf(FILE, fmt, var_list); fscanf(FILE, fmt, var_list); gets(); gets(); fread(buffer, size, count, FILE); fread(buffer, size, count, FILE);

9 C Program Module Header Files Header Files Header Files Header Files External files containing additional data types, variables and functions. Data Type Definitions Data Type Definitions Data Type Definitions Data Type Definitions Application specific data types Function Prototypes Function Prototypes Function Prototypes Function Prototypes Declaration of function type, name, list of argument name and type. Variable Declarations Variable Declarations Variable Declarations Variable Declarations Global - available externally Static - available internally Function Bodies Function Bodies Function Bodies Function Bodies Code for each declared function

10 Header Files Data Type Declarations Data Type Declarations Function Prototypes Function Prototypes Global Variable Reference Global Variable ReferenceExample: #include #include

11 Data Type Definitions Declare new data types to make your code more readable and flexible. A new data type begins with a typedef keyword then is followed by the definition. Example typedef struct { 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];

12 Function Prototypes Declaration of function type, name, list of argument name and type. type fName(arg_list); arg_list: type vName, … Example void deal(cardtype *hand, int numCards);

13 Variable Declarations Declare both global and local variables. Example static int currCard; Local variable available only in file cardtype deck[52]; Global variable available in any file

14 Functions Function Declaration Function Declaration Body Body Example void deal(cardtype *hand, int NumCards) { int i; for (i=0; i < NumCards; i++) hand[i] = deck[currCard++]; } Function Declaration Function Body

15 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.

16 Statements Assignment Assignment card = hand[topCard]; card = hand[topCard]; I/O I/O printf(Slope = %f\n, m); printf(Slope = %f\n, m); Branching Branching if (x != 0) y=5.0/x; if (x != 0) y=5.0/x; switch (oper) { switch (oper) { Loops Loops while (*x != 0) printf(%f\n, *x++); while (*x != 0) printf(%f\n, *x++); do { } while(cond); do { } while(cond);

17 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.

18 Operators Arithmetic Arithmetic +Addition 12+5 17 +Addition 12+5 17 - Subtraction 12-5 7 - Subtraction 12-5 7 *Multiplication 12*5 60 *Multiplication 12*5 60 /Division 12/5 2 /Division 12/5 2 %Modulo 12%5 2 %Modulo 12%5 2 =Assignment =Assignment

19 Increment Increment ++ Suffix ++ Suffix ++ Prefix ++ Prefix Decrement Decrement -- Suffix -- Suffix -- Prefix -- Prefix x is 4 y=++x, both x & y will be 5 Operators x is 4 y=x++, y is 4 & x is 5 x is 4 y=x--, y is 4 & x is 3 x is 4 y=--x, both x & y will be 3

20 Operators Bitwise Bitwise ~Ones Complement ~0110 1001 ~Ones Complement ~0110 1001 &And 0110&1010 0010 &And 0110&1010 0010 |Or 0110|1010 1110 |Or 0110|1010 1110 ^Exclusive Or 0110^1010 1100 ^Exclusive Or 0110^1010 1100 >>Shift Right 0110>>1 0011 >>Shift Right 0110>>1 0011 < { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/7/1658794/slides/slide_20.jpg", "name": "Operators Bitwise Bitwise ~Ones Complement ~0110 1001 ~Ones Complement ~0110 1001 &And 0110&1010 0010 &And 0110&1010 0010 |Or 0110|1010 1110 |Or 0110|1010 1110 ^Exclusive Or 0110^1010 1100 ^Exclusive Or 0110^1010 1100 >>Shift Right 0110>>1 0011 >>Shift Right 0110>>1 0011 <>Shift Right 0110>>1 0011 >>Shift Right 0110>>1 0011 <

21 Operators Compound Assignment 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 &= 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<>= a >>= b a=a>>b >>= a >>= b a=a>>b

22 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; }

23 Branching 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. 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); }

24 Operators Relational Relational ==Equals ==Equals !=Not Equals !=Not Equals >Greater than >Greater than >=Greater than or Equal >=Greater than or Equal { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/7/1658794/slides/slide_24.jpg", "name": "Operators Relational Relational ==Equals ==Equals !=Not Equals !=Not Equals >Greater than >Greater than >=Greater than or Equal >=Greater than or Equal Greater than >Greater than >=Greater than or Equal >=Greater than or Equal

25 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 value xp, *xp); outputs The value at 12ff00 is 3.000000

26 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 Passing a value to a function by reference so that the value of the variable may be changed Accessing elements of an array Accessing elements of an array Dynamic execution using function pointers Dynamic execution using function pointers Dynamic allocation of variables Dynamic allocation of variables

27 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 5 th element of the array (contents of the mailbox). The expression a+4 refers to the address of the 5 th element of the array (the apartment number). Arrays

28 Array Declarations Arrays are declared by specifying a type and a number of elements, i.e., type var[num] Examples: int order[10]; double x[100]; cardtype deck[52]; Arrays are initialize by following the declaration by a list: int order[10] = {1,2,3,4,5,6,7,8,9,10}; Arrays may also be initialized by using a for loop: double x[100]; int i; for (i=0; i < 100; i++) x[i] = 0.0;

29 Array Operators a[n] returns value of n+1 st element in arraya[3] 4 n is called the index *a returns value of address pointed to by a *a 1 same as a[0] a+n returns the address of the n+1 st element same as &a[n] *(a+n) returns value of n+1 st element in array *(a+2) 3 same as a[n] Array a IndexValue 01 12 23 34 45 n-110

30 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; student name id exams

31 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, var and val grouped together as a single variable token. Changing the value of any one member changes the value of all members. Example: union { char oper; int var; float val; } token; token oper var val

32 Member & Pointer Operators s.b returns the value of member b in struct ss.b 2 sp->c returns the value of member c in pointer sp. Same as (*sp).csp->c 3 &s returns the address of s *sp returns the value of the memory address sp typedef struct { int a, b, c; } stype; stype *sp, s = {1, 2, 3}; sp = &s;


Download ppt "C Programming Getting Started Getting Started Hello World Hello World Data types and variables Data types and variables main() main() I/O routines I/O."

Similar presentations


Ads by Google