0% found this document useful (0 votes)
21 views

Module 1

computer fundamentals

Uploaded by

Khushi
Copyright
© © All Rights Reserved
Available Formats
Download as KEY, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Module 1

computer fundamentals

Uploaded by

Khushi
Copyright
© © All Rights Reserved
Available Formats
Download as KEY, PDF, TXT or read online on Scribd
You are on page 1/ 113

Module-1

OVERVIEW OF COMPUTER ORGANIZATION


AND PROGRAMMING FUNDAMENTALS
BY-
SHAHINA ANWARUL
Administration

Total number of lectures: 48 (4 credit course)


Mid Sem- 20%
End Sem- 50%
IA- 30%
2 Class tests - 30% (One before mid term and one before
end term)
2 quiz – 30% (One before mid term and one before end
term)
2 Assignment- 40% (One before mid term and one before
end term)
Passing Criteria

85 or above for Outstanding (O)


35 Marks is the minimum passing marks
Books

1. Yashwant Kanetkar, “Let Us C”.


2. Schaum Series, “Data Structure”.
3. Ellis Horowitz and Sartaz Sahni, “Data Structure using C”.
4. P.K. Sinha, “Computer Fundamentals”

Reference Books
E Balaguruswamy, “Programming in ANSI C”.
How to install TDM GCC on windows

TDM-GCC is a compiler suite for Microsoft Windows. TDM-GCC


is a GCC distribution on Windows. TDM stands for Twilight
Dragon Media, the project's name.
Steps:
1. Search for TDM GCC for windows version

2. https://jmeubank.github.io/tdm-gcc/download/
3. Download your window bit exe
4. Open wingw command prompt
5. Go to the directory where your c files are stored
6. gcc filename.c –o outputfilename
Overview of C Language

C is the programming language developed at AT & T's Bell


Laboratories of USA in 1972. It was written by a man name
Dennis Ritchie.When ever it comes to performance (speed of
execution), C is unbeatable.
Device drivers of new devices are always written in C. The
reason is that C provides you access to the basic elements of
the computer. It gives you direct access to memory of your
CPU through pointers. It allows you to manipulate and play
with bits and bytes.
If you want to create your own OS, you have to learn C.
Because famous OS like windows, ios, linux and unix have
thier major part written in C language.
History of C Standards

1) K&R C
In 1978, Brian Kernighan and Dennis Ritchie published the
first edition of The C Programming Language. This book,
known to C programmers as "K&R", served for many years as
an informal specification of the language.
2) ANSI C and ISO C (C89 or C90)
ANSI (American National Standards Institute) is the primary
organization for encouraging the development of technology
standards in the United States.
In 1983, the American National Standards Institute (ANSI)
formed a committee, to establish a standard specification of
C. In 1989, the C standard was rectified as ANSI X3.159-1989
"Programming Language C". This version of the language is
often referred to as ANSI C, Standard C, or sometimes C89.
History of C Standards

In 1990, the ANSI C standard (with formatting changes) was


adopted by the International Organization for
Standardization (ISO) as ISO/IEC 9899:1990, which is
sometimes called C90. Therefore, the terms "C89" and "C90"
refer to the same programming language.
3) C99
The C standard was further revised in the late 1990s, leading
to the publication of ISO/IEC 9899:1999 in 1999, which is
commonly referred to as C99
4) C11
The standard ISO/IEC 9899:2011, also known as C11 as the
final draft was published in 2011.
The latest C standard was released in June 2018 which is
ISO/IEC 9899:2018 also known as the C11
Example

void main()
{
}
The above program fails in g++ compiler as the return type
of main is void, but it compiles in Turbo C. How do we decide
whether it is a legitimate C program or not?
Example

“void main() {}”, the standard says following about


