Top Banner
Lecturer: Omid Jafarinezhad Sharif University of Technology Department of Computer Engineering 1 Fundamental of Programming (C) Lecture 3 Constants, Variables, Data Types, And Operations
57

Fundamental of Programming (C)

Feb 24, 2016

Download

Documents

Lane

Fundamental of Programming (C). Lecture 3 Constants, Variables, Data Types, And Operations. Outline. C Program Data types Variables Constants Operations Arithmetic Operators unary operators operators that require only one operand binary operators operators that require two operands - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Fundamental of Programming (C)

Lecturer: Omid Jafarinezhad

Sharif University of TechnologyDepartment of Computer Engineering 1

Fundamental of Programming (C)

Lecture 3Constants, Variables, Data Types, And Operations

Page 2: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 2

Outline• C Program• Data types• Variables• Constants• Operations

– Arithmetic Operators • unary operators

– operators that require only one operand• binary operators

– operators that require two operands

– Assignment Operators– Equality and Relational Operators– Logical Operators– Bitwise Operators – Conditional Operator– Comma Operator– sizeof

Page 3: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 3

C Program

stdout (Screen)

stdin (Keyboard)

stderr (Screen)

Constants and variables

Operations and functions

main

X Y Z

A B C D

Instructions and operating procedures

Page 4: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 4

Simple Program• Examples:// int is return data type// main is entrance functionint main(){ statement 1; statement 1; // …. return 0; }

/* Objective: print on screen*/#include <stdio.h> // preprocessor statements have not ;int main(){ printf("welcome to c!!!"); return 0; // indicate that program ended successfully }

welcome to c!!!

// Simplest c programint main(){ return 0;}

Page 5: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 5

• 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 = %d\n", a, b, result); system("Pause"); return 0;}

Page 6: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 6

• Examples:– Header file– Constant– Main function– Variables– Input and output – Process

#include <stdio.h> // (preprocessor )

#define PI 3.14 // PI constant (preprocessor )

// calculating area of circleint main(){ /* variable definition */ float Radius; float Area = 0; // get radius of circle form user printf("Enter Radius :\n"); scanf("%f", &float ); // calculating area of circle Area = PI * Radius * Radius; printf(“Area = %f", Area );

system("Pause"); return 0;}

Page 7: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 7

• Examples:– Header file– Constant– Main function– Variables– Input and output – Process

#include <stdio.h> // (preprocessor )

#define PI 3.14 // PI constant (preprocessor )

// calculating area of circleint main(){ /* variable definition */ float Radius; float Area = 0; // get radius of circle form user printf("Enter Radius :\n"); scanf("%f", & Radius); // calculating area of circle Area = PI * Radius * Radius; printf(“Area = %f", Area );

system("Pause"); return 0;}

Page 8: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 8

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 9no)– Usually only the first 32 characters are significant– There can be no embedded blanks (student no)– Identifiers are case sensitive (area, Area, AREA, ArEa)– Keywords cannot be used as identifiers

Page 9: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 9

Reserved Words (Keywords) in C

auto break int longcase char register returnconst continue short signed

default do sizeof staticdouble else struct switchenum extern typedef unionfloat for unsigned voidgoto if volatile while

Page 10: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 10

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: – surfaceArea – SurfaceArea – Surface_Area

Page 11: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 11

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

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, Identifier ,….;• int width, length, temporary; • float radius, area = 0;

Page 12: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 12

Variable declaration• When we declare a variable– Space is set aside in memory to hold a value of the

specified data type– That space is associated with the variable name– That space is associated with a unique address

• Visualization of the declaration– int width = 95; // get width form user– // &width is 22ff40– // *&width is 95– // sizeof width is 4

& *

address data

22ff40 95

22ff44

Page 13: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 13

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

Page 14: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 14

Data type qualifiers• Modify the behavior of data type to which they are applied:

– Size qualifiers: alter the size of the basic data types:• short: multiply by 0.5• long: multiply by 2• short can be applied to: int• long can be applied to: int and double

– Sign qualifiers: can hold both positive and negative numbers, or only positive numbers.:• signed: + and -• unsigned: +• they can be applied to : int and char

Page 15: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 15

Data type size and rangeRange Size Example Qualifier Data type

