Vous êtes sur la page 1sur 47

TA ZC142 Computer Programming Lecture 2 Date: 28/07/2012

Last Lecture
Introduction to Computer
Representation of Data Programming Language

C Programming Language

Basic Structure

Simple C Program

Todays Lecture

Programming Attributes
Structure of C program C Character Set
Variables & Constants

Data Types Operators

Arithmetic Operators Relational Operators Logical Operators Assignment Operators Increment and Decrement Operators

Conditional Operator Bitwise Operators Special Operators

Structure of a C Language Program


/* Program to compute .

*/ #include<stdio.h> /*Library files inclusion */


Void indicate that main( ) receives no data from OS

int main(void) {

/* local variable declarations */ /* initialization */ /* statements */

return(0);
}

Returns 0 to the OS after execution.

Simple C Program
Standard Header File #include<stdio.h> #define KMS_PER_MILE 1.609 Preprocessor directive

constant

Reserved Words

int main (void) { float miles, kms; /* Read distance in miles */ printf( Enter distance in miles \n); scanf (%f, &miles); /*Convert the distance to kms*/ kms = KMS_PER_MILES * miles;

Variables or User defined identifiers

Comments

Standard Identifier

printf( Distance in kms = \t %f ,kms ) ; // Display the resultant distance in Kms return(0); }

C Character Set
Uppercase letters A to Z , lower case letters a to

z, digits 0 to 9 Special characters.

e.g. + , - , *, &, ?, /, \, #, (, ), {, },[, ], <, >, ==, =, ;, :, , etc


e.g. \n (new line character), \t (horizontal tab), \v (vertical tab)

Escape sequences

Variables & Constants in Programming Language


Variable

Its a name associated with a memory cell whose value can be changed. All variables must be declared before they can appear in executable statements It consists of a data type, followed by one or more variables. E.g. double miles, kms;

Variables
Invalid
5thplayer x Order-no double
count value

Remark
First char is number First char is not letter - is not allowed Double is a reserved word Blank is not permitted

Valid
player5 x Order_no doubletype
Count_value

Variables & Constants in Programming Language


Constant

Its a name associated with a memory cell whose value can not be changed. Declared by #define directive. E.g. #define KMS_PER_MILE 1.609
const

int x = 300; const char c = A;

Data Types
It is a set of values and a set of operations on

those values.

Primary Data types Derived Data types (discussed later) User defined data types (discussed later)

Primary Data Type


Data type int
char float

Description Integer quantity


Single character Floating point number

Memory Requirement 2 bytes


1 byte 4 bytes

double

Double precision

8 bytes

Assignment Statement
It stores a values or a computation result

in a variable It is used to perform arithmetic operations in a program e.g. kms = KMS_PER_MILES * miles;

Assignment operator

Multiply operator

printf() Function
Escape sequence function arguments placeholder

Function name

printf( Distance in kms = \t %f ,kms ) ;


Format String
printlist

scanf() Function
Addressof operator
Function name

scanf ( %d

%d, &age, &year);

Format String

Variables

Sample Program
#include<stdio.h> /* program to display use of I/O and data types */ int main() Input { int marks; Enter your marks: float average; 70 Enter average marks: char grade; 50.5 printf(Enter your marks:\n); Enter your grade: scanf(%d, &marks); printf(Enter average marks:\n); A scanf(%f, &average); Output printf(Enter your grade:\n); Marks = 70 scanf(%c, &grade); Average = 50.5 printf(Marks = %d\n,marks); printf(Average = %f\n,average); Grade = A printf(Grade = %c\n,grade); return (0); }

Arithmetic Operators
Operator + * / Meaning Addition or unary plus Subtraction or unary minus Multiplication Division

Modulo Division

Arithmetic Expression
Let int x = 15; int y = 6;int z;
Example:

z z z z z

= = = = =

x+y x-y x*y x/y (decimal part truncated) x%y (remainder of the division)

Q. If x and y are declared as float then? Q. If x is integer and y is float then?

Example 2 :Program to compute area and circumference of a circle #include<stdio.h> #define PI 3.14 int main(void) { int radius; float area,circum; printf("Enter radius of a circle\n"); scanf("%d", &radius); area = PI * radius * radius; circum = 2 * PI * radius; printf("Area = %f \t Circumference = %f ",area, circum); return(0); }

Precedence & Associativity of Arithmetic Operators


Operator
() Unary +, *, /, %

Precedence
1 2 3

Associativity
Left to Right Left to Right Left to Right

+, -

Left to Right

Assignment Operators
Simple Assignment

Operators a = a+1 a = a-1 a =a*(b+1) a = a/(b+1) a = a%b

Shorthand Operators a+= 1 a-= 1 a*=b+1 a/=b+1 a%=b

Short hand statement is more concise and easier to read

Example
Let
1.

int x, a, b, c;

2.
3.

x=ab/3+c*21 x = ( (a * b) + (-b / c * a) ) / c x = (a c / 5 + b) % 100 + 26

Type Conversion
Implicit Type Conversion
Explicit Type Conversion

Implicit Type Conversion


C automatically converts any

intermediate values to the proper data type Lower type is automatically converted to the higher type before operation proceeds

Implicit Type Conversion


int i, x; float f; double d; long int l; x = l / i +

i * f

d;

Explicit Type Conversion


Also called Type casting
Explicit conversion of the data type of

some variable or expression locally. Syntax

(type-name) expression int female_no, male_no; float ratio; ratio = (float) female_number / male_number;

E.g

More Examples on type casting


Example X = (int)7.5 A = (int)21.3/(int)4.5 B = (double)sum/n Y = (int)a+b Y = (int)(a+b) Result X=7 A=5 Results is in double A is converted to int and then added to b Result of a+b is converted to int

Final result of an expression is converted to the

type of variable on the left of the assignment = before assigning result to it.
float to int truncation of fractional part. double to float rounding of digits long int to int dropping of excess higher order

bits

More Examples:
Write a equivalent C expression for

given algebraic expressions. 1. (a+b)(c+d) 2. ax2+bx+c 3. pr2+2prh 4. s = ut + 1/2at2 5. T = (m1m2/m1+m2)

Relational Operators
Operator < <= > Is less than Is less than or equal to Is greater than Meaning

>=
== !=

Is greater than or equal to


Is equal to Is not equal to

Examples:

5 <= 7

TRUE 5 < -8 FALSE 11 < 8+4 TRUE x+y == a+b TRUE if value of x+y is equal to value of a+b -20 >= 0 FALSE

Logical Operators
Operator && || ! Meaning Logical AND Logical OR Logical NOT

Q. Are !(a>b) and a<=b same?? Q. Are !(a==b) and a!=b same??

Exercise
1. Write a program which takes marks of five

students as input and computes the average marks. Print the average mark of five students.
2. Write a program to compute roots of a quadratic

equation ax2 + bx + c = 0

Exercise
3 . Write a program to solve two linear equations 2x + 8y 10 = 0 5x + 6y 5 = 0

Increment and Decrement Operators


++ Adds one to the operand -- Subtracts one from the operand Both are unary operators

++i is equivalent to: i = i+1 --i is equivalent to: i = i-1 Is ++i and i++ are same??

What are Postfix and Prefix Expressions?


In postfix, the expression is evaluated first using the original value of the variable and then the variable is incremented (or decremented) by one. Ex. m = n++; or m = n--;

In prefix, the variable is incremented (or decremented) first and then the expression is evaluated using the new value of the variable. Ex. m = --n; or m = ++n;

Postfix and Prefix Examples


Output
j =10; i =j++;

i = 10 j = 11

What is the values of i and j?


j =10;

Output i=9 j=9

i=--j;
What is the values of i and j?

Conditional Operator
Also called Ternary operator

Syntax
Variable = expression1 ? expression2

: expression3
Example: a=5;

Output X = 10

b=10;
x =(a>b) ? a : b; What will be the value of x??

Bitwise Operators
Operator & | Meaning Bitwise AND Bitwise OR

^
<< >>

Bitwise exclusive OR
Shift left Shift right

Manipulation of data at bit level Not be applied to float or double values

Special Operators
The Sizeof Operator

Returns the number of bytes the operand occupies


p=sizeof(value); q=sizeof(float); r=sizeof(long int);

Examples:

Comma Operator
Used to link the related expressions

together. Evaluation starts from left to right. And the value of the right most expression is the value of the combined expression. Example:
1.

value = (a = 6, b = 7, c = 8, a+b+c); Value contains 21

Operators

Associativity

Rank

(),[] +, -, ++, --, !, ~, *, &, sizeof, (type) *, /, % Binary plus(+) and Binary minus (-) <<, >> <, <=, >, >= ==, != & ^ | && || ?: =, *=, /=, %=, +=, -=, &=, ^= ,

L to R R to L L to R L to R L to R L to R L to R L to R L to R L to R L to R L to R R to L R to L L to R

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

ALGORITHMS AND FLOW CHARTS

Algorithms

An Algorithm is just a detailed sequence of simple steps that are needed to solve a problem

Flow Charts

Flow Charts are maps or graphical representations of a process. Steps in a process are shown with symbolic shapes, and the flow of the process is indicated with arrows connecting the symbols

Symbols in Flowchart
START , END
INPUT

PROCESS INPUT DATA

DECISION

CONNECTOR CONNECTOR

Example Flow Chart


START

Marks = 50 Avg = 45

Flow chart to find whether the the marks of a student is above avg or below avg

NO Marks > avg Print below Avg

YES Print above Avg

END

Any Doubts or Questions?

Vous aimerez peut-être aussi