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

C Programming (1,2,3)

The document provides an introduction to programming and problem solving using C language. It discusses the seven phases of problem solving: definition, analysis, designing a solution using algorithms and flowcharts, coding, testing and debugging, documentation, and maintenance. It then describes algorithms and flowcharts, the process of coding, testing code for errors, and documenting programs. The remainder of the document introduces C programming, its characteristics, applications, advantages, basic structure, and execution process. It concludes with the components that make up the C language including its character set, tokens like keywords and identifiers, variables, and data types.

Uploaded by

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

C Programming (1,2,3)

The document provides an introduction to programming and problem solving using C language. It discusses the seven phases of problem solving: definition, analysis, designing a solution using algorithms and flowcharts, coding, testing and debugging, documentation, and maintenance. It then describes algorithms and flowcharts, the process of coding, testing code for errors, and documenting programs. The remainder of the document introduces C programming, its characteristics, applications, advantages, basic structure, and execution process. It concludes with the components that make up the C language including its character set, tokens like keywords and identifiers, variables, and data types.

Uploaded by

Ruthvik Revanth
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Unit I: INTRODUCTION TO PROGRAMMING

Problem Solving : The task of expressing the solution of complex problems in terms of
simple operations understood by the computer.

Problem solving has the following phases:


1. Problem definition
2. Problem analysis
3. Designing of a solution using the design tools (algorithm and flowchart)
4. Coding
5. Testing and debugging
6. Program documentation
7. Program maintenance

1. Problem definition : The problem should be defined in user’s language so that the
problem can be clearly understood. A proper definition helps in generating a proper solution
for the problem. In this step analysis of what should be done is decided.

2. Problem analysis : In this step the requirements of the problem are understood. The
requirements such as input-output, time constraints, processing requirements, memory
limitations etc are understood and the method to solve the problem is selected.

3. Designing of a solution : After defining and analyzing the problem, defining the solution is
necessary. The process of designing a solution involves certain design tools such as
algorithm and flowchart.

Algorithm
An algorithm is a step-by-step procedure to solve a given problem. The word algorithm is
derived from the name of 9th century Arab mathematician Al Khowarizmi, who developed
methods for solving problems which used specific step-by-step procedure.

Steps involved in developing an algorithm


1. Clearly understand the problem statement.
2. Study the outputs to be generated so that the input can be specified.
3. Design the process which will produce the desired results.
4. Refine the process.
5. Test the algorithm with different inputs to get desired output.

Flowchart
A flowchart is a pictorial or graphical representation of a solution to a given problem.
Types of flowchart

Flowcharts are classified into two categories


1. Program Flowcharts 2. System Flowcharts

Compiled By – Poonam Warnulkar Page 1


Program Flowchart presents a diagrammatic representation of the sequence of the program
instructions and the system flowchart shows the flow of data throughout the data
processing system.

Steps involved in developing a flowchart


1. Clearly understand the problem statement.
2. Study the outputs to be generated so that the input can be specified.
3. Design the process which will produce the desired results.
4. Refine the process.
5. Test the flowchart with different inputs to get desired output.

Symbols used in flowchart

Symbol Purpose

Terminal
Start and Stop

Input/ Output
Input or output of data

Processing
Represents calculations, data manipulations
or information processing
Decision Making
Represents comparison, a decision that
determines alternate paths to be followed

Predefined process
A group of operations not detailed in the
particular set of flowcharts
Connector
An entry from, or an exit to another part of
the flowchart
Flow direction
The direction of processing

4. Coding : The process of writing program instructions for the given problem. Each step of
the solution is converted to program instructions.

5. Testing and debugging: The process of detecting and correcting the errors in a program.

The following terms are associated with debugging

Source code: The program written by the user.

Object code: The program generated by the compiler.

Compiled By – Poonam Warnulkar Page 2


Compiler: System software to convert the source code to object code.

Syntax error: Error that occurs due to wrong usage of syntax

