0% found this document useful (0 votes)
21 views19 pages

Unit 1

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)
21 views19 pages

Unit 1

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/ 19

UNIT I

PROBLEM SOLVING AND BASICS OF C PROGRAMMING

Introduction, Algorithms, building blocks of algorithms, Algorithmic problem-solving steps; Simple Strategies and
notation for developing algorithms: Control flow, Flow charts, Pseudo codes, Programming languages; Introduction
to C; Structure of a C Program; Compiling and Executing C Programmes, C Tokens and character set, Keywords,
Identifiers, Basic Data types, Variables, Constants, Input/ Output statements, Operators, Type conversion and Type
Casting

1.1 Introduction
Computer is an electronic device which is used to store the data, manipulate the data as per given instructions and it
gives results quickly and accurately.
 Data: Data is a raw material of information.
 Information: Proper collection of the data is called information.
Steps in Problem Solving:
1. Define the problem
 A clear and concise problem statement is provided.
 The problem definition should specify the input and output
 Full knowledge about the problem is needed.
Example: To find the average of two numbers
2. Formulate the mathematical model.
 Any technical problem provided could be represented mathematically
 Full knowledge about the problem should be provided along with the underlying mathematical concept.
Example: Average = (Data1+Data2)/2
3. Develop an algorithm
 An algorithm is the sequence of operations to be performed
 It gives the precise plan for the problem
Example:
1. Start
2. Read the integers A and B from the user.
3. Calculate the sum: C = A + B.
4. Calculate the average: average = sum / 2.
5. Display the result.
4. Write the code for the problem
 The algorithm developed must be converted to any Programming Language
 The compiler will convert the program code to the machine code, which the computer can understand
5. Test the program.
Testing involves checking errors both syntactically and semantically
The errors are called bugs
When the compiler finds the bugs, it prevents compiling the code and reports the error
Checks the program by providing set of data for testing

1.2 Algorithms
An Algorithm is defined as a set of steps for solving a particular problem in a finite amount of time. It is a good
software engineering practice to design algorithms before we write a program.

Characteristics/Properties of Algorithm
 Precision: The steps of an algorithm are clearly defined.
 Uniqueness: The results of each step are uniquely defined and depend only on the input and the results of the
previous steps.
 Finiteness: The algorithm stops after a finite number of instructions are executed.
 Effectiveness: Every step in the algorithm should be easy to understand and can be implemented using any
programming language.
 Input: The algorithm takes input data, which can be in various formats, such as numbers, text, or images.
 Output: The algorithm produces output, which could be a result, a decision, or some other meaningful
information.
 Generality: The algorithm applies to a set of inputs.
Advantage
 It is a stepwise description of a solution, which makes easy to understand.
 It is not dependent on any programming language.
 It is easier for programmer to convert into an actual program.
Disadvantage
 It is difficult to show branching and looping statements.
 It is time consuming, algorithm needs to be developed first which is then converted to program.

1.2.1 Building Blocks of Algorithm


An algorithm is an effective method that can be expressed within a finite amount of space and time and in a well-
defined formal language for calculating a function. Starting froman initial state and initial input, the instructions
describe a computation that, when executed, proceeds through a finite number of well-defined successive states,
eventually producing "output" and terminating at a final ending state. The transition from one state to the next is
not necessarily deterministic; that algorithms, known as randomized algorithms.
An instruction is a single operation that describes a computation. When executed it convert one state to other.
Typically, when an algorithm is associated with processing information, data can be read from an input source, written
to an output device and stored for further processing. Stored data are considered as part of the internal state of the
entity performing the algorithm. In practice, the state is stored in one or more data structures.
The state of an algorithm is defined as its condition regarding stored data. The stored data in an algorithm are stored
as variables or constants. The state shows its current values orcontents.
Because an algorithm is a precise list of precise steps, the order of computation is always crucial to the functioning
of the algorithm. Instructions are usually assumed to be listed explicitly, and are described as starting "from the top"
and going "down to the bottom", an idea that is described more formally by flow of control.
In computer science, control flow (or flow of control) is the order in which individual statements, instructions or
function calls of an algorithm are executed or evaluated.
For complex problems our goal is to divide the task into smaller and simpler functionsduring algorithm design. So a
set of related sequence of steps, part of larger algorithm is known as functions.
An Algorithm is made up of three basic control flow:
 Sequence
 Selection
 Iteration

