[go: up one dir, main page]

0% found this document useful (0 votes)
18 views67 pages

4 About C, Basic C Program and It's Major Components

This document serves as an introduction to the C programming language, detailing its history, features, and structure. It covers essential topics such as data types, variables, constants, operators, and the basic structure of a C program. The course is instructed by Md. Shadmim Hasan Sifat and aims to provide foundational knowledge for programming in C.

Uploaded by

reeonkhan369
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views67 pages

4 About C, Basic C Program and It's Major Components

This document serves as an introduction to the C programming language, detailing its history, features, and structure. It covers essential topics such as data types, variables, constants, operators, and the basic structure of a C program. The course is instructed by Md. Shadmim Hasan Sifat and aims to provide foundational knowledge for programming in C.

Uploaded by

reeonkhan369
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

1

Introduction to
C Programming
A Very Popular Structured Programming Language
2

Course Instructor:
Md. Shadmim Hasan Sifat
Lecturer, CSE, SUST
3

Generation of
Programming
Languages
History of C Programming Language 4

Evolved over the years:


➢ 1972 : C invented
➢ 1978 : The C Programming Language published; first
specification of language
➢ 1989 : C89 standard (known as ANSI C or Standard C)
➢ General-purpose ➢ 1990 : ANSI C adopted by ISO, known as C90
Programming Language ➢ 1999 : C99 standard
➢ mostly backward-compatible
➢ In 1972 De nnis Ritchie writes ➢ not completely implemented in many compilers
C at Bell Labs ➢ 2007 : work on new C standard C1X announced In this
course: ANSI/ISO C (C89/C90)
➢ “ANSI C ”, was completed
late 1988
➢ Middle-level Language
Why C? 5

C Features Uses of C
Simple OS
Portability Compilers
Syntax Based Device Drivers
Case Sensitive Interpreters
Structure Oriented
Embedded System
Middle Level
Use of Pointer
Compiler Based
Fast & Efficient
Powerful
Topics Going To Be Covered… 6

➢ Executing a C Program

➢ Basic Structure of a C Program

➢ Variables, Constants & Data types

➢ Operators

➢ Expressions
7
Executing a C Program

Compilation & Execution

Program Compilation Linking Loading Execution


Code

Compiler Linker Loader


Basic Structure of C Program 8

Documentation Section
Link Section
Definition Section
Global Declaration Section
main() Function Section
Declaration Part
Executable Part
Subprogram Section
Sample C Program 9
Character Set 10
Categories
Letters or Alphabets
Uppercase Letter (A to Z)
Lowercase Letter (a to z)
Digits (0 to 9)
Special Characters
White Spaces

The special characters are listed below:


+ - * / = % & # ! ? ^
" ' ~ \ | < > ( ) [ ]
{ } : ; . , _ (blank space)
Data Types 11
1. Primary Data Types
int
char
float
double
2. Derived Data Types
structures,
unions,
enumerations
3. User-defined Data Types
Primary 27

Data Types
int
E.g. int a; a = 5;
float
E.g. float miles; miles = 5.6;
double
E.g. double big; big = 312E7;

char
E.g. char letter; letter = ‘y';
Modifying the Basic Data Types 13
The lists of modifiers are:
signed
unsigned
short
long
signed, unsigned, short, long can be used with int.
signed, unsigned ca n be used with c har.
long ca n be used with double.
The amount of storage allocated is not fixed. ANSI has
the following rules
short int <=int <=long int
float <=double <=long double
How float & double are stored? 15
C language follows the IEEE 754 standard for representing floating
point values in the memory. Unlike the int type that is directly stored
in the memory in binary form, the float values are divided into two
parts: exponent and mantissa, and then stored.

According to IEEE 754, the floating point values consist of


3 components:
1.Sign Bit: This represents the sign of the number.
0 represents positive while 1 represents negative.

2.Biased Exponent: The exponent of the number


cannot be directly stored as it can be both negative
or positive, so we use a biased exponent where we
add some bias to the exponent.

3.Normalized Mantissa: Matissa is the number


in scientific notation, i.e. precision bits of the
number.
How to Store (65.125)10 to memory
16
Minimum & Maximum Number 17

Minimum Number: 1 10000000 00000000000000000000000