Semantic error: Error that occurs due to wrong logic.

Runtime error: Error that occurs due to wrong input data.

6. Program documentation :The written text and comments that make a program easier for
others to understand, use and modify.

7. Program maintenance : The process of updating or providing new versions of a program


so that the program meets the present requirements of the user.

Programming : The process of converting the representation of a solution into set of


instructions that produce desired results.

Program : A sequence of instructions to be performed by the computer.

Introduction to C programming

• C is a high-level, general-purpose, procedural, structured programming language.


• In 1967, Martin Richards developed BCPL (Basic Combined Programming Language)
for writing system software.
• In 1970, Ken Thompson developed B language to create early versions of UNIX OS.
• In 1972, C was developed by Dennis Ritchie at Bell Laboratories of USA.
• C language has evolved from BCPL(Basic Combined Programming Language) and B
Language.
• In 1978, Brian Kerninghan and Dennis Ritchie published a book with detailed
description of C called “The C Programming Language” which made C language
popular, hence C is also referred as K & R C.
• In 1988, the language was standardized by American National Standards Institute
(ANSI).

Characteristics of C
• C is a structured language where the program can be modularized.
• C is a general purpose programming language.
• C helps is development of system software and application software
• C is a portable language , program written in one machine can be run of different
machines with little or no modifications.
• C has rich set of built-in functions.
• C has limited set of reserved words.
• C is a flexible language, there is no rigid format.

Compiled By – Poonam Warnulkar Page 3


Applications of C
• C language is used to develop system software such as operating systems, compilers,
interpreters, assemblers and editors.
• C language is also used to develop application programs such as word processors,
spreadsheets, CAD applications, animations and games.

Advantages of C
1. C being a structured language helps in modularizing the program i.e., dividing a
problem into number of modules.
2. C compiler is compact and can be easily ported on small machines including PC’s.
3. C is a middle level language, hence suitable for developing system software and
application software.
4. It is a portable language i.e., programs written in one machine can be easily run on
other machine without much modification.
5. Programs written in C execute faster than compared to other languages.
6. C provides rich set of built-in functions.
7. It is easily expandable .
8. It can deal with bits, bytes, word and addresses.
9. It has very few fundamental data types and keywords.
10. It has wide variety of derived data structures such as arrays, structures, unions and
pointers.

Basic Structure of C Program


Documentation Section →Comments
Link Section → Library file access
Definition Section → Defining symbolic constants
Global declaration Section → Global variable declared
main() → function heading
{
Declaration part → Variable declaration
Executable part → Statements in C
}
Sub-routine Section → User defined functions

Executing of a C program
Executing of a C program has four phases:
1. Editing or creating phase : C programs can be written using Turbo C, Microsoft C etc.
In this phase the user types the program in the editor. This is called a source
program.
2. Compilation phase : In this phase the compiler checks the program for errors and
once all the errors are corrected the program is converted to machine
understandable form called the object program.
3. Linking phase: In this phase, the program is linked with the C-library. The compiled
linked program is called the executable code.
4. Execution phase : In this phase the program is executed.

Compiled By – Poonam Warnulkar Page 4


Components of C language

1. The character set


2. Tokens
i. Keywords
ii. Identifiers
iii. Constants
iv. Operators
v. Punctuations
3. Variables
4. Data types

Character set : It is a set of valid characters that a programming language can be identified.
In C language characters are grouped into the following categories,
1. Letters(all alphabets a to z & A to Z).
2. Digits (all digits 0 to 9).
3. Special characters, ( : ; “ . , + * - / & )
4. White spaces.

Keywords
Keywords are preserved words that have special meaning in C language. The meaning has
already been described. These meaning cannot be changed. There are total 32 keywords in
C language.
Auto double int struct
Break else long switch
Case enum register typedef
Const extern return union
Char float short unsigned
Continue for signed volatile
Default goto sizeof void
Do if Static while