1.2.2 Algorithmic problem- solving steps


Steps involved in solving algorithmic problems.
Step 1: Understand the Problem Statement
Before you can design an algorithm, you need to have a clear understanding of the problem you are trying to solve.
Step 2: Identify the Appropriate Algorithm
After understanding the problem statement, the next step is to choose an appropriate algorithmic approach.
Step 3: Plan Your Solution
After choosing a proper algorithm, you must break down your problem into smaller sub-problems.
Step 4: Implement the Algorithm
Translate your planned solution into actual code using a programming language of your choice.
Step 5: Analyze Time and Space Complexity
After writing the code, you need to analyze the time and space complexity of the algorithm. Time complexity tells
you the execution time of your code and grows with the input size. Space complexity tells the memory usage of the
algorithm.
Step 6: Test and Debug
After writing your code, you must test it under various custom or predefined test cases. While testing, you can further
optimize your code by working on the area where it fails.
Step 7: Optimize and Refine
If your algorithm works correctly but fails for some of the test cases during the testing phase, then now you need to
optimize your code to meet the needs. Use optimal data structure to reduce time complexities and memory usage.
After optimizing, check for the test cases again to ensure that your code works perfectly under all the test cases.
Step 8: Documentation
After optimizing your code, you must ensure it is properly documented and safe for future reference.

1.3 Simple Strategies and notation for developing algorithms


1.3.1 Control flow
Control flow refers to the order in which statements within a program execute.
Control flow statements are fundamental components of programming languages that allow developers to control the
order in which instructions are executed in a program. They enable execution of a block of code multiple times,
execute a block of code based on conditions, terminate or skip the execution of certain lines of code, etc.
Sequence
Sequential control means that the steps of an algorithm are carried out in a sequential manner, where each step is
executed exactly once.

Example: Algorithm to find area of rectangle


Step 1: Read the length and breadth
Step 2: Calculate: area = length x breadth
Step 3: Print area
Selection
Algorithms can use selection to determine a different set of steps to execute based on a Boolean expression. If the
conditional test is true, one part of the algorithm will be executed, otherwise it will execute the other part of the
algorithm.

Example: Algorithm to find Greatest of two numbers


Step 1: Read first numbers A
Step 2: Read second number B
Step 3: IF(A>B) Print A is big
Else Print B is big
Iteration
Algorithms often use repetition to execute steps a certain number of times or until a certain condition is met.

Example: Print 'Hello world' 5 times


Step 1 : Start
Step 2 : Initialize the value of i as 1
Step 3 : Check the condition i less than or equal to 5, if the condition is true goto step 4 else goto step 7
Step 4 : Print “Hello World”
Step 5 : Increment the value of i by 1
Step 6 : Goto step 3
Step 7 : Stop

Types of Control Flow statements in Programming:

Control Flow Control Flow


Description
Statements Type Statement
Executes a block of code if a specified condition is true, and
if-else
Conditional another block if the condition is false.
Statements Evaluates a variable or expression and executes code based on
switch-case
matching cases.
Executes a block of code a specified number of times, typically
for
iterating over a range of values.
Looping
while Executes a block of code as long as a specified condition is true.
Statements
Executes a block of code once and then repeats the execution as
do-while
long as a specified condition is true.
Terminates the loop or switch statement and transfers control to
break
the statement immediately following the loop or switch.
Skips the current iteration of a loop and continues with the next
continue
iteration.
Jump Statements
return Exits a function and returns a value to the caller.
Transfers control to a labeled statement within the same function.
goto (Note: goto is generally discouraged due to its potential for
creating unreadable and error-prone code.)

1.3.2 Flow charts


A flowchart is a type of diagram that represents a workflow or process. A flowchart can also be defined as a
diagrammatic representation of an algorithm, a step-by-step approach to solving a task.
1.3.3 Pseudo codes
Pseudo code, as the name suggests, is a false code or a representation of code which can be understood easily. A
Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does not use any programming
language in its representation instead it uses the simple English language text as it is intended for human
understanding rather than machine reading.
Pseudocode is the intermediate state between an idea and its implementation (code) in a high-level language.