-128 .. 127 0 .. 255-128 .. 127

888

signed char c; unsigned char c; char c;

signedunsigned char

signed (16): -32768 .. 32767

unsigned (16): 0 .. 65535

signed (32): -2147483648 .. 2147483647

unsigned (32): 0 .. 4294967295

161616 or 3216 or 3216 or 3216 163232323264646464

signed short i; signed short int i; unsigned int i; int i; signed int i; short i; short int i; long i; long int i; signed long i; signed long int i; long long i; long long int i; signed long long i; signed long long int i;

signedunsignedshortlong

int

+/- 3.4e +/- 38 (~7 digits) 64 float f; float

+/- 1.7e +/- 308 (~15 digits) 6480

double d; long double d; long double

Page 16: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 16

Overflow and Underflow/* The # character indicate a pre-processor directive; it's an instruction to the compiler to make it do something The <> character tell C to look in the system area for the file stdio.h. If I had given the name #include "stdio.h" instead it would tell the compiler to look in the current directory/*#include <stdio.h> /* * Function main begins program execution* Semi-colon is statement terminator, so it is as a signal to the compiler for end of line*/int main() { /* The 2 curly brackets { }, are used to specify the limits of the program block */ char letter = 'A'; // char variable to show ASCII code short shortVariable = 32769; // short variable for test overflow // printf command display string on the monitor printf("current value of shortVariable is = %d\n", shortVariable); printf("current value of letter is = %d", letter); printf("current value of letter is = %c", letter); system("PAUSE"); // pause the execution to show press any key … return 0; // indicate that program ended successfully}

current value of shortVariable is = -32767current value of letter is = 65current value of letter is = A

Page 17: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 17

Program Error• Compile-time or syntax– is caused when the compiler cannot recognize a

statement

• Run-time– E.g. division by zero

• Logical– E.g. Overflow and Underflow

Page 18: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 18

• Examples:– Header file– Constant– Main function– Variables– Input and output – Process

#include <stdio.h> // (preprocessor )

#define PI 3.14 // PI constant (preprocessor )

// calculating area of circleint main(){ /* variable definition */ float Radius; float Area = 0; // get radius of circle form user printf("Enter Radius :\n"); scanf("%f", &float ); // calculating area of circle Area = PI * Radius * Radius; printf(“Area = %f", Area );

system("Pause"); return 0;}

Page 19: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 19

Integer constant value• Base 10: 1 915 +8 -90• Base 8: 074 0123 084• Base 16: 0x1 0X5 0x7fab

• unsigned: 5000u 4U• long: 123456789l 56L• unsigned long: 536489ul• long long : 5361254865LL 25lL

• Example :– 0xABu 0123uL 017LL

Page 20: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 20

floating-point constant value• A floating-point value contains a decimal point

– 33.5 0.0 -657.983 .2 6.

• For example, the value 150.4582 is represented in scientific notation as– 1.504582 X 102

• and is represented in exponential notation (by the computer) as– 1.504582E+02 – This notation indicates that 1.504582 is multiplied by 10 raised to

the second power (E+02)• The E stands for “exponent”

Page 21: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 21

Char and string constant value• Char

char c;c = 'A'; // d = 65;

• Stringprintf("string is array of char!!!");printf("example of escape sequence is \n");

Page 22: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 22

Constant• Constants provide a way to define a variable which cannot be

modified by any other part in the code – #define: without memory consume– const: memory consume

• #define Identifier constant_value – #define PI 3.14– #define ERROR "Disk error " – #define ERROR "multiline \ message"– #define ONE 1 #define TWO ONE + ONE

Page 23: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 23

Constant• const [Data_Type] Identifier = constant_value;– const p = 3; // const int p = 3;– const p; p = 3.14; // compile error– const p = 3.14; // p = 3 because default is int– const float p = 3.14;

Page 24: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 24

• Examples:– Header file– Constant– Main function– Variables– Input and output – Process

#include <stdio.h> // (preprocessor )

#define PI 3.14 // PI constant (preprocessor )

// calculating area of circleint main(){ /* variable definition */ float Radius; float Area = 0; // get radius of circle form user printf("Enter Radius :\n"); scanf("%f", &float ); // calculating area of circle Area = PI * Radius * Radius; printf(“Area = %f", Area );