Identifiers
In C language identifiers are the names given to variables, constants, functions and user-
defined data. These identifier are defined against a set of rules.
Rules for an Identifier
1. An Identifier can only have alphanumeric characters( a-z , A-Z , 0-9 ) and underscore( _ ).
2. The first character of an identifier can only contain alphabet or underscore.
3. Identifiers are also case sensitive in C. For example name and Name are two different
identifiers in C.
4. Keywords are not allowed to be used as Identifiers.
5. No special characters, such as semicolon, period, whitespaces, slash or comma are
permitted to be used in or as Identifier.
6. Identifier should be a whole word and no blank space should be used.
7. Generally the identifier length is 8 to 10 characters though few compilers allow up to 32
characters.

Compiled By – Poonam Warnulkar Page 5


Constants
Constants are fixed values that do not change during the program execution.
Constants are of the following types:
1. Numeric constants
i. Integer Constants
ii. Floating Constants
2. Character constants
i. Single character constant
ii. String constant

Integer Constant : An integer constant is a whole number without a decimal point. Integer
constants can be represented in three different number systems:

Decimal constant : Decimal integers consist of digits from 0 to 9.


Ex : 245, -678 , 7000

Octal constant : An octal constant can be any combination of digits from 0 to 7. The first
digit of an octal constant must be a 0 so as to differentiate it from a decimal constant.
Ex: 05, 0476, -07453

Hexadecimal constant : A hexadecimal constant can be any combination of digits from 0 to


9 and A to F. A hexadecimal constant must begin with 0x or 0X so as to differentiate it from
decimal and octal constants.
Ex: 0X40, 0XC, 0X1AB

Float Constant: Floating point number contains both integer part and a fractional part.
Floating point numbers can be represented in two forms, decimal form(fractional form) and
exponential form.

Fractional Form : Floating point numbers are written with a decimal point. Both positive and
negative numbers can be represented in this form.
Ex: 19.6, 0.16, -5.76

Exponential Form: Very large and very small numbers are represented in this form. The
symbol ‘E’ or ‘e’ is called used to represent a real number. The number before ‘E’ is called
the mantissa and the number after ‘E’ is called the exponent.
Ex: 3.5E-3, -3.58E4, 64e-8

Character constant
Single character constant: A character constant is any character enclosed within single
quotes.
Ex: ch=’T’;
The escape sequence/ back slash characters are also considered to be a character constant.
Ex: ch=’\n’; // a new line character

String constant: A sequence of characters enclosed within double quotes.


Ex: “Hello!”, “ 15 August 1947”, “How are you?”

Compiled By – Poonam Warnulkar Page 6


Escape Sequences / Back Slash Characters
Escape sequences are used as part of an output statement to define a particular operation.
Escape Sequence Purpose
\a System alarm
\b Backspace
\f Formfeed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\” Double quotes
\’ Single quotes
\0 Null
\\ Back Slash
\? Question mark

Punctuators
Punctuators are the symbols available in C.
+ - * / , . ; : ‘ “
{ } \ ~ @ ^ _ = | [
] < > ?

Variable : A variable is the name given to a memory location that contains data value and
whose value can vary during the program execution.

Values associated with a variable


There are two values associated with a variable
1. rvalue ( read value ) : It is the data value stored at some memory location.
2. lvalue ( location value ) : It is the memory address of the data stored.
Memory address → 65520 65522 65524 → lvalue
Data value → 20 80 100 →rvalue
Variable names→ a b c
Rules for naming variables
1. A variable name must begin with an alphabet or an underscore.
2. Variable name should be up to 8 to 10 characters but length can be up to 32
characters.
3. Variable name should not be a keyword.
4. Variable name should be a whole word and no blank spaces can be included.
5. Uppercase and lowercase are different variable names are normally constructed
using lowercase characters.
6. Only special symbol used in an underscore (_) but successive underscores are not
allowed.

Compiled By – Poonam Warnulkar Page 7


