KEMBAR78
C Unit 1 Notes | PDF | Data Type | Integer (Computer Science)
0% found this document useful (0 votes)
29 views35 pages

C Unit 1 Notes

The document outlines the course structure for 'Programming in C', detailing objectives, outcomes, and content across five units, including algorithmic thinking, control structures, functions, pointers, strings, and file handling. It also includes resources for learning, advantages and disadvantages of algorithms and flowcharts, and a brief introduction to the C programming language. The course aims to equip students with foundational programming skills and problem-solving abilities using C.

Uploaded by

kanimozhi
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)
29 views35 pages

C Unit 1 Notes

The document outlines the course structure for 'Programming in C', detailing objectives, outcomes, and content across five units, including algorithmic thinking, control structures, functions, pointers, strings, and file handling. It also includes resources for learning, advantages and disadvantages of algorithms and flowcharts, and a brief introduction to the C programming language. The course aims to equip students with foundational programming skills and problem-solving abilities using C.

Uploaded by

kanimozhi
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/ 35

Course Hours/Week

Course Name Category C


Code L T P
24CS312 PROGRAMMING IN C PC 3 0 0 3
Regulation Nature of the Course Semester Data Book/Codes/Standards
R24 Programming I
Pre-requisite Course (s) Co-requisite Course(s)
PROGRAMMING IN C LABORATORY
Course Objective (s)
1 To understand the basics of algorithmic thinking and problem-solving.
2 To develop knowledge in the C programming language, including syntax, data types, and
operators
3 To develop programs using control flow, functions, pointers.
4 To understand the basics of file handling.
5 To be able to design, write, and debug C programs to solve problems in various domains.
Course Outcomes (s)
Upon completion of the course, students shall have ability to RBT
CO312.1 Understand programming using algorithms, flowcharts and pseudocode U
CO312.2 Develop a C program using datatypes, control flow and arrays AP
CO312.3 Implement decision-making using if-else, switch and control flow statements AP
CO312.4 Apply functions and recursion to solve problems systematically AP
CO312.5 Use pointers to implement the memory manipulation and allocation AP
CO312.6 Create, read, write, and append data to files in C AP
Course Contents

Unit – I ALGORITHMIC THINKING & INTRODUCTION TO C LANGUAGE 9


Algorithm -Definition, Characteristics of Algorithms. Constituents of algorithms: - Sequence, Selection
and Repetition. Flowchart/Pseudocode with examples.
Introduction To C Language: Structure of C Program, Data Types, Input and Output statements,
Operators, Precedence and Associativity of operators, Evaluation of Expressions, Type Conversions in
Expressions, Example programs for operator precedence and evaluating expressions.
Unit – II CONTROL STRUCTURES AND ARRAYS 9
Control structures: Decision statements; if and switch statement; Loop control statements: while, for
and do while loops, Jump statements: break, continue, goto statements, Example programs using
decision statements, looping statements and jump statements.
Arrays: Concepts, One dimensional array, declaration and initialization of one dimensional arrays, two
dimensional arrays, initialization and accessing, multi-dimensional arrays, programming examples
using arrays
Unit – III FUNCTIONS AND POINTERS 9
Functions: Function definition, Types of Functions: User defined and built-in Functions, Advantages of
User Defined Functions. Parameter passing in functions: Call by value, Call by reference, passing arrays
to functions, Recursion as a different way of solving problems, example programs to perform call by
value and reference, nested functions, recursion.
Pointers: Pointer basics, pointer arithmetic, pointers to pointers, generic pointers, array of pointers,
Functions returning pointers, Dynamic memory allocation, Example program to perform types of
pointers.
Unit – IV STRINGS AND USER DEFINED DATA TYPES 9
Strings: Array of characters, variable length character strings, input character strings, character library
functions, String Handling Functions, Arrays of Strings, Example programs to perform string length,
copy, concatenate and compare.
Structures and Unions: Structure definition, initialization, accessing structures, nested structures,
arrays of structures, Structures and functions, Self-referential structures, unions, typedef,
enumerations, Difference between structure and union with examples.
Unit – V FILE HANDLING 9
File Handling: Command Line Arguments, File Modes, Basic File Operations Read, Write and Append,
Example Programs. Random Access Using fseek, ftell and rewind Functions.
Total Hours 45
Learning Resources
Textbooks
1 Computer Science: A Structured Programming Approach Using C, B.A.Forouzan and
R.F.Gilberg, Third Edition, 2006.
2 ReemaThareja, “Programming in C”, Oxford University Press, Second Edition, 2016.
Reference Books
1 The C Programming Language by Brian Kernighan and Dennis Ritchie 2nd edition.
2 Computer Programming and Data Structures by E.Balagurusamy, Tata McGraw Hill, 2008.

