Upload
mehedi-hasan
View
116
Download
0
Embed Size (px)
Citation preview
Programming in C and C++
Dr. M. Babul IslamDept. of Applied Physics and Electronic Engineering
Rajshahi University
CPU (ALU & CU)
Input Device
OutputDevice
Main Memory
Keyboard, Mouse, Mic, etc.
Digital Computer
Monitor, Printer, Speaker, etc.
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
Assembler
Interpreter/Compiler
Assembly language program
Machine language program
High-level language program
Library
Object code LinkerExecutable code (machine code)
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.
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.
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”
• 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.
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
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
Basic Structure of a C Program
• Documentation Section
• Link Section
• Definition Section
• Global Declaration Section
• main ( ) Function Section
{
declaration part
executable part
}
• Subprogram Section
• 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
• 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);
• 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!”);
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
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
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
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)
Operator Meaning
&& logical AND (a && b)
|| logical OR (a || b)
! Logical NOT (!a)
Logical Operators
• ‘=’ (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
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.
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.
Bitwise Operators
Operator Meaning
& bitwise AND (a & b)
| bitwise OR (a | b)
^ bitwise ex-OR (a^b)
<< shift left
>> shift right
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);
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
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
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
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;
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
goto Statement
General form of goto statement:goto label;. . . . . . . .. . . . . . . .label: statement-x;
label:. . . . .. . . . .goto label;statement-x;
• Loop operations:1. The while statement
2. The do-while statement
3. The for statement
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
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
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