Before writing the pseudocode of any algorithm the following points must be kept in mind.
 Organize the sequence of tasks and write the pseudocode accordingly.
 At first, establishes the main goal or the aim.
Example:
This program will print factorial of a given number N.
 Use standard programming structures such as if-else, for, while, and cases the way we use them in
programming. Indent the statements if-else, for, while loops as they are indented in a program, it helps to
comprehend the decision control and execution mechanism. It also improves readability to a great extent.
 Use appropriate naming conventions. The human tendency follows the approach of following what we see.
If a programmer goes through a pseudo code, his approach will be the same as per that, so the naming must
be simple and distinct.
 Reserved commands or keywords must be represented in capital letters.
Example: if you are writing IF…ELSE statements then make sure IF and ELSE be in capital letters.
 Check whether all the sections of a pseudo code are complete, finite, and clear to understand and comprehend.
Also, explain everything that is going to happen in the actual code.
 Don’t write the pseudocode in a programming language.
 It is necessary that the pseudocode is simple and easy to understand.
INPUT number
SET factorial := 1, i := 1
WHILE i <= number DO
COMPUTE factorial := factorial * i
INCREASE i by 1
END LOOP
PRINT factorial
1.3.4 Programming Language
A programming language is a type of written language that tells computers what to do.
Examples are: Python, Ruby, Java, JavaScript, C, C++, and C#.
Programming languages are used to write computer programs and computer software. A programming language is
like a set of commands that tell the computer how to do things.
Usually, the programming language uses real words for some of the commands (e.g. "if... then... else...", "and", "or"),
so that the language is easier for a human to understand. Like any normal language, many programming languages
use punctuation. To make a program, a programmer writes commands in their chosen programming language and
saves the commands to a text file. This text file is called source code. Some programming languages, such as Python
and JavaScript, can be read by the computer right away. If not, the source code has to be compiled, which means that
the computer translates the source code into another language (such as assembly language or machine language) that
a computer can read, but which is much harder for a person to read.
Computer programs must be written very carefully. If a programmer makes mistakes, then the program might then
stop working, which is called "crashing". When a program has a problem because of how the code was written, this
is called a "bug". A very small mistake can cause very serious bugs.

1.4 Introduction to C
C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972.
It is a very popular language, despite being old. It was developed to overcome the problems of previous languages
such as B, BCPL, etc. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
Language Year Developed By
Algol 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K&RC 1978 Kernighan & Dennis Ritchie
ANSI C 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee
C99 1999 Standardization Committee
Characteristics of ‘C’
 High-level programming language
 Small size- has only 32 keywords
 C makes extensive use of function calls
 Well suited for structured programming
 Programs written in C are efficient and fast. This is due to its variety of data type and powerful operators
 The C compiler combines the capabilities of an assembly language with features of a high-level language.
 A-C program is basically a collection of functions that are supported by C library. We can also create our own
function and add it to C library
 Supports pointer to refer computer memory, array, structures and functions
 Core language as many programming languages are based on C
 C is a portable language
Structure of a C Program

Global Declaration
In C programming, a global declaration refers to the declaration of a variable or function that is accessible from any
part of the program, not just from the block or function where it was declared.
A global variable is declared outside of a function, typically at the top of the program file, and it can be used by any
function in the program.
For example
#include <stdio.h>
int count = 0; // global variable
void increment() {
count++;
}
int main() {
increment();
printf("count = %d\n", count); // prints "count = 1"
return 0;
}
Main() function
In C programming, the main() function is a special function that serves as the entry point for the program. When a C
program is executed, the operating system loads the program into memory and starts executing instructions from the
beginning of the main() function.
The main() function has a specific syntax in C:
int main() {

// code goes here


return 0;
}
The int in the function declaration indicates that the main() function returns an integer value to the operating system
when it finishes executing. The return 0; statement at the end of the function is used to indicate that the program
executed successfully.
Any code that you want to execute when the program starts should be placed within the main() function. For example,
you might print a message to the console, read input from the user, or call other functions that perform some task.
Now, what if we don’t have to return any value? For that case, we can add void as a return type on the place of int.
Here is the syntax:
void main(){

// code goes here


}
The void in the function indicates that no value is returned after the execution. You can use it with your sub programs
as well.
Here's an example of a simple C program that uses the main() function to print a message to the console:

#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}
This program uses the printf() function from the stdio.h library to print the message "Hello, world!" to the console.
When the program is executed, the main() function is called, the message is printed to the console, and the program
exits with a return value of 0.
Subprograms
In C programming, subprograms refer to functions or procedures that perform a specific task or set of tasks and can
be called from other parts of the program.
Functions in C are subprograms that return a value to the caller, while procedures (also known as void functions) do
not return a value. Both functions and procedures can have parameters that are used to pass data between the caller
and the subprogram.
Here's an example of a function in C:
#include <stdio.h>
int sum(int a, int b) {
return a + b;
}
int main() {
int x = 3, y = 4;
int result = sum(x, y);
printf("The sum of %d and %d is %d\n", x, y, result);
return 0;
}
Output: The sum of 3 and 4 is 7
In this example, the sum() function takes two integer parameters and returns their sum. The main() function calls the
sum() function with the values of x and y and then prints the result to the console.

1.5 Compiling and Executing C Programmes


The compilation is the process of converting the source code of the C language into machine code. As C is a mid-
level language, it needs a compiler to convert it into an executable code so that the program can be run on our
machine.
The C program goes through the following phases during compilation:
Step 1: Creating a C Source File
We first create a C program using an editor and save the file as filename.c
Step 2: Compiling
If there are no errors in our C program, the object file of the C program will be generated.
Step 3: Linking
The linker combines the object files with the library files to produce the final executable file.

1.6 C Tokens
Tokens in C is the smallest individual element in C and is the most important element to be used in creating a program
in C. Tokens in C is the building block or the basic component for creating a program in C language.
Tokens in C language can be divided into the following categories:
 Keywords
 Variables
 Constants
 Strings
 Special characters
 operators
1.6.1 Keywords in C
Keywords in C can be defined as the pre-defined or the reserved words having its own importance, and each
keyword has its own functionality. Since keywords are the pre-defined words used by the compiler, so they
cannot be used as the variable names. If the keywords are used as the variable names, it means that we are
assigning a different meaning to the keyword, which is not allowed. C language supports 32 keywords given
below:
Auto double int struct break else long switch
case enum register typedef char extern return union
const float short unsigned continue for signed Void
default goto sizeof volatile do if static while
1.6.2 Identifiers in C
Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in C are the user-defined
words. It can be composed of uppercase letters, lowercase letters, underscore, or digits, but the starting letter should
be either an underscore or an alphabet. Identifiers cannot be used as keywords. Rules for constructing identifiers in
C are given below:
 No other special characters except underscore could be use
 No two or more successive underscores could be used
 The first character of an identifier should be either an alphabet or an underscore, and then it can be followed
by any of the character, digit, or underscore.
 It should not begin with any numerical digit.
 In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that identifiers are case
sensitive.
 Commas or blank spaces cannot be specified within an identifier.
 Keywords cannot be represented as an identifier.
 The length of the identifiers should not be more than 31 characters.
 Identifiers should be written in such a way that it is meaningful, short, and easy to read.