3 Anita Goel and Ajay Mittal, “Computer Fundamentals and Programming in C”, 1st Edition,
Pearson Education, 2013.

Online Resources
1 Introduction to programming in C - Course (nptel.ac.in)

2 https://www.udemy.com/topic/c-programming/
ALGORITHM

The step-by-step procedure to solve any logical and mathematical problem is called an Algorithm.
 Should be written in simple English
 Each and every instruction should be precise and unambiguous.
 Instructions in an algorithm should not be repeated infinitely.
 Algorithm should conclude after a finite number of steps.
 Should have an end point
 Derived results should be obtained only after the algorithm terminates.

Qualities of a good algorithm


The following are the primary factors that are often used to judge the quality of the algorithms.
Time – To execute a program, the computer system takes some amount of time. The lesser is the
time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space.
The lesser is the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given problem, some
of these may provide more accurate results than others, and such algorithms may be suitable

Characteristics of an algorithm.

. The characteristics of an algorithm are:


 Well-ordered: the steps are in a clear order
 Unambiguous: the operations described are understood by a computing agent without further
simplification
 Effectively computable: the computing agent can actually carry out the operation
 Input — An algorithm accepts an input.
 Generality — An algorithm works in a set of inputs.
 Definiteness — Each instruction should be written in a simple and precise manner so that everyone
can understand it.

Advantages of Algorithm

 It is a step-wise representation of a solution to a given problem, which makes it easy to understand.


 An algorithm uses a definite procedure.
 It is not dependent on any programming language, so it is easy to understand for anyone even
without programming knowledge.
 Every step in an algorithm has its own logical sequence so it is easy to debug.

Constituents of algorithms
The three main constituents of algorithms—Sequence, Selection, and Repetition
Sequence:
Sequence means executing instructions in a specific order.
Example
Description: To find the sum of two numbers.
1. Start
2. Read the value of ‘a’
3. Read the value of ‘b’
4. Calculate sum=a+b
5. Print the sum of two number
6. Stop
Selection (if-else):
Selection means making decisions based on conditions.
It is also called as decision structure
Basic structure:
IFCONDITION is TRUE then
perform some action
ELSE IF CONDITION is FALSE then
perform some action
The conditional control flow is explained with the example of finding greatest of two numbers.
Example
Description: finding the greater number
1. Start
2. Read a
3.Read b
4. If a>b then
4.1. Print a is greater else
4.2. Print b is greater
5. Stop
Repetition (loops):
Repetition means repeating actions using loops.
Basic Structure:
Repeat untilCONDITIONis true Statements
Example
Description: to print the values from 1 to n
1. Start
2. Read the value of ‘n’
3. Initialize i as 1
4. Repeat step 4.1 until i< n
4.1. Print i
5. Stop

FLOWCHART:
A graphical representation of an algorithm. Flowcharts is a diagram made up of boxes, diamonds,
and other shapes, connected by arrows.
Each shape represents a step in process and arrows show the order in which they occur.
Table 1: Flowchart Symbols
S.No Name of Symbo Type Description
symbol l
1. Terminal Oval Represent the start and
Symbol stop of the program.

2. Input/ Parallelogram Denotes either input or