Declaration of a variable
Declaration is specifying the data type for the variable. Declaration helps is allocating the
memory for the variable and also helps in checking the range of values that can be provided
by the variable.
Syntax: datatype v1, v2, v3,……., vn;
where v1, v2 , v3, …… , vn are the variable names.
Ex: int sum;
float radius;

Initializing the variables


Assigning value to a variable is called as initializing.
There are 3 ways to initialize a variable:
Method 1 ) At the time of declaration
datatype variable_name = value;
Ex: int count=0;
Method 2 ) After declaration, as an assignment statement
datatype variable_name;
variable_name= value;
Ex: float radius;
radius= 3.2;
Method 3 ) Through input from the keyboard

Data Types
Data type indicates the type of data a variable can hold.
There are four types of data types
1. Primary / fundamental data types
2. User-defined data types
3. Derived data types
4. Empty data type
1. Primary / Fundamental Data Type
i) int ( Integer Type) : It represents that a number is of integer type. Integer occupies 2
bytes of memory space and the values range from -32768 to 32767. All the arithmetic
operations are possible with integer values.
ii) float ( Floating Point Type) : It represents a real number. It occupies 4 bytes of
memory space and the values range from 3.4e-38 to 3.4e38.
iii) char ( Character Type) : It represents that a character variable. It occupies 1 byte of
memory space and the range of values varied from -128 to 127 for signed characters.
The operations performed are input and output.
iv) double: It represents a double precision floating point number. It occupies 8 bytes of
memory space and the value ranges from 1.7e-308 to 1.7e308.

Modifiers : C allows to modify the range of values of the fundamental data types through
modifiers
i) short int : It is considered to be half of that of int. It occupies 1 byte of memory space and
the range is -128 to 127.

Compiled By – Poonam Warnulkar Page 8


ii) unsigned int : Here the integer is always a positive number. It occupies 2 bytes of memory
space and the range is 0t o 65535.
iii) unsigned short int : Here the short int is a positive number. It occupies 1 byte of memory
space and the range is 0 to 255.
iv) long int : It is considered to be twice of that of int. It occupies 4 bytes of memory space
and the range is -2,147,483,648 to 2,147,483,647.
v) unsigned long int : Here the long int number is a positive number. It occupies 4 bytes and
range is 0 to 4,294,967,295.
vi) long double : It is considered to be twice of double. It occupies 10 bytes of memory
space and the range is between 3.4e-4932 to 1.1e4932.
vii) unsigned char : It represents a positive character. It occupies 1 byte of memory space
and the range is between 0 to 255.
Data type Bytes Range of values
Int 2 -32,768 to 32,767
Float 4 3.4 E-38 to 3.4 E 38
Char 1 -128 to 127
Double 8 1.7 E-308 to 1.7 E308
short int 1 -128 to 127
long int 4 -2,147,483,648 to 2,147,483,647
unsigned int 2 0 to 65,535
unsigned short int 1 0 to 255
unsigned long int 4 0 to 4,294,967,295
long double 10 3.4E-4294 to 1.1E4932
unsigned char 1 0 to 255

User-Defined Data Type


“type definition” is used to define an identifier that would represent an existing data type.
Syntax: typedef type identifier;

where type→ existing data type, identifier→ new name given to the existing data type.

Ex: typedef int mark;


marks m1,m2,m3;
here marks is the new name given for integer type. Hence marks is further used to declare
the variable m1,m2 and m3 which are of integer type.

Symbolic constant

Symbolic constants are defined in the program as follows


#define symbolic name constant

Ex:
#define PI 3.142
#define MAX 100
Symbolic constants are defined using uppercase characters.

Compiled By – Poonam Warnulkar Page 9


UNIT II: OPERATORS AND EXPRESSIONS
Operator : An operator is a symbol that performs a specific task.

C operators can be classified into following types,