- -

Maximum Number: 0 11111111 111111111111111111111111


User-Defined Data Types 18
Syntax:
typedef existing_data_type new_name_for_existing_data_type;

Note:- We’ll study example of


typedef & Derived Data Type in later.
For example,
structure, union etc.
Tokens/Identifiers 19
Identifier is the word used for name given to variables, functions, constants etc. It can also
Identifiers be defined as a set of combinations of one or more letters or digits used to identify
Variables constants, variables, functions etc.
Keywords Rules for Valid Identifiers
1. First character should always be letter.
Constants 2. Both uppercase and lowercase letters may be used and are recognized as distinct.
Special Symbols 3. Only underscore (_) is allowed among special symbols and is treated as letter.
4. Space and other symbols are not valid.
5. Proper naming conventions should be followed.
6. Identifier’s should not any keyword

Valid Count
32 keywords available in C test23
auto double int struct break else long high_balance
switch case enum register typedef char extern _test
Invalid 4th
return union const float for goto if
order-no
short do signed void default sizeof continue error flag
static while volatile unsigned hi!there
Variables 10

A variable is a
named location in
memory that is used
to hold a value that
may be modified by
the program by time
to time.

General syntax:
typename var1, var2;
Scope of Variables 21
(Where Variables are declared?)
Variables will be declared
in 03 basic places:
inside functions,
in the definition of
function parameters,
outside of all functions.
These are local variables, formal
parameters and global variables
respectively.
In any scope, if there are multiple variables
with same name, then give priority to local
one.
Local Variables 22
Variables that are declared
inside a function are called
local variables.
For Example,
Local Variables contd. 23
Global Variables 14

Unlike local variables, global


variables are known throughout
the program and may be used by
any piece of code.
Constant
Constants 25

Constant - it does not change Primary Secondary


during the execution of a
program. For Example,
Integer Array

Real Po inter

Cha racter Structure

String Union
Primary Constants 26
Integer Constants
Integer constants are whole numbers without any
Valid 1234
fractional parts.
3456
Rules for constructing Integer constants:
-9746
An integer constant must have at least one digit.
Invalid 11.
It must not have a decimal point.
45,35
It could be either positive or negative
$12
If no sign precedes an integer constant is
assumed to be positive.
025
No commas or blank spaces are allowed within x248
an integer constant.
Integer Constants
allowed in C Integer
The allowable range is -2147483648 to
+2147483647 for 32 bit machine. For 16-bit Types of Integer Hexa-
machine it is -32768 to 32767. Constants Decimal Octal decimal
Primary Constants 27
Integer Constants: Decimal Integer Constant
Decimal integer constants:
Valid 1234
The allowable digits in a decimal integer
3456
constant are 0,1,2,3,4,5,6,7,8,9.
-9746
The first digit should not be 0.
Invalid 11.
Should at least one digit.
45,35
$12
025
x248
Primary Constants 28
Integer Constants: Octal Integer Constant
Octal integer constants:
The allowable digits in a octal constant are
0,1,2,3,4,5,6,7
Must have at least one digit and start with digit 0.

Valid 0245
-0476
+04013
Invalid 25 (does not start with 0)
0387( 8 is not an octal digit)
04.32(Decimal point is not allowed)
Primary Constants 29
Integer Constants: Hexadecimal Integer Constant
Hexadecimal integer constants:
The allowable digits in a hexadecimal constant
are 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
Must have at least one digit and start with 0x or 0X.

Valid 0x14AF
0X34680
-0x2673E
Invalid 0345 (Must start with 0x)
0x45H3 (H is not a hexadecimal digit)
Primary Constants 30
Floating Point/Real Constants
A floating point constant may be written in one or
two forms called fractional form or the exponent Valid +325.34
form. 426.0
Rules for constructing floating point / real constants: 32E-89
A floating-point constant must have at least one 35e+56
digit to the left and right of the decimal point. 1 (decimal point missing)
Invalid
It must have a decimal point. 1. (No digit following decimal digit)
-1/2 (Symbol / is illegal)
It could be either positive or negative .5 (No digit to the left of the
If no sign precedes an floating point constant is decimal) 56,8.94 (Comma not
assumed to be positive (by default we say). allowed)
-125.9e5.5
No commas or blank spaces are allowed.
(exponent cannot be fraction)
When value is too large or small, can be 0.158e+954 (exponent too
expressed in exponential form comprising large)
mantissa and exponent. E or e should separate
mantissa and exponent. The mantissa may have
upto 7 digits and the exponent may be
between -38 and +38.
Character Constants 31