Outpu output operation.
t symbol
3. Process symbol Rectangle Denotes the process to
becarried

4. Decision Diamond Represents


symbol decisio
n making and branching
5. Flow lines Arrow lines Represents the
sequence of steps and
direction of flow. Used
to connect symbols.

6. Connector Circle A connector symbol is


represented by a circle
and a letter or digit is
placed in the circle to
specify the link. This
symbol is used to
connect flowcharts.

Rules for drawing flowchart


1. In drawing a proper flowchart, all necessary requirements should be listed out in
logical order.
2. The flow chart should be clear, neat and easy to follow. There should not be
any room for ambiguity in understanding the flowchart.
3. The usual directions of the flow of a procedure or system is from left to right or
top tobottom.
Only one flow line should come out from a process symbol.
4. Only one flow line should enter a decision symbol, but two or three flow lines,
one for each possible answer, cap leave the decision symbol.

5. Only one flow line is used in conjunction with terminal symbol.

6. If flowchart becomes complex, it is better to use connector symbols to reduce


thenumber of flow lines.
7. Ensure that flowchart has logical start and stop.

Advantages of Flowchart
Communication:
Flowcharts are better way of communicating the logic of the system.
Effective Analysis
With the help of flowchart, a problem can be analyzed in more effective way.
Proper Documentation
Flowcharts are used for good program documentation, which is needed for
variouspurposes.
Efficient Coding
The flowcharts act as a guide or blue print during the system analysis and program
development phase.
Systematic Testing and Debugging
The flowchart helps in testing and debugging the program
Efficient Program Maintenance
The maintenance of operating program becomes easy with the help of flowchart.
It helps the programmer to put efforts more efficiently on that part.
Disadvantages of Flowchart
Complex Logic: Sometimes, the program logic is quite complicated. In that case
flowchart becomes complex and difficult to use.
Alteration and Modification: If alterations are required the flowchart may require re-
drawing completely.
Reproduction: As the flowchart symbols cannot be typed, reproduction becomes
problematic.
PSEUDOCODE:

Pseudocode is an informal high-level description of the operating principle of a computer


program or algorithm. It uses the basic structure of a normal programming language, but is
intended for human reading rather than machine reading.
It is text based detail design tool. Pseudo means false and code refers to instructions written in
programming language.
Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax
rules. The pseudocode is written in normal English language which cannot be understood by the
computer.

Example:
Pseudocode: To find sum of two
numbers READ num1,num2
sum=num1+num2
PRINT sum
Basic rules to write pseudocode:
1. Only one statement per line.
Statements represents single action is written on same line. For example to
read theinput, all the inputs must be read using single statement.
2. Capitalized initial keywords
The keywords should be written in capital letters. Eg: READ, WRITE, IF,
ELSE, ENDIF, WHILE, REPEAT, UNTIL
Example:
Pseudocode: Find the total and average of three subjects
RAED name, department, mark1, mark2, mark3
Total=mark1+mark2+mark3
Average=Total/3
WRITE name, department,mark1, mark2, mark3
3. Indent to show hierarchy
Indentation is a process of showing the boundaries of the structure.
4. End multi-line structures
Each structure must be ended properly, which provides more clarity.
Example:
Pseudocode: Find greatest of two
numbers READ a, b
IF a>b then
PRINT a is greater
ELSE ENDIF
PRINT b is greater
5. Keep statements language independent.
Pesudocode must never written or use any syntax of any programming language.
Advantages of Pseudocode
 Can be done easily on a word processor
 Easily modified
 Implements structured concepts well
 It can be written easily
 It can be read and understood easily
 Converting pseudocode to programming language is easy as compared with flowchart
Disadvantages of Pseudocode
 It is not visual
 There is no standardized style or format

1. Algorithm & Flowchart to find the sum of two numbers

Algorithm

Step-1 Start

Step-2 Input first numbers say A

Step-3 Input second number say B

Step-4 SUM = A + B
Step-5 Display SUM
Step-6 Stop

6
2. Algorithm & Flowchart to find Area and Perimeter of Square