1.6.3 Character Set in C
Any letter from English alphabet, digit or special symbol used to represent information. The character set of C can
therefore be given as:
English Alphabet: include both uppercase (A - Z) and lowercase (a - z) letters
Digits: include numerical digits from 0 – 9
Special Characters: include symbols such as
! ; “ < # = $ > % ? & @ ‘ [ ( /
) ] * ^ =+ _ , ` - { . | / } : ~
White Space Characters: The white spaces are characters that create space between words or symbols.
Character Meaning
\b Blank Space
\t Horizontal Tab
\v Vertical Return
\r Carriage Return
\f Form Feed
\n New Line
Escape Sequence in C: The purpose of the escape sequence is to represent the characters that cannot be used normally
using the keyboard. They include \a, \n, \\, \’, \”, \?, \0
1.6.4 Basic Data types
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer,
character, floating, double, etc. Each data type requires different amounts of memory and has some specific
operations which can be performed over it.

Detailed list:

1.6.5 Variables
A variable is the name of the memory location. It is used to store information. Its value can be altered and reused
several times.
Each variable has a unique identifier, its name, and a data type describing the type of data it may hold.
Syntax:
data_type variable_name;
The three components of declaring a variable
1. Variable Declaration:
The process of telling the compiler about a variable's existence and data type is known as variable declaration. It
notifies the compiler that a variable with a specific name and data type will be used in the program.
Syntax:
data_type variable_name;
3. Variable Initialization:
The process of reserving memory space for the variable to keep its contents during program execution is known as a
variable definition.
Syntax:
data_type variable_name=value;
Example:
#include <stdio.h>
void main() {
// Variable definition & Initialization
int age = 25;
float salary = 2500.5;
char initial = 'J';
}
Types of Variables in C
There are many types of variables in c:
1. local variable
2. global variable
Local Variable
 A variable that is declared inside the function or block is called a local variable.
 It must be declared at the start of the block.
void function1(){
int x=10;//local variable
}
Global Variable
A variable that is declared outside the function or block is called a global variable. Any function can change the value
of the global variable. It is available to all the functions.
It must be declared at the start of the block.
#include<stdio.h>
int value=20;//global variable
void main(){
int x=10;//local variable
}
1.6.6 Constants
A constant in C is a value that doesn't change as the program runs. Integers, floating-point numbers, characters, and
strings are just a few of the several types of constants that may be employed. When a constant has a value, it cannot
be changed, unlike variables. They may be utilized in various operations and computations and serve as the program's
representation of fixed values.

Integer Constants:
 The digits of an integer constant can range from 0 to 9.
 A decimal point should not be present in an integer constant.
 Positive or negative integer constants are also possible.
 You can add a suffix to a constant's name to define its type. 'U' or 'u' stands for unsigned, 'L' or 'l' for long,
or 'LL' or 'll' for long long.
Floating-Point Constants:
 A decimal point, an exponent, or digits can all be found in floating-point constants.
 Either exponential notation or decimal notation can be used to write them.
 'E' or 'e' can be used to denote an exponent.
 You can add a suffix to a constant's name to define its type. For instance, "F" or "f" stands for float and "L"
or "l" for long double.
Character Constants:
 Individual characters are represented as character constants when they are in single quotes.
 A single letter or an escape sequence, such as "n" for newline or "t" for tab, can be used as these characters.
String Constants:
 A series of characters surrounded in double quotes is represented by string constants.
 They are essentially character arrays that are closed with the null character "0".
Declaring a Constant:
There are two ways to define constant in C programming.
1. const keyword
2. #define preprocessor
1. const keyword
The const keyword is used to define constant in C programming.
const float PI=3.14;
Now, the value of PI variable can't be changed.
#include<stdio.h>
void main(){
const float PI=3.14;
printf("The value of PI is: %f",PI);
}
2. #define preprocessor
The #define preprocessor is also used to define constant. We will learn about #define preprocessor directive.
#define PI 3.14;
Now, the value of PI variable can't be changed.
#include<stdio.h>
#define PI 3.14;
void main(){
printf("The value of PI is: %f",PI);
}
1.7 Input/ Output statements
All input and output is performed with streams. A stream acts in two way. It is the source of data as well as destination
of data. There are two forms of streams Text Stream and Binary Stream.

Text Stream: It is a sequence of characters organized into lines. Each line consists of zero or more characters and
ends with the "newline" character
Binary Stream: Contains data values using their memory representation.
Streams are associated with physical device such as monitor and keyboard. Based on data flow between devices
streams are classified into input stream and output stream.
Formatting input and output
C language has standard libraries that allow input and output in a program. The stdio.h or standard input output
library in C that has methods for input and output.
printf()
The printf() method, in C, prints the value passed as the parameter to it, on the console screen.
Syntax:
printf(“control string”, variable list);
Control string takes the following format

Flags – specify the output justification

Width – specifies the minimum number of positions in the output


Precision – specifies the maximum number of characters to be printed after the decimal point
Length – explained using the following table

Specifier – used to define the type and the interpretation of the value of the corresponding argument.

Examples:
scanf()
The scanf() method, in C, reads the value from the console as per the type specified and store it in the given address.
Syntax:
scanf(“control string”, variable list);
Type Specifiers:

Output:
1.8 Operators
An operator is simply a symbol that is used to perform operations.
There are following types of operators to perform different types of operations in C language.
 Arithmetic Operators  Unary Operators  Assignment Operator
 Relational Operators  Conditional Operators  Comma Operator
 Equality Operators  Bitwise Operators  sizeof Operator
 Logical Operators  Shift Operators

1.8.1 Arithmetic Operators


Arithmetic operators carry out fundamental mathematical operations. The arithmetic operators in C are as follows:

with
1.8.2 Relational Operators
Relational operators assess the relationship between values by comparing them. They return either true (1) or false
(0). The relational operators in C are as follows:

1.8.3 Equality Operator


The equality operator verifies whether two operands are equal or not equal.

1.8.4 Logical Operators


Logical operators perform logical operations on boolean values and return either true (1) or false (0). Here are the
logical operators in C:
Logical AND Operator (&&): The logical AND operator returns true if both operands are true.

int a = 5;
int b = 3;
int result = (a > 3) && (b < 5); // result = 1 as both conditions are true
Logical OR Operator (||): The logical OR operator returns true if at least one of the operands is true
int a = 5;
int b = 3;
int result = (a > 3) || (b > 5); // result = 1 as the first condition is true
Logical NOT Operator (!): The logical NOT operator negates the value of the operand.

int a = 5;
int result = !(a > 3); // result = 0
1.8.5 Unary Operator
A unary operator is an operator used to operate on a single operand.
Unary Minus (-)
The unary operator is used to change the sign of any positive value to a negative value. It means it changes the
positive number to the negative, and a negative number becomes the positive number using the unary minus operator.
int a = 2;
int b = -(a);
Increment Operator (++)
It is the unary increment operator, which is denoted by the "++" symbol. The "++" symbol represents the operand's
value is increased by 1. It can be used in two ways, as the post-increment and the pre-increment.
Pre Increment: The pre-increment operator is represented as (++a), which means the value of variable 'a' is increment
by 1 before using operand to the expression.
For example:
x = 10;
A = ++x;
The initial value of x is 10, and using the pre-increment operator (++x) increases the operand value by 1 before
assigning it to the variable 'A'.
Post Increment: The (a++) symbol represents the post-increment operator, which means the value of 'a' is incremented
by 1 after assigning the original value to the expression or another variable.
For example:
x = 10;
A = x++;
Here the initial value of the x variable is 10 and using the post-increment operator (x++) to assign increment value
of the 'x' to the variable 'A'.
#include <stdio.h>
#include <conio.h>
void main ()
{
int x, y, a, b; // declare local variable
a = 10;
x = ++a; // It shows pre increment operator
printf (" Pre Increment Operator");
// Here the value of x is increased by 1.
printf (" \n The value of x is %d.", x);
printf (" \n The value of a is %d.", a);
b = 20;
y = b++; // It shows the post increment operator
printf (" \n\n Post Increment Operator");
printf (" \n The value of y is %d.", y);
// get updated value of b
printf (" \n The value of b is %d.", b);
}
Output:
Pre Increment Operator
The value of x is 11.
The value of a is 11.

Post Increment Operator


The value of y is 20.
The value of b is 21.
Unary Decrement Operator (--)
The unary decrement operator is opposite to the unary increment operator. The Unary decrement operator is
represented by the double minus (--) symbol, and it is used to decrease the operand value by 1 according to the
decrement's types. The Unary decrement operator is of two types: the Pre decrement operator and the Post Decrement
operator.
Pre Decrement: The pre decrement operator is denoted as (--a) symbol, meaning the operand value is decreased by
1 before assigning to another variable or expression.
Post Decrement: The Post decrement operator is denoted as (a--) symbol, which means the original value is decreased
by 1 after assigning to another variable or expression.
#include <stdio.h>
#include <conio.h>
void main ()
{
int x, y, a, b; // declare local variable
a = 10;
x = --a; // It shows pre decrement operator
printf (" Pre Decrement Operator");
// Here the value of x is decreased by 1.
printf (" \n The value of x is %d.", x);
printf (" \n The value of a is %d.", a);
b = 20;
y = b--; // It shows the post decrement operator
printf (" \n\n Post Decrement Operator");
printf (" \n The value of y is %d.", y);
// get updated value of b
printf (" \n The value of b is %d.", b);
}
Output:
Pre Decrement Operator
The value of x is 9.
The value of a is 9.

Post Decrement Operator


The value of y is 20.
The value of b is 19.
1.8.6 Conditional Operator
The conditional operator is also known as a ternary operator. The conditional statements are the decision-making
statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'.
As conditional operator works on three operands, so it is also known as the ternary operator.
Syntax
Expression1? expression2: expression3;
Example
#include <stdio.h>
void main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? printf("eligible for voting") : printf("not eligible for voting"); // conditional operator
}
Output:
Enter your age 19
eligible for voting
1.8.7 Bitwise Operator
The bitwise operators are the operators used to perform the operations on the data at the bit-level. It consists of two
digits, either 0 or 1.
Bitwise AND operator
Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands are written on both sides
of the (&) operator. If the corresponding bits of both the operands are 1, then the output of the bitwise AND operation
is 1; otherwise, the output would be 0.
a AND b = 0110 && 1110 = 0110
Bitwise OR operator
The bitwise OR operator is represented by a single vertical sign (|). Two integer operands are written on both sides
of the (|) symbol. If the bit value of any of the operand is 1, then the output would be 1, otherwise 0.
a OR b = 0110 || 1110 = 1110
Bitwise exclusive OR operator
Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both sides of the exclusive
OR operator. If the corresponding bit of any of the operand is 1 then the output would be 1, otherwise 0.
a XOR b = 0110 ^ 1110 = 0111
Bitwise NOT operator
It is represented by the symbol tilde (~). It takes only one operand or variable and performs complement operation
on an operand. When we apply the complement operation on any bits, then 0 becomes 1 and 1 becomes 0.
a = 0110; ~a = 1001
1.8.8 Assignment Operator
The assignment operator is used to assign the value, variable and function to another variable. Let's discuss the
various types of the assignment operators such as =, +=, -=, /=, *= and %=
Example of the Assignment Operators:
A = 5; use Assignment symbol to assign 5 to the operand A
B=A Assign operand A to the B
A = 20 \ 10 * 2 + 5; assign equation to the variable A
A -= B; A = A - B;
A *= B; A = A * B;
A /= B; A = A / B;
A %= B; A = A % B;
1.8.9 Comma Operator in C
In C, the comma operator guarantees that two or more expressions are evaluated sequentially from left to right, with
the value of the rightmost expression serving as the result of the whole expression.
Example
#include<stdio.h>
void main()
{
int y;
int a = (y=2,y+4);
printf("%d", a);
}
Output:
6
1.8.10 sizeof() operator
The sizeof() operator determines the size of the expression or the data type specified in the number of char-sized
storage units.
Example
#include <stdio.h>
void main()
{
double i=78.0; //variable initialization.
float j=6.78; //variable initialization.
printf("size of (i+j) expression is : %d",sizeof(i+j)); //Displaying the size of the expression (i+j).
}
Output:
size of (i+j) expression is : 8
1.8.11 Operator Precedence

1.9 Type conversion


If a data type is automatically converted into another data type at compile time is known as type conversion. The
conversion is performed by the compiler if both data types are compatible with each other.
Example
int a = 20;
Float b;
b = a; // Now the value of variable b is 20.000 /* It defines the conversion of int data type to float data
type without losing the information. */
1.10 Type casting
When a data type is converted into another data type by a programmer or user while writing a program code of any
programming language, the mechanism is known as type casting. The programmer manually uses it to convert one
data type into another. It is used if we want to change the target data type to another data type.
Destination_datatype = (target_datatype) variable;
Example
float b = 3.0;
int a = (int) b; // converting a float value into integer

You might also like