prototype of main().
#include<stdio.h>
int main()
{
int i = 1;
printf("%d %d %d\n", ++i, i++,
i);
return 0; 2 1 3 - using g++ 4.2.1 on Linux.i686
} 1 2 3 - using SunStudio C++ 5.9 on Linux.i686
2 1 3 - using g++ 4.2.1 on SunOS.x86pc
1 2 3 - using SunStudio C++ 5.9 on SunOS.x86pc
1 2 3 - using g++ 4.2.1 on SunOS.sun4u
1 2 3 - using SunStudio C++ 5.9 on SunOS.sun4u

Which compiler is right?


The answer to all such questions is C standard. In all such cases, we need
to see what C standard says about such programs.
What to do with programs whose behavior is undefined or
unspecified in standard?
As a programmer, it is never a good idea to use programming constructs
whose behavior is undefined or unspecified, such programs should always
be discouraged. The output of such programs may change with the
compiler and/or machine.
Number Systems

Computer uses a fixed number of bits to represent a piece of


data, which could be a number, a character, or others. A n-bit
storage location can represent up to 2^n distinct entities. For
example, a 3-bit memory location can hold one of these eight
binary patterns: 000, 001, 010, 011, 100, 101, 110, or 111.
Hence, it can represent at most 8 distinct entities.

1. Decimal number system :It has ten symbols: 0, 1, 2, 3, 4,


5, 6, 7, 8, and 9, called digits. It uses positional notation. That
is, the least-significant digit (right-most digit) is of the order of
10^0 (units or ones), the second right-most digit is of the order
of 10^1 (tens), the third right-most digit is of the order of 10^2
(hundreds), and so on. For example,
Number Systems

2. Binary (Base 2) Number System: Binary number system has


two symbols: 0 and 1, called bits. It is also a positional notation, for
example,
10110B = 1×2^4 + 0×2^3 + 1×2^2 + 1×2^1 + 0×2^0
We shall denote a binary number with a suffix B.
A binary digit is called a bit. Eight bits is called a byte (why 8-bit
unit? Probably because 8=2^3).
3. Hexadecimal (Base 16) Number System: Hexadecimal
number system uses 16 symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C,
D, E, and F, called hex digits. It is a positional notation, for example,
A3EH = 10×16^2 + 3×16^1 + 14×16^0
We shall denote a hexadecimal number (in short, hex) with a suffix
H. Some programming languages denote hex numbers with prefix
0x (e.g., 0x1A3C5F), or prefix x with hex digit quoted (e.g.,
x'C3A4D98B').
Number Systems

Each hexadecimal digit is also called a hex digit. Most


programming languages accept lowercase 'a' to 'f' as well as
uppercase 'A' to 'F'.
Computers uses binary system in their internal operations, as
they are built from binary digital electronic components.
However, writing or reading a long sequence of binary bits is
cumbersome and error-prone. Hexadecimal system is used as
a compact form or shorthand for binary bits. Each hex digit is
equivalent to 4 binary bits (nibble or nybble), i.e., shorthand
for 4 bits, as follows:
Important Number Conversions

Conversion from Hexadecimal to Binary


Replace each hex digit by the 4 equivalent bits, for examples,
A3C5H = 1010 0011 1100 0101B
102AH = 0001 0000 0010 1010B

Conversion from Binary to Hexadecimal

Starting from the right-most bit (least-significant bit), replace


each group of 4 bits by the equivalent hex digit (pad the left-
most bits with zero if necessary), for examples,
1001001010B = 0010 0100 1010B = 24AH
10001011001011B = 0010 0010 1100 1011B = 22CBH
It is important to note that hexadecimal number provides
a compact form or shorthand for representing binary bits.
Basic Organization of a Computer System
Algorithm
An algorithm is simply a solution to a problem. An algorithm
presents the solution to a problem as a well defined set of
steps or instructions.
Qualities of a good algorithm
Inputs and outputs should be defined precisely.
Each steps in algorithm should be clear and unambiguous.
Algorithm should be most effective among many different
ways to solve a problem.
An algorithm shouldn't have computer code. Instead, the
algorithm should be written in such a way that, it can be used
in similar programming languages.
Features of an Algorithm:
As we know that an algorithm takes some inputs, execute
some finite number of steps and gives an output. So, the
certain step involved in the algorithm must be executable.
It must generate some result.
After a specific period, it must cease to run.
pseudocode