Algorithm

Step-1 Start
Step-2 Input Side Length of Square say L
Step-3 Area = L x L
Step-4 PERIMETER = 4 x L
Step-5 Display AREA, PERIMETER
Step-6 Stop

7
3.Algorithm & Flowchart to find the smallest of two numbers Algorithm

Step-1 Start
Step-2 Input two numbers say NUM1,NUM2

Step-3 IF NUM1 < NUM2 THEN


print smallest is NUM1 ELSE
print smallest is NUM2 ENDIF
Step-4 Stop

8
4.Addition of two numbers
Pseudo code Flowchart
READ a
Start
READ b
Result c=a+b
PRINT c

6. Find the greater number

Pseudocode Flow Chart


General Structure
IF condition THEN
Process 1 if(condition)
ENDIF
Process 1
Process 2
Example
READ aREAD b
Start
IF a>b THEN
PRINT a is greater
a=10,b=20

Print a is greater

9
6.Find the greater number

READ aREAD b Start

IF a>b THEN
PRINT a is greater a=10,b=20

Print a is greater

Print b is greater

10
11
C INTRODUCTION:
The programming language “C‟ was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories. Although C was initially developed for writing system software, today it has become such a
popular language that a variety of software programs are written using this language.
The greatest advantage of using C for programming is that it can be easily used on different types
of computers. Many other programming languages such as C++ and Java are also based on C which means
that you will be able to learn them easily in the future. Today, C is widely used with the UNIX operating
system.
APPLICATION OF C:
 OPERATING SYSTEM
 EMBEDDED SYSTEM
 GUI(GRAPHICAL USER INTERFACE)
 NEW PROGRAMMING PLATFORMS
 GOOGLE
 MYSQL
 ASSEMBLERS
 DRIVERS
 GAMING AND ANIMATION

FEATURES OF C PROGRAMMING/ADVANTAGES:
 C is a robust language with rich set of built in function.
 Programs written in c are efficient and fast.
 C is highly portable, programs once written in c can be run on another machine with minor or no
modification.
 C is basically a collection of c library functions, we can also create our own function and add it to
the c library.
 C is easily extensible.
DISADVANTAGE OF C:
 C doesnot provide OOP.
 There is no concepts of namespace in c.
 C doesnot provides binding or wrapping up of a single unit.
 C doesnot provide constructor and destructor.
STRUCTURE OF C:

1.Documentation section:
The documentation section consists of a set of comment lines
giving the name of the program, the author and other details, which the programmer
would like to uselater.
2. Link section:
The link section provides instructions to the compiler to link functions
from the system library such as using the #includedirective.
3. Definition section:
The definition section defines all symbolic constants such using
the #define directive.
4. Global declaration section: There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global
declaration section that is outside of all the functions. This section also declares all
the user-defined functions.
5. main () function section: Every C program must have one main function section. This
section contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all the variables used in the
executable part.
2. Executable part: There is at least one statement in the executable part. These two
parts must appear between the opening and closing braces. The program
execution begins at the opening brace and ends at the closing brace. The closing
brace of the main function is the logical end of the program. All statements in the
declaration and executable part end with a semicolon.
6. Subprogram section: If the program is a multi-function program then the subprogram
Section contains all the user-defined functions that are called in the main () function. User
defined functions are generally placed immediately after the main () function, although
they may appear in any order.

C PROGRAMMING: DATA-TYPES
A data-type in C programming is a set of values and is determined to act on those
values. C provides various types of data-types which allow the programmer to select the
appropriate typefor the variable to set its value.
The data-type in a programming language is the collection of data with values having
fixed meaning as well as characteristics. Some of them are integer, floating point, character etc.
Usually, programming languages specify the range values for given data-type.
C Data Types are used to:

• Identify the type of a variable when it declared.


• Identify the type of the return value of a function.
• Identify the type of a parameter expected by a function.
ANSI C provides three types of data types:

1. Primary(Built-in) Data Types:void, int, char, double and float.