1. Arithmetic operators
2. Increment and decrement operators
3. Assignment operator
4. Relational operators
5. Logical operators
6. Bitwise operators
7. Conditional operators
8. Special operators

Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic
arithmetic operators.
Operator Description Example
+ Adds the operands on either side of it 240 + 60 results in 300
- Subtracts the operand on the right from the 620 – 20 results in 600
operand on the left.
* Multiplies the operands on either side of it 20 * 4 results in 80
/ Divides the operand on the left by the operand 440/ 8 results in 55
on the right
% Divides the operand on the left by the operand 56 % 6 results in 2
on the right and returns the remainder

Increment and Decrement operators


Increment operator ( ++ ) is used to increase the value of an operand by one unit.
If the operator is written before the operand it is called pre-increment and if the operator is
written after the operand it is called post-increment.
Ex : If a= 15
++a = 16 [ Pre-increment: Increment and use ]
a++ = 15 [ Post-increment : Use and increment]

Decrement operator ( -- ) is used to decrease the value of an operand by one unit.


If the operator is written before the operand it is called pre-decrement and if the operator is
written after the operand it is called post-decrement.
Ex : If x= 20
--x = 19[ Pre-decrement: Decrement and use ]
x-- = 20 [ Post-decrement : Use and decrement]

Assignment Operator
Assignment operator assigns a value to a variable . ‘ = ‘ is used as an assignment operator.
General form: operand = value;
Ex: a= 10
Assignment operators can be used with arithmetic operators as a short hand notation

Compiled By – Poonam Warnulkar Page 10


Operator Description Example
+= adds right operand to the left operand and a+=b is same as a=a+b
assign the result to left
-= subtracts right operand from the left operand a-=b is same as a=a-b
and assign the result to left operand
*= mutiply left operand with the right operand a*=b is same as a=a*b
and assign the result to left operand
/= divides left operand with the right operand a/=b is same as a=a/b
and assign the result to left operand
%= calculate modulus using two operands and a%=b is same as a=a%b
assign the result to left operand

Relational operators
Relational operators compares the values of two operands and returns the result in either
True or False.
Operator Description Example
== Checks if two operands are equal 100 = = 120 → False
!= Checks if two operands are not equal. 120 != 220 → True
> Checks if operand on the left is greater 440 > 400 → True
than operand on the right
< Checks if operand on the left is smaller 610 < 400 → False
than operand on the right
>= Checks if left operand is greater than or 70 >= 80 →False
equal to the right operand
<= Checks if operand on left is smaller than 99 <= 155 →True
or equal to the right operand

Logical operators
Logical operators compares two or more relational expressions and results in either true or
false.
There are three logical operators in C
1. Logical AND (&&)
2. Logical OR ( || )
3. Logical NOT (! )

Logical AND ( && ) : Logical AND operator compares two or more relational expressions
and if all the expressions are true the result obtained is true otherwise false.
Expression 1 Expression 2 Expression 1 && Expression 2
False False False
False True False
True False False
True True True
Ex: i) (20==30 ) && ( 300>=50) results in False
ii) ( 100 != 150) && ( 200 < 150) && ( 510 >= 66) results in True

Compiled By – Poonam Warnulkar Page 11


Logical OR ( || ) : Logical OR operator compares two or more relational expressions and any
one of the expression is true the result obtained is true otherwise false.
Expression 1 Expression 2 Expression 1 || Expression 2
False False False
False True True
True False True
True True True
Ex: i) ( 440 != 640) || ( 780 >880) results in true
ii) ( 20 < 10 ) || ( 90 >= 100) || (66 <= 55) results in False

Logical NOT ( ! ) : It reverses the logical state of a operand or a expression.


Expression !(Expression)
True False
False True
Ex: i) ! ( 300 == 400) results in True
ii) ! ( (40+60) ==100) results in False

Bitwise operators
Bitwise operators works on bits and performs bit by bit operation.
The Bitwise operators in C are:
1. Bitwise AND (&)
2. Bitwise OR ( | )
3. Bitwise XOR ( ^ )
4. Bitwise One’s complement ( ~)
5. Bitwise Left Shift ( << )
6. Bitwise Right Shift ( >> )