A character constant is a single


alphabet, single digit, or a single
special symbol enclosed within
single quotes.

Remember golden rule:


single character single quote.
e.g. 'A' '5' '+' '?'
String C onstants 32

A string constant is a sequence of


alphanumeric characters enclosed in
double quotation marks whose
maximum length is 255 characters.

For example,
const char txt [ ] = "This is C
Programming language.";
"green", "My name &&&!!! ???", "$2525"
Declaration of Constants 33

Value of an identifier defined as constant, cannot be altered


during program execution.
Generally, the constant is associated with an identifier and
that name is used instead of actual number.
General Syntax
const typename identifier = const;
e.g. const float pi = 3.14159;
Another way to define constants is with the #define
preprocessor which has the advantage that it does not use
any storage (but who count bytes these days?).
#define Identifier Value
#define PI 3.1415
Operators 34

1. Unary operators
-, ++, - -, sizeof, (type)
e.g. -743, -a, -root (negating a number)
a++, a--, + + a, --a (Pre/Post - Inc/Dec-rement)
2. Binary operators
Arithmetic,
Assignment,
Relational,
Logical
3. Tertiary operators
(? option_condition_true : condition_condition_false)
Binary Operators : 35
Arithmetic Operators
+ for addition
- for subtraction
* for multiplication
/ for division
% for remainder operation,
modulo operator
Binary Operators : 36
Assignment Operators
= for assignment
+= add with destination and assign
-= deduct from destination and assign
*= multiply with destination and assign
/= divide the destination and assign
%= assign the remainder after dividing the destination
exp1 += exp2 is equivalent to exp1=exp1+exp2
exp1 -= exp2 is equivalent to exp1=exp1-exp2
exp1 *= exp2 is equivalent to exp1=exp1*exp2
exp1 /= exp2 is equivalent to exp1=exp1/exp2
exp1 %= exp2 is equivalent to exp1=exp1%exp2
Binary Operators : 37
Relational Operators
< less than
> greater than
<= less than or equals to
>= greater than or equals to

Equality operators are closely


associated with this group
== equal to
!= not equal to
Binary Operators : 38
Logical Operators
&& logical and (AND)
|| logical or (OR)

Given that , j = 7, c = ‘w’, k = 8


Expression Interpretation Value

(j >= 6) && (c == 'w') true 1

(k < 11)&& (j > 100) false 0

(j >= 6) || (c == 19) true 1