2. Derived Data Types:Array, References, and Pointers.

3. User Defined Data Types:Structure, Union, and Enumeration.

Primary Data Types:

Every C compiler supports five primary data types:


void -As the name suggests it holds no value and is generally used for specifyingthe type of
function or what it returns. If the function has a void type, it means that the function will not
return any value.
int-Used to denote an integer type.
Char-Used to denote a character type.
float, double-Used to denote a floating point
type.
int*,float*,char*- used to denote a pointer type.
Declaration of Primary Data Types with variable name:
After taking suitable variable names, they need to be assigned with a data type. This is how the
data types are used along with variables:
Example: int
age; char
letter;
float height, width;

Derived Data Types


C supports three derived data types:
DATATYPES DESCRIPTION
Arrays Arrays are sequences of data items having homogeneous
values. They have adjacent memory locations to store
values.
References Function pointers allow referencing functions with a
particular signature.

Pointers These are powerful C features which are used to access the
memory and deal with their addresses.

User Defined Data Types

C allows the feature called type definition which allows programmers to define their own

identifier that would represent an existing data type. There are three such types:

Data Types Description

Structure It is a package of variables of different types under a single name. This is done
to handle data efficiently. “struct” keyword is used to define a structure.
Union These allow storing various data types in the same memory location. Programmers
can define a union with different members but only a single member can contain
a value at given time.
Enum Enumeration is a special data type that consists of integral constants and each of them
is assigned with a specific name. “enum” keyword is used to define the enumerated data
type.

Example for Data Types and Variable Declarations in C


#include <stdio.h> int main()
{

int a = 4000; // positive integer data type float b = 5.2324; // float data type
char c = 'Z'; // char data type
long d = 41657; // long positive integer data type long e = -21556; // long -ve integer data type
int f = -185; // -ve integer data type
short g = 130; // short +ve integer data type short h = -130; // short -ve integer data type
double i = 4.1234567890; // double float data type float j = -3.55; // float data type
}
Let's see the basic data types. Its size is given according to 32 bit architecture.
Data Types Memory Size Range

Char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

Short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

Int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to


2,147,483,647
signed long int 4 byte -2,147,483,648 to
2,147,483,647
unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte
double 8 byte
long double 10 byte
The storage representation and machine instructions differ from machine to Machine.
sizeof operator can use to get the exact size of a type or a variable on a particular platform.
Example: #include <stdio.h>
#include <limits.h>
int main() {
printf("Storage size for int is: %d \n", sizeof(int));
printf("Storage size for char is: %d \n", sizeof(char)); return 0
}
VARIABLES

Variables are containers for storing data values, like numbers and characters.

In C, there are different types of variables (defined with different keywords), for example:

 int - stores integers (whole numbers), without decimals, such as 123 or -123
 float - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Characters are surrounded by single quotes

Declaring (Creating) Variables


To create a variable, specify the type and assign it a value:

Syntax
type variableName = value;

Eg: int myNum = 15;

CONSTANTS
A constant is a value or variable that can't be changed in the program, for example: 10,
20, 'a', 3.4, "c programming" etc. There are different types of constants in C programming.

List of Constants in C

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint" etc

2 ways to define constant in C

There are two ways to define constant in C programming.

1. const keyword
2. #define preprocessor
C const keyword:
The const keyword is used to define constant in C programming.
Example:
const float PI=3.14;
Now, the value of PI variable can't be changed.

#include<stdio.h>
int main()
{
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}

Output:
The value of PI is: 3.140000