A set of specific instructions which are very similar to


computer code, but not specific to any one computer.
Pseudocode allows to include control structures such as
while, if,if then-else, repeat-until, for, case etc., which are
present in many high level languages.
While algorithms can be written in natural language,
pseudocode is written in a format that is closely related to
high level programming language structures.
Additionally, transforming an algorithm presented in
pseudocode to programming code could be much easier than
converting an algorithm written in natural language.
Flow chart

A flowchart is a pictorial representation of an algorithm in


which the steps are drawn in the form of different shapes of
boxes and the logical flow is indicated by interconnecting
arrows.
The boxes represent operations and the arrows represent the
sequence in which the operations are implemented.
Flowchart Symbols
Flow chart
BASIS FOR
ALGORITHM FLOW CHART
COMPARISON

Basic Includes sequence of An information


steps which depicts the diagram made up of
procedure of the different shapes shows
solution. the data flow.

Comprehensibility Hard to understand Easily interpreted

Uses Text Symbols

Implements No rules are employed. Predefined rules are


implemented.

Debugging Easier Difficult

Ease of construction Perplexing Simple


Key Differences Between Algorithm and
Flowchart

An algorithm involves a combination of sequential steps to


interpret the logic of the solution. In contrast, a flowchart is
the pictorial illustration of the algorithm.
A flow chart is more understandable as compared to the
algorithm.
The algorithm is written in a language that can be perceived
by humans. On the other hand, the flowchart is made up
using different shapes and symbols.
There are no stringent rules are implemented in the
algorithms while the flowchart is abode by predefined rules.
Errors and bugs are easily detected in the algorithm as
compared to the flow charts.
Flow charts are simple to create. On the contrary, the
construction of the algorithm is complex.
Activity

Let's say that you have a friend arriving at the airport, and your
friend needs to get from the airport to your house. What are the
algorithms that you might give your friend for getting to your
home:
Possible Solutions?

The taxi algorithm:


Go to the taxi stand.
Get in a taxi.
Give the driver my address.
The call-me algorithm:
When your plane arrives, call me.
Meet me outside the airport.
The bus algorithm:
Outside baggage claim, catch bus for ISBT Dehradun
On reaching Dehradun ISBT catch bus for ballupur.
Get off on ballupur.
Walk two blocks north to my house.
Choosing the best Algorithm

All four of these algorithms accomplish exactly the same goal,


but each algorithm does it in completely different way. Each
algorithm also has a different cost and a different travel time.
Taking a taxi, for example, is probably the fastest way, but also
the most expensive. Taking the bus is definitely less expensive,
but a whole lot slower. You choose the algorithm based on the
circumstances.
Example-1

Ques: Write an algorithm, pseudocode and draw corresponding


flow chart to determine a student’s final grade and indicate
whether it is passing or failing. If final grade is less than 40,
student is considered as fail. The final grade is calculated as the
average of four marks.
Example-1

Ans: Algorithm:
1. Input set of marks
2. Find the average by adding the marks and dividing them by 4
3. if average is less than 40 then display fail otherwise pass
Pseudocode:
1. Input set of 4 marks a,b,c,d
2. Compute average as (a+b+c+d)/4
3. if (average<40) then

display fail
else display pass
Example-2

Q)Write an algorithm and pseudocode and draw a


corresponding flow chart to print the sum of the digits of
a given number
Ans: Algorithm:
1. Input a Number

2. Initialize Sum to zero

3. While Number is not zero

4. Get Remainder by Number Mod 10


5. Add Remainder to Sum
6. Divide Number by 10
7. Print sum
Example-2

pseudocode :
Step 1: Input N
Step 2: Sum = 0
Step 3: While (N != 0)
Rem = N % 10;
Sum = Sum + Rem;
N = N / 10;
Step 4: Print Sum
Example-2

