Introduction to C Programming C How to Program

  • Slides: 60
Download presentation
Introduction to C Programming C How to Program, 6/e

Introduction to C Programming C How to Program, 6/e

OBJECTIVES §Interpreter VS Compiler §Simple C program • Variables • Data types • Arithmetic

OBJECTIVES §Interpreter VS Compiler §Simple C program • Variables • Data types • Arithmetic in C • Operations • Precedence Rules

Interpreter VS Compiler

Interpreter VS Compiler

A Simple C Program // int is return data type // main is entrance

A Simple C Program // int is return data type // main is entrance function int main() { statement 1; // …. return 0; }

A Simple C Program #include <stdio. h> int main() { printf("Hello world!n"); return 0;

A Simple C Program #include <stdio. h> int main() { printf("Hello world!n"); return 0; }

A Simple C Program #include <stdio. h> int main() { //this is a comment

A Simple C Program #include <stdio. h> int main() { //this is a comment printf("Hello world!n"); return 0; }

A Simple C Program #include <stdio. h> int main() { /*this is a comment

A Simple C Program #include <stdio. h> int main() { /*this is a comment */ printf("Hello world!n"); return 0; }

A Simple C Program #include <stdio. h> int main() { int x; int y;

A Simple C Program #include <stdio. h> int main() { int x; int y; x = 3; y = 4; int z; z = x + y; printf("z = %d" , z); return 0; }

A Simple C Program #include <stdio. h> int main() { int x; int y;

A Simple C Program #include <stdio. h> int main() { int x; int y; scanf("%d" , &x); scanf("%d" , &y); int z; z = x + y; printf("z = %d" , z); return 0; }

C Program Examples: ◦ ◦ ◦ Header file Main function Variables Input and output

C Program Examples: ◦ ◦ ◦ Header file Main function Variables Input and output Process #include <stdio. h> // header file (preprocessor ) // calculating sum of two user input variables int main() { /* variable definition */ int a; int b; int result = 0; // get first variables form user printf("Enter first number: n"); scanf("%d", &a); // get scoend variables form user printf("Enter scoend number: n"); scanf("%d", &b); // sum of input variables result = a + b; printf("%d + %d = %dn", a, b, result); system("Pause"); return 0; }

2. 2 A Simple C Program: Printing a Line of Text

2. 2 A Simple C Program: Printing a Line of Text

2. 2 A Simple C Program: Printing a Line of Text (Cont. ) •

2. 2 A Simple C Program: Printing a Line of Text (Cont. ) • Lines 1 and 2 • /* Fig. 2. 1: fig 02_01. c A first program in C */ • begin with /* and end with */ indicating that these two lines are a comment. • C 99 also includes the C++ language’s // single-line comments in which everything from // to the end of the line is a comment.

2. 2 A Simple C Program: Printing a Line of Text (Cont. ) •

2. 2 A Simple C Program: Printing a Line of Text (Cont. ) • You insert comments to document programs and improve program readability. • Comments do not cause the computer to perform any action when the program is run. • Comments are ignored by the C compiler and do not cause any machine-language object code to be generated. • Comments also help other people read and understand your program.

2. 2 A Simple C Program: Printing a Line of Text (Cont. ) •

2. 2 A Simple C Program: Printing a Line of Text (Cont. ) • Line 3 • #include <stdio. h> • Lines beginning with # are processed by the preprocessor before the program is compiled. • Line 3 tells the preprocessor to include the contents of the standard input/output header (<stdio. h>) in the program.

2. 2 A Simple C Program: Printing a Line of Text (Cont. ) •