1. Bitwise AND (& ): It compares the bits and if all the corresponding bits are 1, the resulting
bit is a 1, otherwise a 0
Operand1 Operand2 Operand1 & operand2
0 0 0
0 1 0
1 0 0
1 1 1
Ex: 10101010 & 11110000 results in 10100000

2. Bitwise OR (| ): It compares the bits and if any one of the corresponding bit is 1, the
resulting bit is a 1, otherwise a 0
Operand1 Operand2 Operand1 & operand2
0 0 0
0 1 1
1 0 1
1 1 1
Ex: 10101010 | 11110000 results in 11111010

Compiled By – Poonam Warnulkar Page 12


3. Bitwise XOR (exclusive OR ^) : The resulting bit is a 1 , if and only if any one of the bit is a
1 otherwise it is a 0.

Operand1 Operand2 Operand1 ^ operand2


0 0 0
0 1 1
1 0 1
1 1 0
Ex: 10101010 ^ 11110000 results in 01011010

4. Bitwise One’s complement (~) : In a binary number, a 1 is converted to a 0 and a 0 is


converted to a 1.
Ex: a= 1010 1100
One’s complement of a = 0101 0011

5. Bitwise Left Shift (<<) : Left shift operator shifts the bits in the operand to the left. The
number of places the bits are sifted depends on the number following the operand. The
blanks created towards the right must be filled by 0’s.
Ex : a= 1011 0011
a << 1 results in 01100110
a<< 3 results inn 10011000

6. Bitwise Right Shift (>>) : Right shift operator shifts the bits in the operand to the right.
The number of places the bits are sifted depends on the number following the operand. The
blanks created towards the left must be filled by 0’s.
Ex : a= 1011 0011
a >> 2 results in 00101100
a>> 4 results in 00001011

Conditional operator : It is also called as ternary operator as it uses three expressions. The
ternary operator is used to replace a if-else statement in a program.
General form : variable = exp1 ? exp2 : exp3 ;
exp1 is evaluated and if it is true exp2 is assigned to variable and if exp1 is false exp3 is
assigned to variable.
Ex : Consider the following statement
if( n % 2 == 0)
even= 1;
else
odd=0;
the above if-else statement can be written as
even= (n%2==0) ? 1 : 0 ;

Compiled By – Poonam Warnulkar Page 13


Special operators
C contains the following special operators.

1. Comma operator ( , )
2. sizeof( ) operator
3. Address operator ( & )
4. Pointer operator ( * )
5. Dot operator ( . )
6. Arrow operator (→)

Comma operator : A comma operator is used to link the related expressions together. The
group of expressions are separated by comma (,).
Ex : sum =( a=20, b=25, a+b);

sizeof( ) operator : sizeof( ) returns the number of bytes necessary to store a variable.
General form: sizeof(operand);
Ex: i) int num;
sizeof(num);
return 2 (in bytes as num is an integer type)
ii) sizeof(float);
returns 4 (in bytes)

Expressions
An expression is a valid combination of operators and operands that computes to a value.
Consider the following expression
12 + b * 10
Here 12, b and 10 are the operands and +, * are the operators.
The expressions in C is classified into
1. Arithmetic expression
2. Relational expression
3. Logical expression

1. Arithmetic expression : Expressions that use arithmetic operators with numeric or


character operands are called arithmetic expression. There are three types of arithmetic
expressions are:

i. Integer mode expression


ii. Real mode expression
iii. Mixed mode expression

i. Integer mode expression : This type of expression consists of integer type operands and
arithmetic operators ( +, -, *, /, %).
Ex: i) 10 + 3 -2 which results in 11 ii) 10 + 6 % 3 results in 10

Compiled By – Poonam Warnulkar Page 14


