35
Programming in C and C++ Dr. M. Babul Islam Dept. of Applied Physics and Electronic Engineering Rajshahi University

C Programming All

Embed Size (px)

Citation preview

Page 1: C Programming All

Programming in C and C++

Dr. M. Babul IslamDept. of Applied Physics and Electronic Engineering

Rajshahi University

Page 2: C Programming All

CPU (ALU & CU)

Input Device

OutputDevice

Main Memory

Keyboard, Mouse, Mic, etc.

Digital Computer

Monitor, Printer, Speaker, etc.

Page 3: C Programming All

Computer Programming Language

Low-level language• Machine language

• Expressed in binary number• Closer to machine• Not portable, i.e., machine dependent• Difficult to write programs

• Assembly language• Use English like words called mnemonics instead of binary number• Closer to machine• Machine dependent• Easier than machine language• Required a translator program called assembler

High-level language• Closer to programmer• Examples: Fortran, C, C++, Java, etc.• Requires a translator program interpreter or compiler• Portable, i.e., machine independent

Page 4: C Programming All

Assembler

Interpreter/Compiler

Assembly language program

Machine language program

High-level language program

Library

Object code LinkerExecutable code (machine code)

Page 5: C Programming All

C Tokens

• In a C program the smallest individual units are known as C tokens.

Keywordsfloat, while

Identifiersmain, sum

Constants12.2, 13

Strings“ABC”, “roll”

Special Symbols[ ], { }

Operators+, -, *

C Tokens

• Every C word is classified as either a keyword or an identifier.

Page 6: C Programming All

Keywords versus Identifiers

Keywords:• All keywords have their fixed meanings and these meanings cannot be changed.• All keywords must be written in lowercase.

Identifiers:• Identifiers refer to the names of variables, functions and arrays.• Both uppercase and lowercase letters are permitted.• First character must be an alphabet or underscore ( _ ).• Must consist of only letters, digits or underscore.• Cannot use a keyword.• Must not contain white space.

Page 7: C Programming All

Constants versus VariablesConstants:• In C constants refer to fixed values that do not change during the execution of a program.

Constants

Numeric constants

Integerconstants

12, 32

Characterconstants

Real (floating point)

constants3.2, 5.9

Single characterconstants‘a’, ‘x’

Stringconstants

“sam”, “a”

Page 8: C Programming All

• Valid variable names: student total marks x sub_total a1 temp Area

• Invalid variable names: 123 1st (area) %x sub total x&

Variables:• A variable is a data name that may be used to store a data value. Unlike constants, a variable may take different values during the execution.

Page 9: C Programming All

Data Types

C supports three classes of data types:

1. Primary or fundamental data types:

integer (int), character (char), floating point (float), double-precision floating point (double) and void

2. Derived data types:

array, function, structure and pointer

3. User-defined data types

Page 10: C Programming All

Type Keywords Size (bits)

character or signed character char 8

unsigned character unsigned char 8

integer or signed integer signed int or int 16

unsigned integer unsigned int or unsigned 16

short integer or signed short int or short int 8

signed short integer or short

unsigned short integer unsigned short int 8

or unsigned short

long integer or signed long int or 32

signed long integer long int or long

unsigned long integer unsigned long int 32

or unsigned long

floating point float 32

double-precision floating point double 64

long double long double 80

Size of data types on a 16-bit machine and their keywords

Page 11: C Programming All

Basic Structure of a C Program

• Documentation Section

• Link Section

• Definition Section

• Global Declaration Section

• main ( ) Function Section

{

declaration part

executable part

}

• Subprogram Section

Page 12: C Programming All

• Declaration of Variables:

data-type variable names;

Example: int x, count;

float avg, z;

char a;

• Assign Values to Variables:

variable name = value;

Example: count = 0;

Assignment statement

Assignment operator

Page 13: C Programming All

• Reading Data from Keyboard:

scanf (“control string”, &variable1, &variable2, . . .);

Example-1:

int x;

scanf (“%d”, &x);

Example-2:

float r;

scanf (“%f”, &r);

Example-3:

int a, b;

float x;

scanf (“%d %d %f ”, &a, &b, &x);

Page 14: C Programming All

• Printing output/data/message on the screen:

printf (“control string”, variable1, variable2, . . .);

Example-1:

int x = 5;

printf (“x = %d”, x);

Example-2:

float r;

printf (“%f”, r);

Example-3:

printf (“This is my first program!”);

Page 15: C Programming All

Steps of Writing C Program

1. Include header file(s)

2. Declare main ( ) function

2.1 Declare necessary variables

2.2 Read/assign input

2.3 Write necessary statements

2.4 Output (write/print) results

2.5 End program

Page 16: C Programming All

C Operators

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Assignment Operators

5. Increment and Decrement Operators

6. Conditional Operators

7. Bitwise Operators

8. Special Operators

Page 17: C Programming All

Arithmetic Operators

Operator Meaning

+ Addition or unary plus

- Subtraction or unary minus

* Multiplication