If you try to change the value of PI, it will render compile time error.#include<stdio.h>
int main(){
const float PI=3.14; PI=4.5;
printf("The value of PI is: %f",PI);
return 0;
OUTPUT:
Compile Time Error: Cannot modify a const object.
C #define preprocessor
The #define preprocessor directive is used to define constant or micro substitution. It can use any
basic data type.
Syntax: #define token value
Let's see an example of #define to define a constant.
#include <stdio.h>
#define PI 3.14
main()
{
printf("%f",PI);
}
Output:
3.140000
Backslash character constant:
C supports some character constants having a backslash in front of it. The lists of backslash
characters have a specific meaning which is known to the compiler. They are also termed as “Escape
Sequence”.

Example:
\t is used to give a tab
\n is used to give new line
Constants Meaning Constants Meaning
\a beep sound \n newline
\v vertical tab \\ backslash
\b backspace \r carriage
return
\’ single quote \0 null
\f form feed \t horizontal
\” double quote tab

KEYWORDS:
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. There are
only 32 reserved words (keywords) in C language.
A list of 32 keywords in c language is given below:

auto break case Char Const Continue default do Double else


enum extern float For Goto If int long register return
short signed sizeof Static Struct Switch typedef union unsigned void
volatile while

OPERATORS :
Operator is a special symbol that tells the compiler to perform specific mathematical or logical Operation.
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Ternary or Conditional Operators
Arithmetic Operators:
Given table shows all the Arithmetic operator supported by C Language. Lets suppose variable A
hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0

Relational Operators:
Which can be used to check the Condition, it always return true or false. Lets suppose variable
hold 8 and B hold 3.

Logical Operator:

Which can be used to combine more than one Condition?. Suppose you want to combined two

conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C). Here && is
Logical Operator.
Operator Example (int A=8, B=3, C=-10) Result
&& (A<B) && (B>C) False
|| (B!=-C) || (A==B) True
! !(B<=-A) True
Truth table of Logical Operator

C1 C2 C1&&C2 C1||C2 !C1 !C2


T T T T F F
T F F T F T
F T F T T F
F F F F T T
Assignment operators:
Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3.

Operator Example (int A=8, B=3) Result


+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
a=b Value of b will be assigned to a
Increment and Decrement Operator:
Increment Operators are used to increased the value of the variable by one and Decrement Operators
are used to decrease the value of the variable by one in C programs.
Both increment and decrement operator are used on a single operand or variable, so it is called as a
unary operator. Unary operators are having higher priority than the other operators it means unary operators
are executed before other operators.
Increment and decrement operators are cannot apply on constant.
The operators are ++, -- Type of Increment Operator
 pre-increment
 post-increment
pre-increment (++ variable):
In pre-increment first increment the value of variable and then used inside the expression (initialize
into another variable).
Syntax:
++variable;
post-increment (variable ++):