2. 2 A Simple C Program: Printing a Line of Text (Cont. ) • Line 6 • int main( void ) • Every program in C begins executing at the function main. • The parentheses after main indicate that main is a program building block called a function. • The keyword int to the left of main indicates that main “returns” an integer (whole number) value. • The void in parentheses here means that main does not receive any information. • A left brace, {, begins the body of every function (line 7). A corresponding right brace ends each function (line 11). • This pair of braces and the portion of the program between the braces is called a block.

2. 2 A Simple C Program: Printing a Line of Text (Cont. ) •

2. 2 A Simple C Program: Printing a Line of Text (Cont. ) • Line 8 • printf( "Welcome to C!n" ); • instructs the computer to perform an action, namely to print on the screen the string of characters marked by the quotation marks. • A string is sometimes called a character string, a message or a literal. • The entire line, including printf, its argument within the parentheses and the semicolon (; ), is called a statement. • Every statement must end with a semicolon (also known as the statement terminator).

2. 2 A Simple C Program: Printing a Line of Text (Cont. ) •

2. 2 A Simple C Program: Printing a Line of Text (Cont. ) • When encountering a backslash in a string, the compiler looks ahead at the next character and combines it with the backslash to form an escape sequence. • The escape sequence n means newline.

2. 2 A Simple C Program: Printing a Line of Text (Cont. ) •

2. 2 A Simple C Program: Printing a Line of Text (Cont. ) • Line 10 • return 0; /* indicate that program ended successfully */ • is included at the end of every main function. • The keyword return is one of several means we’ll use to exit a function. • When the return statement is used at the end of main as shown here, the value 0 indicates that the program has terminated successfully.

Variables and Data Type

Variables and Data Type

Variables in computer A variable is a location in memory where a value can

Variables in computer A variable is a location in memory where a value can be stored for use by a program.

Variables • Have the same meaning as variables in algebra • Single alphabetic character

Variables • Have the same meaning as variables in algebra • Single alphabetic character • Each variable needs an identifier that distinguishes it from the others • a = 5 • x = a + b • valid identifier in C may be given representations containing multiple characters • • • A-Z, a-z, 0 -9, and _ (underscore character) First character must be a letter or underscore (no, _no 9 no) There can be no embedded blanks (student no) Identifiers are case sensitive (area, AREA, Ar. Ea) Keywords cannot be used as identifiers

Reserved Words(Keywords) in C auto case break char int register long return const continue

Reserved Words(Keywords) in C auto case break char int register long return const continue short signed default do sizeof static double else struct switch enum float extern for typedef unsigned union void goto if volatile while

Naming Conventions • C programmers generally agree on the following conventions for identifier: •

Naming Conventions • C programmers generally agree on the following conventions for identifier: • Use meaningful identifiers • Separate words within identifiers with: • underscores • capitalize each word • Examples: • surface. Area • Surface. Area • Surface_Area

Variable declaration • Before using a variable, you must declare it • All variables

Variable declaration • Before using a variable, you must declare it • All variables must be defined with a name and a data type. § Data_Type Identifier; • int width; // width of rectangle • float area; // result of calculating area stored in it • char separator; // word separator § Data_Type Identifier = Initial_Value; • int width = 10; // width of rectangle • float area = 255; // result of calculating area stored in it • char seperator = ‘, ’; // word separator § Data_Type Identifier, Identifier; • int width, length, temporary; • float radius, area = 0;

Data types • Minimal set of basic data types • primitive data types •

Data types • Minimal set of basic data types • primitive data types • • • int float double char void • The size and range of these data types may vary among processor types and compilers • In code blocks: • • int 4 byte float 4 byte char 1 byte double 8 byte

Write a program that show size of data type in code blocks.

Write a program that show size of data type in code blocks.

Result

Result

2. 3 Another Simple C Program: Adding Two Integers

2. 3 Another Simple C Program: Adding Two Integers

Input & Output

Input & Output

Printf / Scanf • prints the literal Enter first integer on the screen and

Printf / Scanf • prints the literal Enter first integer on the screen and positions the cursor to the beginning of the next line. • printf( "Enter first integern" ); /* prompt */ • This message is called a prompt because it tells the user to take a specific action. • The scanf function reads from the standard input, which is usually the keyboard. • scanf( "%d", &integer 1 ); /* read an integer */ • uses scanf to obtain a value from the user.

Printf / Scanf • This scanf has two arguments, "%d" and &integer 1. •

Printf / Scanf • This scanf has two arguments, "%d" and &integer 1. • The first argument, the format control string, indicates the type of data that should be input by the user. • The %d conversion specifier indicates that the data should be an integer (the letter d stands for “decimal integer”). • The second argument of scanf begins with an ampersand (&)—called the address operator in C—followed by the variable name. The ampersand, when combined with the variable name, tells scanf the location (or address) in memory at which the variable integer 1 is stored.

Printf / Scanf • When the computer executes the preceding scanf, it waits for

Printf / Scanf • When the computer executes the preceding scanf, it waits for the user to enter a value for variable integer 1. • The user responds by typing an integer, then pressing the Enter key to send the number to the computer. • The computer then assigns this number, or value, to the variable integer 1. • Any subsequent references to integer 1 in this program will use this same value.

Printf / Scanf specifier d or i u f c s % Output Signed

Printf / Scanf specifier d or i u f c s % Output Signed decimal integer Unsigned decimal integer Decimal floating point Character String of characters A % followed by another % character will write a single % to the stream. example 324 54 214. 58 A abcd %

Arithmetic Operator

Arithmetic Operator

2. 5 Arithmetic in C • The C arithmetic operators are summarized in Fig.

2. 5 Arithmetic in C • The C arithmetic operators are summarized in Fig. 2. 9.

Operators Operator • Arithmetic Operators Width * High • unary operators • operators that

Operators Operator • Arithmetic Operators Width * High • unary operators • operators that require only one operand • binary operators • operators that require two operands • ternary operators • operators that require three operands • Equality and Relational Operators • Logical Operators • Bitwise Operators • Assignment Operators • Conditional Operator Operand

Arithmetic Operators • Unary Operator C operation Operator Expression Explanation Positive + a =

Arithmetic Operators • Unary Operator C operation Operator Expression Explanation Positive + a = +3; Negative - b = -4; Increment ++ i++; Equivalent to i = i + 1 Decrement - - i - -; Equivalent to i = i - 1

PRE / POST Increment • Consider this example: int width = 9; printf("%dn", width++);

PRE / POST Increment • Consider this example: int width = 9; printf("%dn", width++); printf("%dn", width); • But if we have: int width = 9; printf("%dn", ++width); printf("%dn", width); int width = 9; printf("%dn", width); width++; printf("%dn", width); 9 10 int width = 9; width++; printf("%dn", width); 10 10

PRE / POST Increment int R = 10; int count = 10; ++ Or

PRE / POST Increment int R = 10; int count = 10; ++ Or -- Statement Equivalent Statements R = count++; R = ++count; R = count--; R = --count; R = count; count = count + 1; R = count; count = count – 1; R = count; R count 10 11 11 11 10 9 9 9

Arithmetic Operators • Binary Operators C operation Operator Expression Addition + b = a

Arithmetic Operators • Binary Operators C operation Operator Expression Addition + b = a + 3; Subtraction - b = a – 4; Multiplication * b = a * 3; Division / b = a / c; Modulus (integer) % b = a % c;

Division • The division of variables of type integer will always produce a variable

Division • The division of variables of type integer will always produce a variable of type integer as the result • Example int a = 7, b; float z; b = a / 2; z = a / 2. 0; printf("b = %d, z = %fn", b, z); Since b is declared as an integer, the result of a/2 is 3, not 3. 5 b = 3, z = 3. 500000

Modulus • You could only use modulus (%) operation on integer variables (int, long,

Modulus • You could only use modulus (%) operation on integer variables (int, long, char) z = a % 2. 0; // error z = a % 0; // error Modulus will result in the remainder of a/2. • Example int a = 7, b, c; b = a % 2; c = a / 2; printf("b = %dn", b); printf("c = %dn", c); - 7 2 6 3 a/2 integral 1 a%2 remainder

Equality and Relational Operators • Equality Operators: • Relational Operators: Operator > < >=

Equality and Relational Operators • Equality Operators: • Relational Operators: Operator > < >= <= Example x > y x < y x >= y x <= y Operator Example Meaning == x == y x is equal to y != x != y x is not equal to y Meaning x is greater than y x is less than y x is greater than or equal to y x is less than or equal to y

Bitwise Operators Operator Name & AND Result is 1 if both operand bits are

Bitwise Operators Operator Name & AND Result is 1 if both operand bits are 1 | OR Result is 1 if either operand bit is 1 ^ XOR Result is 1 if operand bits are different ~ Description Not (Ones Complement) Each bit is reversed << Left Shift Multiply by 2 >> Right Shift Divide by 2

Examples • A • B • c • c • c = = =

Examples • A • B • c • c • c = = = = 199; 90; a & b = 66; a | b = 233; a ^ b = 157; ~a = 56 a << 2 = 28; a >> 3 = 24; A= 1 1 0 0 0 1 1 1 B= 0 1 1 0 A&B= 0 1 0 A|B= 1 1 0 1 1 1 A^B= 1 0 0 1 1 1 0 1 !A = 0 0 1 1 1 0 0 0 0 0 1 1 0 0 0

Logical Operators • Logical operators are useful when we want to test multiple conditions

Logical Operators • Logical operators are useful when we want to test multiple conditions • AND • OR • NOT

&& - Logical AND • All the conditions must be true for the whole

&& - Logical AND • All the conditions must be true for the whole expression to be true • Example: if (a == 1 && b == 2 && c == 3) • means that the if statement is only true when a == 1 and b == 2 and c == 3 e 1 e 2 Result = e 1 && e 2 0 0 0 false 0 1 0 false true false 1 0 0 true false 1 1 1 true

|| - Logical OR • The truth of one condition is enough to make

|| - Logical OR • The truth of one condition is enough to make the whole expression true • Example: if (a == 1 || b == 2|| c == 3) • means the if statement is true when either one of a, b or c has the right value e 1 e 2 Result = e 1 || e 2 0 0 0 false 0 1 1 false true 1 0 1 true false true 1 1 1 true

! - Logical NOT • Reverse the meaning of a condition • Example: if

! - Logical NOT • Reverse the meaning of a condition • Example: if (!(radius > 90)) • Means if radius not bigger than 90. e 1 Result = !e 1 0 1 false true 1 0 true false

Assignment Operators • Assignment operators are used to combine the '=' operator with one

Assignment Operators • Assignment operators are used to combine the '=' operator with one of the binary arithmetic or bitwise operators • Example : • c = 9; Operator Expression Equivalent Statement Results += -= *= /= %= &= ^= |= <<= >>= c += 7; c -= 8; c *= 10; c /= 5; c %= 5; c &= 2 ; c ^= 2; c |= 2; c <<= 2; c >>= 2; c = c + 7; c = c – 8; c = c * 10; c = c / 5; c = c % 5; c = c & 2; c = c ^ 2; c = c | 2; c = c << 2; c = c >> 2; c = 16 c = 1 c = 90 c = 1 c = 4 c = 0 c = 11 c = 36 c = 2

Conditional Operator • The conditional operator (? : ) is used to simplify an

Conditional Operator • The conditional operator (? : ) is used to simplify an if/else statement • Condition ? Expression 1 : Expression 2; • The statement above is equivalent to: if (Condition) Expression 1; else Expression 2; • Which are more readable?

Conditional Operator • Example: if/else statement: if (total > 12) grade = ‘P’; else

Conditional Operator • Example: if/else statement: if (total > 12) grade = ‘P’; else grade = ‘F’; conditional statement: (total > 12) ? grade = ‘P’: grade = ‘F’; OR grade =( total > 12) ? ‘P’: ‘F’;

Conditional Operator • Example: if/else statement: if (total > 12) printf(“Passed!!n”); else printf(“Failed!!n”); Conditional

Conditional Operator • Example: if/else statement: if (total > 12) printf(“Passed!!n”); else printf(“Failed!!n”); Conditional Statement: printf(“%s!!n”, total > 12 ? “Passed”: “Failed”);

Precedence Rules • The rules specify which of the operators will be evaluated first

Precedence Rules • The rules specify which of the operators will be evaluated first • For example: x = 3 * a - ++b%3; Precedence 1 (highest) 2 3 4 5 (lowest) Operator () unary * / % + = += -= *= /= %= Associativity Level left to right to left to right to left

Precedence Rules • how would this statement be evaluated? • : x = 3

Precedence Rules • how would this statement be evaluated? • : x = 3 * a - ++b % 3; • What is the value for X, for: a = 2, b = 4? x = 3 * a - ++b % 3; x = 3 * a - 5 % 3; x = 6 – 2; x = 4;

Precedence Rules • If we intend to have a statement evaluated differently from the

Precedence Rules • If we intend to have a statement evaluated differently from the way specified by the precedence rules, we need to specify it using parentheses ( ) • x = 3 * a - ++b % 3; • Consider having the following statement: • x = 3 * ((a - ++b)%3); • the expression inside a parentheses will be evaluated first • The inner parentheses will be evaluated earlier compared to the outer parentheses

Precedence Rules • how would this statement be evaluated? • x = 3 *

Precedence Rules • how would this statement be evaluated? • x = 3 * ((a - ++b)%3); • What is the value for X, for: a = 2, b = 4? x = 3 * ((a - ++b) % 3); x = 3 * ((a - 5) % 3); x = 3 * ((-3) % 3); x = 3 * 0; x = 0;