Flow Chart
Questions?

Write an algorithm, pseudocode and draw corresponding


flow chart for the Questions given below:

1)Find the sum of all the multiples of 3 or 5 below 1000.


2) find all the roots of a quadratic equation ax2+bx+c=0
3) find the largest among three different numbers entered by
user.
4)Determine and Output Whether Number N is Even or Odd
5)Calculate the remainder, and the quotient of two given
numbers.
6) Generate even numbers between 100and 200.
Compiling and executing a ‘C’ code

#include <stdio.h>
#define SOMETHING "Hello World" Preprocessor
directive
int main()
{
/* Using a macro to print 'Hello World'*/
printf(“Hi”);
printf(SOMETHING);
return 0;
}
Compiling and executing a ‘C’ code

There are four main stages through which a source code


passes in order to finally become an executable.The four
stages for a C program to become an executable are the
following:
Pre-processing
Compilation
Assembly
Linking
Compiling and executing a ‘C’ code

1) Preprocessing: This is the very first stage through which a source code
passes. In this stage the following tasks are done:
Removal of Comments
Expansion of Macros
Expansion of the included files.
Conditional compilation

gcc -E -o Program1.i Program1.c

Analysis:
printf contains now “Hello World” rather than the macro SOMETHING
that’s because macros have expanded.
Comments are stripped off.
#include<stdio.h> is missing instead we see lots of code. So header
files has been expanded and included in our source file.
Compiling and executing a ‘C’ code

2) Compilation:In this phase compilation proper takes place.


The compiler (ccl) translates Test.i into Test.s.
File Test.s contains assembly code. You can explicitly tell gcc to
translate Test.i to Test.s by executing the following command.
gcc -S Program1.i
The command line option -S tells the compiler to convert the
preprocessed code to assembly language without creating an
object file. After having created Test.s we can see the content
of this file. While looking at assembly code we may note that
the assembly code contains a call to the external
function printf.
3) Assembly: Here, the assembler (as) translates Test.s into
machine language instructions, and generates an object
file Test.o. You can invoke the assembler at your own by
executing the following command.
gcc Program1.s -o Program1.o
Compiling and executing a ‘C’ code

The above command will generate Program1.o as it is specified


with -o option. And, the resulting file contains the machine
instructions for the classic "Hello World!" program, with an
undefined reference to printf.
4) Linking: This is the final stage in compilation of "Hello
World!" program. This phase links object files to produce final
executable file. An executable file requires many external
resources (system functions, C run-time libraries etc.). Regarding
our "Hello World!" program you have noticed that it calls
the printf function to print the 'Hello World!' message on console.
This function is contained in a separate pre compiled object
file printf.o, which must somehow be merged with
our Program1.o file. The linker (ld) performs this task for you.
Eventually, the resulting file helloworld is produced, which is an
executable. This is now ready to be loaded into memory and
executed by the system.
GCC Compilation
Process
Sample Code of C “Hello World” Program
Structure of a C program

Documentations (Documentation Section): The


Documentation section usually contains the collection of
comment lines giving the name of the program, author’s or
programmer’s name and few other details.
Preprocessor Statements (Link Section): It links
predefined functions in library files into your program
Global Declarations : used to define those variables that are
used globally within the entire program and is used in more
than one function
The main() function
Local Declarations
Program Statements & Expressions
User Defined Functions
Structure of a C program

* Comments */ This is a comment block, which is ignored by the


compiler. Comment is used anywhere in program to
add info about program or code block, which can
be helpful for programmer to understand the code
easily in feature.
#include<stdio. This is a preprocessor command to include the
h> header file stdio.h in the program before compiling
the source-code.
main() The main() is the main function where program
execution begins. Every C program must contain
only one main function.
Braces The Curly braces which shows how much the
main() function has its scope.
printf() It is a predefined (already written and compiled)
function in C, which prints text on the screen
return 0 At the end of the main function returns value 0.
Memory Management in C
Memory Management in C