ii) Real mode expression : This type of expression consists of real numbers and arithmetic
operators ( +, -, *, / ).
Ex :
i) 2.5 + 3.7 results in 6.2
ii) 7.2/2/5+10.0 results in 13.0
iii) Mixed mode expression : This expression consists integer and real numbers.
Ex:
i) 1.5*10+6.7 results in 21.7
ii) 7%5+10.0*10/4 results in 27.0

Evaluation of arithmetic expression


The operators in C are evaluated in a specific order which is called the precedence of the
operators. Precedence establishes the hierarchy of one set of operators over another when
an expression is evaluated. The order in which the operators of the same precedence level
are performed is known as associativity.
Precedence level Operators Associativity
1 () L to R
2 ++ , -- L to R
3 *, /, % L to R
4 +,- L to R
Ex: a= 6 * 8 + 16 * 4
a= 48+16*4
a=48+64
a=112
Relational expressions: A relational expression consist of operands and relational operands.
Relational expression results in either true or false after comparison of the operands.
Precedence level Operators Associativity
1 < > <= >= L to R
2 == != L to R
Ex: i) 40 < 100 results in True ii) 7.8 >=10 results in False iii) 2+20 ==50 results in False

Logical Expressions: It consists of operands and relational expressions and results in either
true or false.
Ex: i) ( 100>=35) && ( 100<100) results in false ii) (44==66) || ( 56>30) results in true
iii) !( 60+40 ==100) results in false

Type conversions
The process of converting one predefined type into another is called type conversion.
There are two types of conversions
1. Implicit type conversion
2. Explicit type conversion( Type casting)

1. Implicit type conversion: This type conversion takes place automatically when operands
of different data types are manipulated.

Compiled By – Poonam Warnulkar Page 15


Operand 1 Operand 2 Result
Int float Converts int to float
Char int Converts char to int
Float double Converts float to double
int short Converts short to int
Int long Converts int to long

Conversions also takes place in assignment statements


Assignment Conversion Result
float=int Converts int to float float x;
x=6;
Hence x=6.000000
int=float Converts float to int int a;
a=66.72;
Hence a=66
int=char Converts char to int. int ch;
Assigns the ASCII value of the ch=’A’;
character Hence ch=65
char=int Converts int to char. Assigns char ch;
the character depending on ch=66;
the value. Hence ch=’B’
double=float converts float to double float x=3.142525;
Hence x=3.14252500000
float=double converts double to float double x= 2.134523789;
Hence x=2.134529

2. Explicit conversion ( Type casting): It is a user-defined conversion.


General form : (data_type) expression;
Ex:
i) int x;
……..
(float) x; // x is converted from integer type to float type
ii) int sum,n;
float average;
average=(float) sum/ n; // sum is converted from integer type to float type

Mathematical functions
Mathematical functions are defined in C library by including math.h header file in the
program.
A function is written in a program as
function _name(argument list);

Compiled By – Poonam Warnulkar Page 16


Function Purpose Example
ceil(x) Rounds up to the nearest integer ceil(5.2) = 6
ceil(-2.3)=-2
floor(x) rounds down to the nearest integer floor(2.2)=2
floor(-2.7)=-3
sqrt(x) returns the square root of the value sqrt(49.0)=7.0
pow(x,y) x raised to the power of y pow(2,4)= 16
exp(x) returns E to the power if x exp(2.5)= 12.1824
(e=2.718282)
log(x) Natural logarithm of x log( 10.0)=1.0
log10(x) Base 10 logarithm of x log10(1.0)=1.0
fabs(x) Absolute value of x fabs(-3.0)=3.0
fabs(5.0)=5.0
sin(x) sin of x sin(90)=1
cos(x) cosine of x cos(90)=0
tan(x) tangent of x
asin(x) inverse sine of x
acos(x) inverse cosine of x
atan(x) inverse tangent of x
sinh(x) hyperbolic sine of x
cosh(x) hyperbolic cosine of x
tanh(x) hyperbolic tangent of x

Conversion of mathematical expressions to equivalent C expressions


Mathematical expression C expression

3abc 3*a*b*c