system("Pause"); return 0;}

Page 25: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 25

Operators• Arithmetic Operators

– unary operators • operators that require only one operand

– binary operators• operators that require two operands

• Assignment Operators• Equality and Relational Operators• Logical Operators• Bitwise Operators • Conditional Operator• Comma Operator• sizeof

Width * High

Operator

Operand

Page 26: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 26

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

Page 27: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 27

PRE / POST Increment• Consider this example:

• But if we have:

910

int width = 9;printf("%d\n", width++);printf("%d\n", width);

int width = 9;printf("%d\n", width);width++;printf("%d\n", width);

1010

int width = 9;printf("%d\n", ++width);printf("%d\n", width);

int width = 9;width++;printf("%d\n", width);printf("%d\n", width);

Page 28: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 28

PRE / POST Incrementint R = 10;int count = 10;

++ Or -- Statement Equivalent Statements R count

R = count++;R = count;count = count + 1; 10 11

R = ++count;count = count + 1;R = count; 11 11

R = count--;R = count;count = count – 1; 10 9

R = --count;count = count – 1;R = count; 9 9

Page 29: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 29

Arithmetic Operators• Binary Operators

C operation Operator ExpressionAddition + b = a + 3;Subtraction - b = a – 4;Multiplication * b = a * 3;Division / b = a / c;Modulus (integer) % b = a % c;

Page 30: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 30

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 = %f\n", b, z);

b = 3, z = 3.500000

Since b is declared as an integer, the result of a/2 is 3, not 3.5

Page 31: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 31

Modulus• You could only use modulus (%) operation on integer

variables (int, long, char) z = a % 2.0; // error z = a % 0; // error

• Exampleint a = 7, b, c;b = a % 2;c = a / 2;printf("b = %d\n", b);printf("c = %d\n", c);

Modulus will result in the remainder of a/2.

- a/2

a%2

integral

remainder

7 2

6 3

1

Page 32: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 32

Assignment Operators• lvalue = rvalue;

int i;float f;i = 2; // *&i = 2;2 = i; // error: invalid lvalue in assignmentf = 5.6; i = f; // i = 5;i = -5.9; // i = -5;

Page 33: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 33

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 = c + 7; c = 16

-= c -= 8; c = c – 8; c = 1

*= c *= 10; c = c * 10; c = 90

/= c /= 5; c = c / 5; c = 1

%= c %= 5; c = c % 5; c = 4

&= c &= 2 ; c = c & 2; c = 0

^= c ^= 2; c = c ^ 2; c = 11

|= c |= 2; c = c | 2; c = 11

<<= c <<= 2; c = c << 2; c = 36

>>= c >>= 2; c = c >> 2; c = 2

Page 34: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 34

Precedence Rules• The rules specify which of the operators will

be evaluated first– For example: x = 3 * a - ++b%3;

Precedence Operator Associativity Level1 (highest) () left to right

2 unary right to left3 * / % left to right4 + - left to right

5 (lowest) = += -= *= /= %= right to leftc = b = d = 5;

Page 35: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 35

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 * a - 5 % 3;x = 6 - 5 % 3;x = 6 – 2;x = 4;

Page 36: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 36

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

Page 37: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 37

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;

Page 38: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 38

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 – b-- % 3;x = 3 * ++a – 4 % 3;x = 3 * 3 – 4 % 3;x = 9 – 1;x = 8;

b = b -1 , b = 3;

Page 39: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 39

Equality and Relational Operators• Equality Operators:

• Relational Operators:

Operator Example Meaning== x == y x is equal to y!= x != y x is not equal to y

Operator Example Meaning > x > y x is greater than y< x < y x is less than y>= x >= y x is greater than or equal to y<= x <= y x is less than or equal to y

Page 40: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 40

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

conditions– AND– OR – NOT

• C has not bool data type, but:– 0: evaluate to false

• If(0) printf(" …");– other: evaluate to true

• If(1) printf(" …");• If(-13) printf(" …");

Page 41: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 41

&& - 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 If (a = 5) …

e1 e2 Result = e1 && e2false false false false true false true false false true true true

e1 e2 Result = e1 && e20 0 00 1 01 0 01 1 1