A typical memory layout of a running process


1. Text Segment: which contains executable instructions. the
text segment is often read-only, to prevent a program from
accidentally modifying its instructions.
2. Initialized Data Segment: contains the global variables
and static variables that are initialized by the programmer.
Data segment is not read-only, since the values of the
variables can be altered at run time.
This segment can be further classified into initialized read-
only area and initialized read-write area.
Example: A global C statement int a=1 would be stored in
initialized read-write area. And a global C statement like
const char* a = “hello world” makes the string literal
“hello world” to be stored in initialized read-only area and the
character pointer variable string in initialized read-write
area.
Memory Management in C

3. Uninitialized Data Segment: Uninitialized data segment,


often called the “bss” segment, named after an ancient
assembler operator that stood for “block started by symbol.
Data in this segment is initialized by the kernel to arithmetic
0 before the program starts executing.
4. Stack: The stack area traditionally adjoined the heap area
and grew the opposite direction; when the stack pointer met
the heap pointer, free memory was exhausted.
The stack grows and shrinks as functions push and pop local
variables
There is no need to manage the memory yourself, variables
are allocated and freed automatically
The stack has size limits
Stack variables only exist while the function that created
them, is running
Memory Management in C

Variables created on the stack will go out of scope and are


automatically deallocated.
Much faster to allocate in comparison to variables on the heap.
Implemented with an actual stack data structure.
Stores local data, return addresses, used for parameter
passing.
Can have a stack overflow when too much of the stack is used
(mostly from infinite or too deep recursion, very large
allocations).
Data created on the stack can be used without pointers.
4. Heap: It is used on demand to allocate a block of data for use
by the program.
Slower to allocate in comparison to variables on the stack.
Can have fragmentation when there are a lot of allocations and
deallocations.
Memory Management in C

In C++ or C, data created on the heap will be pointed to by


pointers and allocated with new or malloc respectively.
WE use the heap if we don't know exactly how much data we
will need at run time.
Example to compare the size of
uninitialized data segment(bss)
Example to compare the size of
uninitialized data segment(bss)
Keywords

Keywords are predefined, reserved words used in programming


that have special meanings to the compiler. As C is a case
sensitive language, all keywords must be written in lowercase.
Here is a list of all keywords allowed in ANSI C.
Identifiers

In C language identifiers are the names given to variables,


constants, functions and user-define data. These identifier are
defined against a set of rules.
Rules for an Identifier
An Identifier can only have alphanumeric characters( a-z , A-Z ,
0-9 ) and underscore( _ ).
The first character of an identifier can only contain
alphabet( a-z , A-Z ) or underscore ( _ ).
Identifiers are also case sensitive in C. For
example name and Name are two different identifier in C.
Keywords are not allowed to be used as Identifiers.
No special characters, such as semicolon, period, whitespaces,
slash or comma are permitted to be used in or as Identifier.
Identifiers (Note)

It won’t give any compile error and prints “main”


C language standard (i.e. C99 and C11) defines a predefined
identifier therefore C compiler implicitly adds __func__
variable in every function so that it can be used in that
function to get the function name.
Syntax: static const char __func__[] = “function-name”;
Data types

In C programming, variables or memory locations should be


declared before it can be used.
Data types in c is used to declare variables or functions of
different types. The type of a variable determines how much
space it occupies in storage and how the bit pattern stored is
interpreted.
Data types

Basic Type:
1. Integer Type: Integers are whole numbers that can have
both positive and negative values but no decimal values.
Example: 0, -5, 10
In C programming, keyword int is used for declaring integer
variable. For example: int a;
Here, a is a variable of type integer.
Data types

We can declare multiple variable at once in C programming.


For example: int a, b;
2. float - Floating types: Floating type variables can hold real
numbers such as: 2.34, -9.382, 5.0 etc. You can declare a
floating point variable in C by using either float or double
keyword. For example:
float a;
double b;
double: It is used to store decimal numbers (numbers with
floating point value) with double precision.
Data types