In post-increment first value of variable is used in the expression (initialize into another variable)
and then increment the value of variable.
Syntax:
variable++;
Example:
#include<stdio.h>
#include<conio.h>
void main() Output:
{ Pre-increment x::10
int x,i; i=10; i::10
x=++i; Post-increment x::10
printf(“Pre-increment\n”); i::11
printf(“x::%d”,x);
printf(“i::%d”,i);
i=10;
x=i++;
printf(“Post-increment\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
}
Type of Decrement Operator:
 pre-decrement
 post-decrement
Pre-decrement (-- variable):
In pre-decrement first decrement the value of variable and then used inside the expression (initialize
into another variable).
Syntax:
--variable;

Post-decrement (variable --):


In Post-decrement first value of variable is used in the expression (initialize into another variable)
and then decrement the value of variable.
Syntax:
variable--;

Example:
#include<stdio.h>
#include<conio.h> Output:
void main() Pre-decrement x::9
{ i::9
int x,i; i=10; Post-decrement x::10
x=--i; i::9
printf(“Pre-decrement\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
i=10;
x=i--;
printf(“Post-decrement\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
}

Ternary Operator:
If any operator is used on three operands or variable is known as Ternary Operator. It can be
represented with ? : . It is also called as conditional operator
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.
Conditional Operator flow diagram
Example:

find largest number among 3 numbers using ternary operator


#include<stdio.h>
void main()
{
int a,b,c,large; Output:
printf(“Enter any three numbers:”); Enter any three numbers: 12 67 98
scanf(“%d%d%d”,&a,&b,&c); The largest number is 98
large=a>b?(a>c?a:c):(b>c?b:c);
printf(“The largest number is:%d”,large);
}
Special Operators:
C supports some special operators

Operator Description

sizeof() Returns the size of an memory location.


& Returns the address of an memory location.
* Pointer to a variable.

EXPRESSION:
An expression is a sequence of operators and operands that specifies computation of a value.
For e.g, a=2+3 is an expression with three operands a,2,3 and 2 operators = & +
Simple Expressions & Compound Expressions:
An expression that has only one operator is known as a simple expression. E.g: a+2
An expression that involves more than one operator is called a compound expression.
E.g: b=2+3*5.

Types of Expressions in C
 Arithmetic expressions
 Relational expressions
 Logical expressions
 Conditional expressions
Arithmetic Expressions:
The arithmetic expression is evaluated in specific order considering the operator's precedence, and the
result of an expression will be based on the type of variable.
Eg: Z = 2 + 3 - (2 * 4)
Relational Expressions:
Relational operators >, <, ==,!= etc are used to compare 2 operands. Relational expressions consisting of
operands, variables, operators, and the result after evaluation would be either true or false.
Example:
C=a>b
Logical Expressions:
Relational expressions and arithmetic expressions are connected with the logical operators, and the result
after an evaluation is stored in the variable, which is either true or false.
Example:
C= (a+b)>c && a<b
Conditional Expressions:
The general syntax of conditional expression is:
Exp1? Exp2: Exp3
From the given above expressions, the first expression (exp1) is conditional, and if the condition is
satisfied, then expression2 will be executed; otherwise, expression3 will be performed.
Example:
2<3? 2 : 3
Expression evaluation:

In C language expression evaluation is mainly depends on priority and associativity.


Priority
This represents the evaluation of expression starts from "what" operator.

Associativity
It represents which operator should be evaluated first if an expression is containing more than one
operator with same priority.

Precedence of operators :

The precedence rule is used to determine the order of application of operators in evaluating sub
expressions. Each operator in C has a precedence associated with it. The operator with the highest
precedence is operated first.
Associativity of operators :
The associativity rule is applied when two or more operators are having same precedence in the sub
expression. An operator can be left-to-right associative or right-to-left associative.
EVALUATION OF EXPRESSION
At first, the expressions within parenthesis are evaluated. If no parenthesis is present, then the arithmetic
expression is evaluated from left to right. There are two priority levels of operators in C.
High priority: * /%
Low priority: + -
The evaluation procedure of an arithmetic expression includes two left to right passes through the entire
expression. In the first pass, the high priority operators are applied as they are encountered and in the
second pass, low priority operations are applied as they are encountered.
Rules for evaluation of expression:
• First parenthesized sub expressions are evaluated first.

• If parentheses are nested, the evaluation begins with the innermost sub expression.

• The precedence rule is applied to determine the order of application of operators in evaluating

sub expressions.
• The associability rule is applied when two or more operators are having same precedence in the sub
expression.
Suppose, we have an arithmetic expression as: x = 9 – 12 / 3 + 3 *2 -1
First Pass
Step 1: x = 9-4 + 3 * 2 – 1
Step 2: x = 9 – 4 + 6 – 1
Second Pass
Step 1: x = 5 + 6 – 1
Step 2: x = 11 – 1
Step 3: x = 10

But when parenthesis is used in the same expression, the order of evaluation gets changed.
For example, x = 9 – 12 / (3 + 3) * (2 –1)
First Pass
Step 1: x = 9 – 12 / 6 * (2 – 1)
Step 2: x= 9 – 12 / 6 * 1
Second Pass
Step 1: x= 9 – 2 * 1
Step 2: x = 9 – 2
Third Pass
Step 3:x=7

For example, we have an expression as:


x = 9 – ((12 / 3) + 3 * 2) –1
The expression is now evaluated as:
First Pass:
Step 1: x = 9 – (4 + 3 * 2) – 1
Step 2: x= 9 – (4 + 6) – 1
Step 3: x= 9 – 10 -1
Second Pass
Step 1: x= - 1 – 1
Step 2: x = -2
Note:
The number of evaluation steps is equal to the number of operators in the arithmetic expression.
TYPE CONVERSION IN EXPRESSIONS
Type conversion refers to converting one data type to another during the evaluation of an expression.
There are two types of conversions in C:
 Implicit (automatic) type conversion
 Explicit type conversion (type casting).

Implicit (automatic) type conversion


Implicit conversion is done automatically by the compiler when you assign a value of one type to
another.
For example, if you assign an int value to a float type:
Example
// Automatic conversion: int to float
float myFloat = 9;
printf("%f", myFloat); // 9.000000
Explicit Conversion
Explicit conversion is done manually by placing the type in parentheses () in front of the value.
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;
printf("%f", sum); // 2.500000
IO STATEMENT:
The I/O functions are classified into two types:
 Formatted Functions
 Unformatted functions

FORMATTED INPUT FUNCTION:


SCANF():
It is used to get data in a specified format. It can accept different data types.
Syntax:
scanf(“Control String

EXAMPLE:
#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,sum;
clrscr();
scanf(“%d %d”,&a,&b);
sum= a+b;
}
FORMATTED OUTPUT FUNCTION:
PRINTF():
The printf( ) function is used to print data of different data types on the console in a specified
format.
Syntax:
printf(“Control String”, var1, var2, …);
EXAMPLE:
#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,sum;
clrscr();
printf(“enter two numbers:”); Enter two numbers: 5 4
scanf(“%d %d”,&a,&b); Sum is 9
sum= a+b;
printf(“sum is:%d”,sum);
}
UNFORMATTED INPUT FUNCTION:
 getchar()
 getch()
 getche()
 gets()
getchar():
This function reads a single character data from the standard input.
Syntax:

variable_name=getchar();
Example:
#include<stdio.h>
OUTPUT:
#include<conio.h>
j
void main()
{
Char ch;
ch=getchar();
Printf(“%c”,ch);
}
getch():
getch() accepts only a single character from keyboard. The character entered through getch() is not
displayed in the screen (monitor).
Syntax:
variable_name = getch();
Example:
#include<stdio.h>
#include<conio.h>
void main()
OUTPUT:
{ Ch=a
Char ch;
ch=getch();
Printf(“ch=%c”,ch);
}
getche():
.getche() also accepts only single character, but getche() displays the entered character in the screen
Syntax:
variable_name = getche();
Example:
#include<stdio.h>
#include<conio.h>
void main()
OUTPUT:
{ a
Char ch; Ch=a

ch=getche();
Printf(“ch=%c”,ch);
}
gets():
This function is used for accepting any string through stdin (keyboard) until enter key
is pressed.
Syntax:
gets(variable_name);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
Char ch[10];
gets(ch); OUTPUT:
Printf(“ch=%s”,ch); cprogram
getch();
}
UNFORMATTED OUTPUT FUNCTION:
 putchar()
 putch()
 puts()
putchar():
This function prints one character on the screen at a time.
Syntax :
putchar(variable name);

Example:
#include<stdio.h>
OUTPUT:
#include<conio.h>
enter a character: j
void main() j

{
Char ch;
printf(“enter a character:”);
ch=getchar();
putchar(ch);
getch();
}
putch():
putch displays any alphanumeric characters to the standard output device. It displays only one
character at a time.
Syntax:
putch(variable_name);
Example:
include<stdio.h>
#include<conio.h>
void main()
{ OUTPUT:
char ch; Press any character:
clrscr(); Pressed character is: e
printf(“Press any character: ”);
ch = getch();
printf(“\nPressed character is:”);
putch(ch);
getch();
}
puts():
This function prints the string or character array.
Syntax:
puts(variable_name);
Example:
include<stdio.h>
#include<conio.h>
void main()
{ OUTPUT:
Enter a string: cprogramming
char ch[20]; cprogramming
clrscr();
puts(“enter a string”);
gets(ch);
puts(ch);
}

You might also like