2(a+b+c) 2*(a+b+c)
𝑎 a/b +c
+𝑐
𝑏

2x2+3x+5 2*x*x+3*x+5

√𝑎 2 + 𝑏 2 sqrt(a*a+b*b)

−𝑏 + √𝑏 2 − 4𝑎𝑐 (-b+sqrt(b*b-4*a*c))/(2*a)
2𝑎
(𝑎 + 𝑏)4 pow(a+b, 4)

Compiled By – Poonam Warnulkar Page 17


UNIT III: MANAGING INPUT AND OUTPUT STATEMENTS
Introduction
In C, there is no built-in statements to perform input and output operations. Hence library
functions are used to perform I/O operations. These functions are defined in stdio.h header
file.

Types of I/O statements


1. Formatted I/O statements : enables the user to specify the type of the data and the way
in which it should be read or written.

2. Unformatted I/O statements : doesn’t allow to specify the type of data and the way it
should be read and written.

Type Input Output


Formatted scanf() printf()
Unformatted getchar() putchar()
gets() puts()

Unformatted I/0

Reading a single character input


getchar() function is used to read a single character from the keyboard.
Syntax: variable_name=getchar();
Ex.
char ch;
ch=getchar();

Writing a single character output


putchar() function is used to print a single character.
Syntax: putchar(variable_name);
Ex:
char ch=’A’;
putchar(ch);
will display ‘A’ on the screen

Formatted I/O

Formatted Input
scanf() function is used to read the value for a variable from the keyboard. scanf() is used to
enter numeric, character and string data.
Syntax: scanf(“control string”, address-list);
where control string → contains the conversion specifiers.
address-list → address of the variables
Ex: scanf(“%d%d”,&a,&b);

Compiled By – Poonam Warnulkar Page 18


Conversion specifiers
Conversion character Purpose
%c reads a single character
%d reads a integer
%e reads a floating point number in exponential form
%f reads a floating point number
%g reads a float both in fractional and exponential form
%h reads a short integer
%i reads a decimal or hexadecimal
%o reads a octal
%p reads a pointer
%s reads a string
%u reads a unsigned integer
%x reads a hexadecimal number

Formatted output
printf() function is used to print the data on the screen.
Syntax: printf(“control string”, variable-list);
where control string → consists of text label, back slash characters or conversion characters.
variable-list → list of variables to be displayed.

Ex: printf(“C is a high level language”);


printf(“Sum of three numbers=%d”,sum);

Format specifiers
Inorder to print the output in a particular order, C provides format specifiers which begin
with % sign followed by a number and a conversion specifier.
Syntax : % -w. p
where
- is to left justify the value
w field width(optional)
p Number of places after decimal (precision)

Format specifiers for integers

Right justified : % w d
Left justified : % - w d
where w→ field width
Ex:
i) printf(“%d”, 2365); ii) printf(%8d”,2365);

2 3 6 5 2 3 6 5

Compiled By – Poonam Warnulkar Page 19


iii) printf(“%-8d”,2365);

2 3 6 5

Format specifiers for floating point numbers


Right justified : % w.p f
Left justified : % - w.p f
where w→ field width, p→precision
Ex: float n=123.567;
i) printf(“%f”,n);

1 2 3 . 5 6 7 0 0 0

ii) printf(“%10.2f”,n);

1 2 3 . 5 6

iii) printf(“%-10.2f”,n);

1 2 3 . 5 6

Format specifiers for characters : %wc

i) printf(“%c”,A); A

ii) printf(“%4c”,A); A

iii) printf(“%-4c”,A); A

Reading a string

gets() function is used to read a string.


Syntax: gets(string variable name);
Ex: char name[20];
gets(name);

Printing a string
puts() function is used to display a string.
Syntax: puts(string variable name);
Ex: char name[20]=”Dennis”;
puts(name);
will display “Dennis” on the screen.

Compiled By – Poonam Warnulkar Page 20

You might also like