3. char: The most basic data type in C. It stores a single


character and requires a single byte of memory in almost all
compilers.
Keyword char is used for declaring character type variables.
For example:
char test = 'h';
Here, test is a character variable. The value of test is 'h'.
The size of character variable is 1 byte.
Data types and sizes of Data types

Different data types also have different ranges upto which they
can store numbers. These ranges may vary from compiler to
compiler. Below is list of ranges along with the memory
requirement and format specifiers on 32 bit gcc compiler.
Online Lecture

Size-of operator, Modifiers, Use of values.h and limits.h


Variables

A variable is a name of memory location. It is used to store


data. Its value can be changed and it can be reused many
times.
It is a way to represent memory location through symbol so
that it can be easily identified.
type variable_list;
int a;
float b;
char c;
Here, a, b, c are variables and int, float, char are data types.
Rules to define variable name
Variable name must not start with a digit.
Variable name can consist of alphabets, digits and special
symbols like underscore _.
Variables

Blank or spaces are not allowed in variable name.


Keywords are not allowed as variable name.
Declaration and Definition of variable
Declaration of variables must be done before they are used in
the program. Declaration does two things.
It tells the compiler what the variable name is.
It specifies what type of data the variable will hold.
Definition of variable means to assign a value to a variable.
Definition specify what code or data the variable describes. A
variable must be declared before it can be defined.
Example
Local and Global variables

Local variables: Variables that are declared inside a function


or block are called local variables. Local variables are not
known to functions outside their own. Example: Here all the
variables a, b, and c are local to main() function.
Local and Global variables

Global variables: They are defined outside a function, usually


on top of the program. Global variables hold their values
throughout the lifetime of your program and can be accessed
inside any functions defined for the program.
Local and Global variables

Note: A program can have same name for local and global
variables but the value of local variable inside a function will
take preference.
Example:
Constant in C

Constant is a value that never changes.


Constant in C means the content whose value doesnot change
at the time of execution of the program.
It is considered as the best practice to define constants using
only upper-case names.
Syntax: const type constant_name; or const data_type
*variable_name;
We can define constants in C in two ways.
Using const keyword in variable declaration.
Using #define preprocessor directives.
Types:
Constant in C

Integer Constant:
An integer constant is a decimal(base 10), octal(base 8), or
hexadecimal(base 16) number that represents an integer
value.
Integer constants are used to represent integer value that
cannot be changed.
Example: 10, -121, 0, 0256, +14, 0x6, 0xA
Rules for constructing integer constant:
1) An integer constant must have at least one digit.2) It must
not have a decimal point.3) It can either be positive or negative.
4) No commas or blanks are allowed within an integer constant.
5) If no sign precedes an integer constant, it is assumed to be
positive.
Constant in C

Decimal Integer constant:• 0 to 9• E.g.: 49, 58, -62 …


Octal Integer constant:• 0 to 7• Add “0” before the value.•
E.g.: 045, 056, 067
Hexadecimal Integer constant:• 0 to 9 and A to F• Add 0x
before the value• E.g.: 0x42, 0x56, 0x67
Constant in C

Backslash Character Constants In C:


There are some characters which have special meaning in C
language.
They should be preceded by backslash symbol to make use of
special function of them.
Constant in C
Example:1(using const keyword)
Example-2(using #preprocessor directive)
Literal

A literal is a value that is expressed as itself. For example,


the number 25 or the string "Hello World" are both literals.
A constant is a data type that substitutes a literal. Constants
are useful in situations where a specific, unchanging value is
to be used at various times during the software program
Example: literal vs constant
Operators in C

Operators in C Programming (all valid operators available in C),


expressions (combination of operators, variables and constants)
and precedence of operators (which operator has higher priority
and which operator has lower priority).

Precedence and Associativity are two characteristics of


operators that determine the evaluation order of
subexpressions in absence of brackets.
Types

Operator Types:
Operators are the symbols which tell the computer to execute
certain mathematical or logical operations.
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment and Decrement operators
Conditional operators
Bitwise operators
Special operators
Arithmetic Operators

Note: ‘/’ is integer division which only gives integer part as


result after division. ‘%’ is modulo division which gives the
remainder of integer division as result.
Operators
Relational Operators

Relational Operators
Relational operators are used when we have to make comparisons. C
programming offers 6 relational operators.

Relational operators are most commonly used in decision statements


like if, while, etc. Some simple relational expressions are:
Example
Note:

Assignment operator and Equality operator is entirely


Different. Assignment operator(=) is used to Assign
Values while Equality(==) operator is used to compare
the Two Expressions.
Logical Operators:

There are 3 logical operators in C language AND(&&), OR(||)


and NOT(!)
Logical Operators in C programming language combines
multiple boolean expressions. If we want to check more than
one condition, then we need logical Operators.
Logical Operators always produces boolean results, either
TRUE(non-zero value) or FALSE(zero value).
Example: If roll_no of a student is greater than 34 and less
than 72 then student belongs to batch 2We can implement
above mentioned condition using logical operator as follows:
if((roll_no >34) && (roll_no <72))
AND : Returns true, If both operands are true otherwise
false.
OR : Returns false If both operands are false, otherwise true.
NOT : Returns true if operand is false and Returns false if
operand is true.
Example
Short-Circuiting in Logical Operators:

In case of logical AND, the second operand is not evaluated


if first operand is false. For example, program 1 below
doesn’t print “C language” as the first operand of logical AND
itself is false.
Short-Circuiting in Logical Operators:

In case of logical OR, the second operand is not evaluated if


first operand is true. For example, program 1 below doesn’t
print “C Language” as the first operand of logical OR itself is
true.
Bitwise Operators

C is a middle level language, it support many operations


which can be performed in assembly language like operations
on bits.
Bitwise operators performs bit-by-bit operations on operands.
There are six bitwise operators supported in C programming
language.
Bitwise Operators

Bitwise Operators can only be applied on char and integer


operands. We cannot use bitwise operators with float, double,
long double, void and other user define complex data types.
Bitwise Shift Operators

The shift operators shift their first operand left (<<) or right
(>>) by the number of positions the second operand
specifies.
Both operands must be integral values. These operators
perform the usual arithmetic conversions; the type of the
result is the type of the left operand after conversion.
Bitwise Shift Operators

The shift operators shift their first operand left (<<) or right
(>>) by the number of positions the second operand
specifies.
Left shift is useful in implementing multiplication with
powers of 2 and Right shift is used to implement division
with powers of 2.class Test { public static void main(String
args[]) { int y = 4; System.out.println(y>>1); }
}
We can also check whether a number is even or odd by AND
ing operation with 1. Because if lowest order bit is set
number is odd otherwise it is even.
Increment and decrement operators

Increment: The ‘++’ operator is used to increment the value


of an integer. When placed before the variable name (also
called pre-increment operator), its value is incremented
instantly. For example, ++x. And when it is placed after the
variable name (also called post-increment operator), its value is
preserved temporarily until the execution of this statement and
it gets updated before the execution of the next statement. For
example, x++.
Decrement: The ‘–‘ operator is used to decrement the value of
an integer. When placed before the variable name (also called
pre-decrement operator), its value is decremented instantly. For
example, –x. And when it is placed after the variable name (also
called post-decrement operator), its value is preserved
temporarily until the execution of this statement and it gets
updated before the execution of the next statement. For
example, x–.
Example2

How does printf("%d %d %d", i, ++i, i++) evaluate? Does it


operate from left to right or from right to left?
The answer is undefined.
printf("%d %d %d", i, ++i, i++)
There are two modifications of i within a single sequence point,
it called undefined behavior.
Decision control statements

There comes situations in real life when we need to make some


decisions and based on these decisions, we decide what should we
do next. Similar situations arises in programming also where we
need to make some decisions and based on these decision we will
execute the next block of code.

Decision making statements in programming languages decides the


direction of flow of program execution. Decision making statements
available in C:

if statement
if..else statements
nested if statements
if-else-if ladder
switch statements
if statement

if statement is the most simple decision making statement. It is used to


decide whether a certain statement or block of statements will be executed
or not i.e if a certain condition is true then a block of statement is executed
otherwise not.
Syntax:

if(condition)
{
// Statements to execute if
// condition is true
}

if(condition)
statement1;
statement2;

.
Flow chart
if-else

The if statement alone tells us that if a condition is true it will execute a


block of statements and if the condition is false it won’t. But what if we
want to do something else if the condition is false. Here comes the else
statement. We can use the else statement with if statement to execute a
block of code when the condition is false.
Syntax:

if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example
Example-1
Example-2
Example-2
switch case

Note:

1. expression in the switch must result in integer value.2.


Maximum one of the label values match the expression value in
order for the corresponding statements to execute. Otherwise
default statement executes if present in the switch statement.3.
break statement must be in the end in each case.4. break
causes the execution to jump out of the switch to the statement
immediately following the switch.
Example1

In C switch statement, the expression of each case label must


be an integer constant expression.
The expression used in switch must be integral type ( int,
char and enum). Any other type of expression is not allowed.
Example2

All the statements following a matching case execute


until a break statement is reached.
Example3

The statements written above cases are never


executed
Two case labels cannot have same value
Ternary Statement
Ternary statement or Ternary operator is like if-else statement in
its functioning. However, its syntax differs from if-else’s syntax.
Advantage of Ternary Operator
Using ?: reduce the number of line codes and improve the
performance of application.
Syntax
expression-1 ? expression-2 : expression-3
In the above symbol expression-1 is condition and expression-2
and expression-3 will be either value or variable or statement or
any mathematical expression. If condition will be true
expression-2 will be execute otherwise expression-3 will be
executed. Example
a<b ? printf("a is less") : printf("a is greater");
Example

# include <stdio.h>
int main()
{
int a, b, c, big ;
printf("Enter three numbers : ") ;
scanf("%d %d %d", &a, &b, &c) ;
big = a > b ? (a > c ? a : c) : (b > c ? b : c) ;
printf("\nThe biggest number is : %d", big) ;
}
Loops

3 type of Loops in C language


while loop
for loop
do-while loop

while loop
while loop can be addressed as an entry control loop. It is
completed in 3 steps.
Variable initialization.( e.g int x=0; )
condition( e.g while( x<=10) )
Variable increment or decrement ( x++ or x-- or x=x+2 )
Loops

In for loop we have exactly two semicolons, one after


initialization and second after condition. In this loop we can
have more than one initialization or increment/decrement,
separated using comma operator. for loop can have only
one condition.
The for loop is executed as follows:
It first evaluates the initialization code.
Then it checks the condition expression.
If it is true, it executes the for-loop body.
Then it evaluate the increment/decrement condition and
again follows from step 2.
When the condition expression becomes false, it exits the
loop.
Loops

The for loop seems most appropriate when number of


iteration are known in advance, for example, counting array
elements. But, there could be many complex problems where
number of iterations depend upon a certain condition and
can't be predicated beforehand, in those situation
programmers usually prefer to use while loop.
Loops

do while loop
In some situations it is necessary to execute body of the loop
before testing the condition. Such situations can be handled
with the help of do-while loop. do statement evaluates the
body of the loop first and at the end, the condition is checked
using while statement. It means that for at least one
time ,the body of the loop will be executed, even though the
starting condition inside while is initialized to false. General
format of do-while loop is,
In for loop, initialization, condition and adjustment
statements are all put together in one line which make loop
easier to understand and implement. While in the while loop,
initialization is done prior to the beginning of the loop.
Conditional statement is always put at the start of the loop.
While adjustment can be either combined with condition or
embedded into the body of the loop. For example:

You might also like