Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

Programming in C and C++

Dr. M. Babul Islam


Dept. of Applied Physics and Electronic Engineering
Rajshahi University
Digital Computer
Keyboard, Mouse, Mic, etc. Monitor, Printer, Speaker, etc.

Input CPU Output


Device (ALU & CU) Device

Main
Memory
Computer Programming
Language

Low-level language High-level language


• Machine language • Closer to programmer
• Expressed in binary number • Examples: Fortran, C, C++, Java, etc.
• Closer to machine • Requires a translator program
• Not portable, i.e., machine dependent interpreter or compiler
• Difficult to write programs • Portable, i.e., machine independent
• 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
Assembly Machine
language Assembler language
program program

High-level
language Interpreter/ Executable code
Object code Linker
program Compiler (machine code)

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

C Tokens

Keywords Constants Strings Operators


float, while 12.2, 13 “ABC”, “roll” +, -, *

Identifiers Special Symbols


main, sum [ ], { }

• 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 Variables
Constants:
• In C constants refer to fixed values that do not change during the
execution of a program.

Constants

Numeric Character
constants constants

Integer Real (floating Single String


point) character
constants constants constants constants
12, 32 3.2, 5.9 ‘a’, ‘x’ “sam”, “a”
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.

• Valid variable names:


student total marks x
sub_total a1 temp Area

• Invalid variable names:


123 1st (area)
%x sub total x&
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
Size of data types on a 16-bit machine and their keywords
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
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:


Assignment statement
variable name = value;
Example: count = 0;
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)
Logical Operators

Operator Meaning
&& logical AND (a && b)
|| logical OR (a || b)
! Logical NOT (!a)
Assignment 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);
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 statements
1. if statement
2. switch statement
3. Conditional operator (?:) statement
4. goto statement

False
Test expression

True

Fig: Two-way branching


if Statement
i. Simple if statement:
if (test condition)
{ True Test True
False
statement block; condition
?
}
statement-x;
True-block False False-block
statement
statement statement
block
ii. if ……else statement:
if (test condition) statement-x
statement-x
{
true-block statement;
} statement-y
else statement-y
{
false-block statement; Fig: Flowchart of if……else control.
} Fig: Flowchart of simple if control.
statement-x;
iii. Nested if ……else statement:
if (test condition-1)
{
if (test condition-2) False Test True
{ condition-1
?
statement-1;
} False Test True
else statement-3 condition-2
?
{
statement-2;
} statement-2 statement-1
}
else
{ statement-x
statement-3;
}
statement-x; statement-y

Fig: Flowchart of nested if……else control.


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)
switch
{ expression
case value-1:
block-1; Block-1
break;
case value-2: Block-2
block-2;
break;
...... Default-
...... block
default:
default-block; statement-x
break;
}
statement-x;
Fig: Flowchart of switch statement.
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 Test condition made before
} the loop executed
Example:
.............
sum = 0;
n = 1;
while (n <= 10)
{
sum = sum + n*n;
++n;
}
printf(“Sum = %d\n”, sum);
..............
do-while Statement

General format of the do-while statement:


do
{
Body of the loop
} while (test condition);
Example:
.............
Test condition made after
sum = 0;
the loop executed
n = 0;
do
{
++n;
sum = sum + n*n;
} while (n <= 9);
printf(“Sum = %d\n”, sum);
..............
for Statement

General format of the for statement:


for (initialization; test-condition; increment/decrement)
{
Body of the loop
Test condition made before
}
the loop executed
Example:
.............
sum = 0;
for( n = 1; n<=10; n++)
{
sum = sum + n*n;
}
printf(“Sum = %d\n”, sum);
..............
Arrays and Functions
Array:
An array is a linear list of fixed-size homogeneous data elements.
Ex: int a [3];

Classification of Arrays: a [0]


• One-dimensional arrays (a [3]) a [1]
• Two-dimensional arrays (a [3][3]) a [2]
• Multidimensional arrays
Declaration of one-dimensional array:
General format of one-dimensional array declaration is
type variable-name [size];
Ex: int mark [5];
Index
Since an array provides a convenient structure for representing data, it is
classified as one of the data structures in C. Other data structures include
structure, list, queue and tree.
Functions:
• Library functions (e.g., printf, scanf, sqrt, sin, etc.)
• User-defined functions

Three elements that are related to user-defined functions:


• Function definition
• Function call
• Function declaration
Function definition shall include the following elements:
Like variables, all functions in C must be declared before they are
•invoked.
Function A
type General
function declaration formatofoffour
consists function definition:
parts:
• Function name function_type function_name (parameter list)
Function header
• function type {
• List of parameters
• function name local variable declaration;
• local variable declarations statement 1;
•• parameter list
function statements Function statement
body 2;
• terminating semicolon
return statement ………
return statement;
}
• Recursion and recursive function
Function calls it self.
Example:
factorial (int n)
{
int fact;
if (n == 1)
return (1);
else
fact = n*factorial(n-1);
return (fact);
}
• Passing array to a function
Declaration: int lrgest (int a [ ], int size); int matrix (int a[ ] [n], int m, int n);
Call: largest (a, size);
Definition: int largest(int a [ ], int size)
{
body
}
• Call by value versus call by reference

• Scope, Visibility and Lifetime of Variables


Structures
General format of structure definition:
struct tag_name
{
data_type member1;
data_type member2;
....... …………;
....... …………;
};
structure tag
struct result
{ keyword
char name[32];
int roll, mark; structure elements or members
float grade_point;
};
Declaring structure variables:
struct result
{
char name[32];
int roll, mark;
float grade_point;
} result_1st, result_2nd, result_3rd;

struct book_bank
{
char title[32];
char author[32];
int pages;
float price;
};
struct book_bank book1, book2, book3;
Accessing structure members:
Under a structure the members themselves are not variables, they should be
linked to the structure variables in order to make meaningful members.
The link between a member and a variable is established using the member
operator ‘.’ which is also known as ‘dot-operator’ or ‘period operator’.
Example:
book1.price = 120.50;
book1.pages = 250;
scanf(“%s\n”, book1.title);
scanf(“%d\n”, &book1.pages);

Arrays of structures:
struct book_bank
{ book[0].price = 120;
char title[32]; book[1].price = 220;
char author[32];
float price;
}struct book_bank book[10];
Arrays within structures:
struct book_bank
{ book[0].price[0] = 120;
char title[32]; book[0].price[1] = 220;
char author[32];
float price[2];
}struct book_bank book[10];
String Operation
Declaring and Initializing String Variables:
• C does not support strings as a data type
• C allows to represent strings as character arrays

The general form of declaration of a string variable:


char string_name [size];
Ex: char city [10];
C permits a character array to be initialized in either of the following
way:
char city [10] = “Rajshahi”;
char city [10] = {‘R’, ‘a’, ‘j’, ‘s’, ‘h’, ‘a’, ‘h’, ‘i’, ‘\0’};
C also permits us to initialize a character array without specifying the
number of elements (size). In such cases, the size will be determined
automatically. For example
char city [ ] = “Rajshahi”;
Reading String from Terminal:
char name [10];
scanf (“%s”, name);
Reading a Line of Text:
char line [80];
scanf (“%[^\n]”, line);
getchar ( ) and gets ( ) functions:
char c;
c = getchar ( ); // reading a single character using getchar ( )
function
char line [80];
gets (line); // reading string using gets ( ) function
printf (“%s”, line)
Writing String to Screen:
printf (“%s”, name);
putchar ( ) and puts ( ) functions:
char c = ‘x’;
putchar ( c); // writing a single character to screen
using putchar ( ) function
char line [80];
gets (line); // reading string using gets ( ) function
puts (line); // writing string using puts ( ) function
Some String-Handling Functions:

Function Purpose
strcat () To concatenate two strings.
strcmp () To compare two strings.
strcpy () To copy one string over another.
strlen () To find the length of a string.
File Management in C
Basic file operations:
• Naming a file
• Opening a file
• Reading data from a file
• Writing data to a file
• Closing a file
File handling functions (High level I/O functions):

Function name Operation


• fopen ( ) • To create a new file for use.
• To open an existing file for use.
• fclose ( ) • To close a file which has been opened for use.
• getc ( ) • To Read a character from a file.
• putc ( ) • To Write a character to a file.
• fprintf ( ) • To write a set of data values to a file.
• fscanf ( ) • To read a set of data values from a file.
• getw ( ) • To read an integer from a file.
• putw ( ) • To write an integer to a file.
• fseek ( ) • To set the position to a desired point in the file.
• ftell ( ) • To give the current position in the file (in terms
of byte from the start).
• rewind ( ) • To set the position to the beginning of the file.
Declaring and opening a file: This statement declares the variable fp as a
pointer to the data type FILE. FILE is a
General format: FILE *fp; structure that is defined in the I/O library.
fp = fopen (“file_name”, “mode”);

This statement opens the file named file_name and assigns


an identifier to the FILE type pointer fp. The mode
specifies the purpose of opening this file. The mode can be
one of the following:
r open the file for reading
w open the file for writing
a open the file for appending (or adding data to it)

You might also like