(c != ‘p') || ((j+k) < 10) true 1


Tertiary Operator 39
(Test expression) ? true_value :false_value;
E.g. (j<0) ? 0 : 100
Bitwise Operators 40
a = 15 = 0000 1111
Bitwise Logical b = 7 = 0000 0111
Operators
Bitwise Operator

a = 15 = 0000 1111
Bitwise b = 7 = 0000 0111
Shift AND = 0000 0111
Operators
a = 15 = 0000 1111
One’s Complement
Operator
b = 7 = 0000 0111
OR = 0000 1111
Bitwise Logical a = 15 = 0000 1111
Operators b = 7 = 0000 0111
Bitwise AND (&) XOR = 0000 1000
a = 15 = 0000 1111
Bitwise OR (|)
NOT = 1111 0000
Bitwise XOR (^)
b = 7 = 0000 0111
Bitwise NOT (~) NOT = 1111 1000
Bitwise Operators 41
Bitwise Shift Operators
Left Shift (<<)
Right Shift (>>)

a 0000 1111
Left Shift 0111 1000
by 3
Right 0000 0001
Shift by 3
Bitwise Operators 42
One’s Complement Operator

a = 12 = 0000 1100
~a = -13 = 1111 0011
Bitwise Operators 43
Two’s Complement
a = -13 = 1111 0011

~a = 0000 1100
+1

13 = 0000 1101
Pre/Post – Increment
/Decrement Operators
➢ Pre-Increment and Pre-Decrement
Operators:
➢ Pre-Increment (++variable): At first increases the
value of the variable by 1, then returns the updated
value.
➢ Pre-Decrement (--variable): At first decreases the
value of the variable by 1, then returns the updated
value.

➢ Post-Increment and Post-Decrement


Operators:
➢ Post-Increment (++variable): At first returns the
current value of the variable, then increases the value
by 1.
➢ Post-Decrement (--variable): At first returns the
current value of the variable, then decreases the
value by 1.
sizeof operator 45
Typecast Operator 46
➢ Typecast operator is also unary operator. It is used to change the data
type from one data type to another.
➢ This can be useful for managing data types in calculations, passing specific types to
functions, or controlling memory use.
➢ Typecasting is done by placing the desired type in parentheses before the variable
or value to be converted.

Syntax:(type) expression
e.g. (float) x/2;

Unary operators have higher


precedence. Also, the
associativity of the unary
operator is right to left.
Hierarchy of Operations 47
Precedence - which of the operator is to be executed first, BODMAS,
bracket is operated first.
Associativity is the preference of the operators (of same precedence level),
when there is tie between them. e.g. suppose we have Priority Operator
z = a + b*c 1st *, /, %
Then, operation occurs as z = a + (b*c) as * higher precedence than +
2nd +, -
But when the case is like
z = a*b + c /d, operation occurs as 3rd =

z = (a*b) + (c/d) i.e. multiplication is done first. Then (c/d) is evaluated. Then
only the two values are added. It happens so because *and / have higher
precedence than +. However, as * and / have same precedence level, * is
evaluated first, as the associativity of the arithmetic operators is from left to right,
hence whichever operator occurs first, that is evaluated.
Arithmetic Expression:
z = a + 2*b/c*d + 23 + a*a; a = 2, b = 3, c = 4, d = 5 then z = ?
Operator Precedence & Associativity 48

Postfix operator like a++, a– has greater priority than


Prefix operator like ++a, --a
Operator Precedence &
Associativity
49
Operator Precedence &
Associativity
50
What about function’s precedence??
51
➢ It is not defined whether
fun1() will be called first or
whether fun2() will be called.

➢ Behaviour is undefined and


output is compiler
dependent.

➢ NOTE: Here associativity will


not come into picture as we
have just one operator and
which function will be called
first is undefined.

➢ Associativity will only work


when we have more than one
operators of same
precedence.
Practice Problem
52
Sample C Program 53
Comments : Documentation 54
➢ Comments are used to provide the
description or documentation about the code
There are
you have written. 02 types of
comments
➢ Through commenting you can mention
important note, briefly explain behaviour of
the code, and other useful details.

➢ Comments help the developer understand the


logic/algorithm of the code if he/she revisits
the code after a long time.

➢ You can mention the comments anywhere you


want in the program, and the compiler will
ignore your comments.

➢ Comments do not affect programs or they do


not consume any program memory space.
They are not part of the final executable
generated. It is there just for the documentation
purpose.
File Inclusion
Directive #include

Preprocessor Directives:Link Mac ro Substitution


Directive
#define

➢ Preprocessor directives are instructions given to the #if


preprocessor (Compiler) to perform specific actions
before the actual compilation starts.

Preprocessor Directives
#elif

➢ They are not part of the C language itself but are #else

commands to the preprocessor. Conditional


#endif
➢ Preprocessor directives begin with the # symbol and do Directive

not end with a ; semicolon.


#ifdef

Types of Preprocessor Directives (Mainly) #ifndef

File Inclusion #under

#include
#pragma

Macro Substitution Miscellaneous


#error
Directives
#define
#line
File Inclusion : Link 56

➢ We can import the code from other source code files (like .h
files i.e. header files) into our document (current .c file)
making the code available to us to use.

➢ Let’s assume, we have a file named “my_header_file.h”


inside which a line of code is written like this…
char message[] = "Hello from another file\n";
➢ Now we will use the #include preprocessor
directive to include the my_header_file.h into
our main.c file and access the required info from it.
Difference Between 57

<stdio.h> and “my_header_file.h”


There are 02 types of header file
➢ Already Built-in (Use <header_name> after #include)
➢ User Defined (Use “header_name” after #include)

Some very popular Built-in Header files are…


Macro Substitution : Definition 58
➢ A macro is a fragment of code that has been
given a name. Whenever the name is used, it
is replaced by the contents of the macro.

➢ To create a macro, we use the #define


preprocessor directive, with a name and a
body.
#define MACRO_NAME Macro_Body

➢ Types of Macro:
➢ Object-like Macros: These resemble data objects or
constants.
➢ #define PI 3.14159
➢ #define MAX 100

➢ Function-like Macros: These resemble function calls and


can take arguments
➢ #define SQUARE(x) ((x) * (x))
➢ #define MAX(x,y) ( x>y ? x : y )
Global Declaration 59

There are 02 types of declaration…


➢ Global Variable Declaration
➢ Global Variables: Variables declared outside of any function, typically at the top of the file, are known as
global variables. These variables have global scope, meaning they can be accessed and modified by any
function within the same file.
➢ Scope: The scope of a global variable extends from the point of declaration to the end of the file.
➢ Lifetime: The lifetime of a global variable is the duration of the program's execution. They are created when
the program starts and destroyed when the program ends.

➢ Function Prototype Declaration


➢ Function Prototypes: A function prototype is a declaration of a function that specifies the function's name,
return type, and parameters (without the function body). Function prototypes are usually placed at the top
of the file or in header files to ensure that functions are declared before they are used.
➢ Forward Declaration: Function prototypes serve as forward declarations, allowing the compiler to know
about the function's existence and how to call it before its actual definition.
➢ Parameter Types: The prototype specifies the types of parameters the function expects, which helps the
compiler to perform type checking on function calls.
➢ Consistency: Using function prototypes ensures consistency in function declarations and definitions across
different files.
Examples : Global
Function Structure 61

Function is a block of code that performs a specific task and can be


called from other parts of the program.

A function consists of several components:

➢ Return Type: Specifies the type of value that the function will
return after execution.
➢ Common return types include int, void, float, char, etc.
➢ Example: int add(int a, int b){//code} – here, int is the return type,
indicating that the function will return an integer.

➢ Function Name: The name of the function, which is used to call it


from other parts of the code.
➢ Function names follow the same naming conventions as variable names.
➢ Example: int add(int a, int b) {//code} – here, add is the name of the
function.
Function Structure contd. 62

➢ Parameters (or Arguments): Input values that the function


takes to perform its operation.
➢ have types (e.g., int, float) and names, which act as placeholders for the values
passed/received during a function call.
➢ A function can have zero, one, or multiple parameters.
➢ Example: int add(int a, int b){//code} – here, int a, int b are the
parameters.
➢ Function Body: Contains the actual code or logic that the
function executes.
➢ Enclosed within curly braces { }.
➢ Example:
➢ Return Statement: Specifies the value that the function will
send back to its caller.
➢ Only needed if the return type is not void.
➢ Ends the function execution and returns control back to the caller.
➢ Example: return a + b; in the code shown above.
Function Structure Done! 63

➢ Function Declaration (or Prototype): A declaration tells the


compiler about the function's name, return type, and
parameters, without defining the function's body.
➢ Typically placed before the main() function or in a header file.
➢ Example: int add(int, int);

➢ Function Call: Executes the function by passing


arguments (values for parameters) to it.
➢ Can be done from main() or other functions within the program.
➢ Examaple: int sum = add(5,10);
64
Formal Params & Args 15
If a function is to use arguments, it must declare
variables that will accept the values
of the arguments.

Parameters are the variable names defined in a function


or method signature. They act as placeholders that specify
what kind of data the function expects. Parameters are
"inputs" expected by the function but do not hold any specific
value until the function is called.

Arguments are the actual values you pass to a function


when you call it. These values are "assigned" to the
parameters defined in the function.
[Click Me, If you don’t trust me !!!]
Escape Sequences 25
backslash symbol (\) is
considered an "escape
character":

It causes an escape from the


normal interpretation of string
so that the character is
recognized as one having a
special meaning.
Escape Sequences contd. 66
Q/A? 67

Thank You!

Feel Free To Ask Any Question !!!

You might also like