Page 42: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 42

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

e1 e2 Result = e1 || e2false false false false true truetrue false truetrue true true

e1 e2 Result = e1 || e20 0 00 1 11 0 11 1 1

Page 43: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 43

! - Logical NOT• Reverse the meaning of a condition• Example: if (!(radius > 90))– Means if radius not bigger than 90.

e1 Result = !e1false truefalse truetrue false true false

e1 Result = !e10 10 11 01 0

Page 44: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 44

Bitwise Operators • Apply to all kinds of int and char types:– signed and unsigned – char, short, int, long, long long

Operator Name Description& 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~ Not (Ones Complement) Each bit is reversed

<< Left Shift Multiply by 2>> Right Shift Divide by 2

Page 45: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 45

Bitwise Operators • Applicable for low level programming, e.g.:– Port manipulation– I/O programming

• Usually: – &: set OFF one bit– |: set ON one bit– ^: reverse one bit

Page 46: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 46

XOR

e1 e2 Result = e1 ^ e20 0 00 1 11 0 11 1 0

Page 47: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 47

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

1 1 0 0 0 1 1 1

0 1 0 0 0 0 1 0

1 1 0 1 1 1 1 1

1 0 0 1 1 1 0 1

0 0 1 1 1 0 0 0

0 0 0 1 1 1 0 0

0 0 0 1 1 0 0 0

0 1 0 1 1 0 1 0

Page 48: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 48

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

statement– Condition ? Expression1 : Expression2;

• The statement above is equivalent to:if (Condition) Expression1;else Expression2;

• Which are more readable?

Page 49: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 49

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’;

Page 50: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 50

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”);

Page 51: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 51

Comma Operator• (Expression1 ,Expression2,…);• Example:– int x, y, z;– z = (x = 2, y = x + 1);– printf("z = %d", z);

int x, y, z; x = 2; y = x + 1; z = y; printf("z = %d", z);

Page 52: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 52

sizeof• The sizeof keyword returns the number of bytes of the given

expression or type– returns an unsigned integer result

• sizeof variable_Identifier;• sizeof (variable_Identifier);• sizeof (Data_Taype);

• Example:– int x; – printf("size of x = %d", sizeof x);– printf("size of long long = %d", sizeof(long long));– printf("size of x = %d", sizeof (x));

Page 53: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 53

Type Casting• Explicit Type cast: carried out by programmer using casting

int k, i = 7;float f = 10.14;char c = 'B';k = (i + f) % 3; // errork = (int)(i + f) % 3;

• Implicit Type cast: carried out by compiler automatically f = 65.6; i = f; //f = (int)f;c = i; // c = (int)i;

Page 54: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 54

Type Casting char c = 'A'; short s = 1; int i; float f; double d;

i = (c + s); (int) (char) (short) (short)

(int)

d = (c / i) + (f * d) + (f + i); (char) (int) (float) (double) (float) (int) int double float

double

double

Page 55: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 55

Precedence RulesPrimary Expression Operators () [] . -> left-to-rightUnary Operators * & + - ! ~ ++expr --expr (typecast) sizeof right-to-left

Binary Operators

* / %

left-to-right

+ ->> <<< > <= >=== !=&^|&&||

Ternary Operator ?: right-to-leftAssignment Operators = += -= *= /= %= >>= <<= &= ^= |= right-to-leftPost increment expr++ expr-- -Comma , left-to-right

Page 56: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 56

Good Programming Practices• Place each variable declaration on its own line with a descriptive

comment

• Place a comment before each logical chunk of code describing what it does

• Do not place a comment on the same line as code – with the exception of variable declarations

• Use spaces around all arithmetic and assignment operators

• Use blank lines to enhance readability

Page 57: Fundamental of Programming (C)

Constants, Variables, Data Types, And Operations – Lecture 3

Sharif University of TechnologyDepartment of Computer Engineering 57

Good Programming Practices• AVOID: variable names starting with an underscore– often used by the operating system and easy to miss

• Place a blank line between the last variable declaration and the first executable statement of the program

• Indent the body of the program

• Use all uppercase for symbolic constants (used in #define preprocessor directives)– Examples:• #define PI 3.14159• #define AGE 52