/ Division

% Modulo division or remainder division

Ex: 13 % 3 = 1, 9 % 10 = 9

Page 18: C Programming All

Relational Operators

Operator Meaning

< is less than

Ex: 4.5 < 4 False

12 < 19 True

<= is less than or equal to

Ex: 7 <= 6 False

12 <= 13 True

> is greater than

>= is greater than or equal to

== is equal to

Ex: a == b True (if a and b equals)

!= is not equal to

Ex: a != b True (if a is not equal to b)

Page 19: C Programming All

Operator Meaning

&& logical AND (a && b)

|| logical OR (a || b)

! Logical NOT (!a)

Logical Operators

Page 20: C Programming All

• ‘=’ (equal to): a = 5+3;

• Shorthand assignment operators:

variable operator = expression

Ex: a += b+c;

which is equivalent to

variable = variable operator expression

a = a + (b +c);

Assignment Operators

Page 21: C Programming All

Increment and Decrement Operators

• ++

++m; or m++ ; (Equivalent to m = m+1)

• --

--m; or m-- ; (Equivalent to m = m-1)

• m = 5;

y = ++m;

In this case y = 6 and m = 6.

• m = 5;

y = m++;

In this case y = 5 and m = 6.

Page 22: C Programming All

Conditional Operators

A ternary operator pair “?:” is used as conditional operator as follows:

expression-1 ? expression-2 : expression-3;

True

False

Ex:

a = 10;

b = 15;

x = (a > b) ? a : b;

So, x will be 15.

Page 23: C Programming All

Bitwise Operators

Operator Meaning

& bitwise AND (a & b)

| bitwise OR (a | b)

^ bitwise ex-OR (a^b)

<< shift left

>> shift right

Page 24: C Programming All

Special Operators

• The comma operator ( , )

Ex: z = (x = 12, y = 3, x + y);

Here z will be equal to 15.

• The sizeof operator

The sizeof is a compile time operator, it returns the number of bytes the operand (a variable, a constant or a data type qualifier) occupies.

Ex:

m = sizeof(sum);

m = sizeof(long int);

Page 25: C Programming All

Decision Making, Branching and Looping

• Decision-making statements1. if statement

2. switch statement

3. Conditional operator (?:) statement

4. goto statement

Test expressionFalse

True

Fig: Two-way branching

Page 26: C Programming All

i. Simple if statement:if (test condition) {

statement block; }statement-x;

if Statement

Test condition

?

True

False statementblock

statement-x

statement-y

Fig: Flowchart of simple if control.

ii. if ……else statement:if (test condition) { true-block statement; }else { false-block statement; }statement-x;

Test condition

?

True False

False-block statement

statement-x

statement-y

Fig: Flowchart of if……else control.

True-block statement

Page 27: C Programming All

iii. Nested if ……else statement:if (test condition-1) { if (test condition-2) { statement-1; } else {

statement-2; } }else { statement-3; }statement-x;

Test condition-1

?

False True

statement-1statement-2

statement-x

Fig: Flowchart of nested if……else control.

statement-3Test

condition-2?

False True

statement-y

Page 28: C Programming All

iv. else … if ladder:if (test condition-1) statement-1;else if (test condition-2) statement-2; else if (test condition-n)

statement-n; else default-statement;statement-x;

Page 29: C Programming All

switch Statement

General form of switch statement:switch (expression) { case value-1:

block-1; break;

case value-2: block-2; break;

. . . . . . . . . . . . default:

default-block; break;

}statement-x;

switchexpression

Block-1

statement-x

Fig: Flowchart of switch statement.

Block-2

Default-block

Page 30: C Programming All

goto Statement

General form of goto statement:goto label;. . . . . . . .. . . . . . . .label: statement-x;

label:. . . . .. . . . .goto label;statement-x;

Page 31: C Programming All

• Loop operations:1. The while statement

2. The do-while statement

3. The for statement

Page 32: C Programming All

while Statement

General format of the while statement:

while (test condition)

{

Body of the loop

}

Example:. . . . . . . . . . . . .sum = 0;n = 1;while (n <= 10){ sum = sum + n*n; ++n;}printf(“Sum = %d\n”, sum);. . . . . . . . . . . . . .

Test condition made before the loop executed

Page 33: C Programming All

do-while Statement

General format of the do-while statement:

do

{

Body of the loop

} while (test condition);

Example:. . . . . . . . . . . . .sum = 0;n = 1;do{ sum = sum + n*n; ++n;} while (n <= 9);printf(“Sum = %d\n”, sum);. . . . . . . . . . . . . .

Test condition made after the loop executed

Page 34: C Programming All

for Statement

General format of the for statement:

for (initialization; test-condition; increment/decrement)

{

Body of the loop

}

Example:. . . . . . . . . . . . .sum = 0;for( n = 1; n<=10; n++){ sum = sum + n*n; }printf(“Sum = %d\n”, sum);. . . . . . . . . . . . . .

Test condition made before the loop executed

Page 35: C Programming All