0% found this document useful (0 votes)
24 views24 pages

Unit 2

Uploaded by

mkdoesrandomshit
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)
24 views24 pages

Unit 2

Uploaded by

mkdoesrandomshit
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/ 24

Computer Programming Unit II Prepared by S.

Ashok Kumar, AP/CSE

COMPUTER
 Computer is an electronic device which accepts input from the user, process it and produce the
desired output.

A, B C=A+B C

Input Processing Output

 Computer is a machine and hence it cannot think on its own. So it requires some instructions to do
some task. Those instructions are called programs.
 Computer can understand only machine language(0’s and 1’s). The source code written in some
programming languages is converted to machine language by the compiler. It is then processed and
the output is displayed by converting it to a source language.
PROGRAM DEVELOPMENT CYCLE

Developing a program
In order to develop a program, a programmer must determine:
1. The data required to perform those instructions.
2. The instructions to be performed.
3. The order in which those instructions are to be performed.

Clearly understand Documentation &


the problem Implementation

Problem Analysis
Program Test & Debug
Development
Cycle

Design Phase Coding

Algorithm Testing

1
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

1. Clearly understand the problem and its scope


Developer needs to clearly understand the problem. By understanding the problem, he can
understand the scope with which the problem needs to be solved
2. Problem Analysis
By analysing the problem, the developer needs to develop various solutions to solve the given
problem. From these solutions, the optimum solution is chosen, which can solve the problem comfortably
and economically.
3. Design Phase
After selecting the appropriate solution, algorithm is developed for the problem which depicts the
step by step procedure to solve a problem. Further, algorithm is represented by flowchart and pseudo code.
Flowchart is a pictorial representation of algorithm which is used to understand the problem clearly. Pseudo
code is written to depict the logic of problem which helps to perform coding.
4. Testing the Algorithm for Accuracy
Before converting the algorithms into actual code, it should be checked for accuracy. The main
purpose of checking algorithm is to identify major logical errors at an early stage, because logical errors are
often difficult to detect and correct at later stages.
5. Coding
After meeting all the design considerations, the actual coding of the program takes place in the
chosen programming language.
6. Test and Debug the Program
It is common for the initial program code to contain errors. Compiler tests the program for syntax
errors thereby the bugs in the program are corrected.
7. Documentation and Implementation
Once the program is free from all the errors, developer prepares the document which contains a
entire detail of the problem. After documentation, the program is installed on the end user's machine.

PROBLEM SOLVING TECHNIQUES


Problem solving technique is a set of techniques and that helps in providing in logic and sequence for
solving a problem.
Three form of problem solving techniques:
Sequential control:
 Each and every step is executed in sequence/linear
Selection control:
 The instruction which is to be executed next is selected based on decision taken

2
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

Looping control:
 In looping control, condition is checked. Based on that condition, some statements will be executed
repeatedly.

The various problem solving techniques are algorithm, flowchart, and pseudo code.
ALGORITHM
 An algorithm is a step by step procedure to solve a problem in finite number of steps.
 After the algorithm terminates desired result should be obtained.
Properties/Characteristics/Rules of an algorithm:
 Each and every instruction should be precise and ambiguous.
 It should be finite and written in sequence thereby desired result should be obtained after the
algorithm terminates.
 It should be general (i.e.,)Not for specific input.
 It is represented in normal english.
1. Algorithm to add two numbers
Step 1: Start
Step 2: Read the values of a and b
Step 3: Calculate the sum of a and b and store it in c
Step 4: Print the value of c
Step 5: Stop
2. Algorithm to find the average of N marks
Step 1: Start
Step 2: Read the limit value n
Step 3: Read N marks
Step 4: Calculate the sum of N marks and store it in total
Step 5: Calculate the average of marks by total/N
Step 6: Print the total and average
Step 7: Stop
3. Algorithm to find the greatest of two numbers
Step 1: Start
Step 2: Read the values of a and b
Step 3: Compare the values of a and b
Step 4: If a is greater than b, print a is greatest else print b is greatest
Step 5: Stop

3
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

4. Algorithm to find the greatest of three numbers


Step 1: Start
Step 2: Read the values of a, b and c
Step 3: Compare the values of a, b and c
Step 4: If a is greater than b and c, print a is greatest else compare values of b and c
Step 5: If b is greater than c, print b is greatest else print c is greatest.
Step 6: Stop
5. Algorithm to display the value of n until it is less than 5
Step 1: Start
Step 2: Read the value of n
Step 3: While n<5, display n and add 1 to n
Step 4: Stop

Advantages of algorithm:
 Step by step solution is easy to understand
 Easy to debug errors
 Algorithm is independent of programming language

FLOWCHART
 A flowchart is a pictorial representation of an algorithm in which the steps are drawn in the form
of different shapes of boxes and the logical flow is indicated by interconnecting arrows.
 The boxes represent operations and the arrows represent the sequence in which the operations are
performed.
Symbol Symbol Name Description
Flow lines are used to connect different shapes.
Flow Lines These lines indicate the sequence of steps and the
direction of flow of control.

This symbol is used to represent the beginning


Terminal
(start) and termination (end) of program.

It is used to read the input and to display the


Input/Output output

4
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

This symbol is used to represent the instructions


Processing
which is to be performed

Decision symbol denotes a decision to be made. If


the decision is yes, some instructions will be
Decision
performed. If the decision is no, some other
instruction is performed.

Connector symbol is used to connect flowchart


connector
which is continued in another page.

Properties of flowchart
 Flow lines should not cross
 Standard symbols must be used
 Chart the main logic and it should be as simple as possible
 Use connectors if new page is needed
 Consistency is maintained in using the names/variables
Advantages
 Used to understand logic clearly by pictorial step
 Easy to analyse
 Easy to debugging and testing
Disadvantages
 Alteration and modification is difficult
 Difficult to use if program logic is complex
1. Flowchart to add two numbers

Start

Read a,b

c=a+b

Print c
5
Stop
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

2. Flowchart find greatest of two numbers

Start

Read a,b

If a>b

Print a is Print b is
greatest greatest

Stop

3. Flowchart find greatest of three numbers

Start

Read a,b

Yes If a>b No
and a>c

Yes No
Print a is If b>c
greatest

Print b is Print c is
greatest greatest

Stop

6
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

4. Flowchart to find the average of N marks

Start

Read limit n

Read N marks

total=sum of N marks

average=total/N

Print total, average

Stop

5. Flowchart to find the average of five marks

Start

Read m1,m2,m3,m4,m5

total=m1+m2+m3+m4+m5

average = total/N

Print total, average

Stop

7
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

6. Flowchart to display the value of n until it is less than 5

Start

Read n

No While
n<5

Yes
Print n

n=n+1

Stop

PSEUDOCODE
 Pseudo code is the logic of the program without exact syntax
 It is written in normal english and cannot be understand by compiler
Some of keywords used in Pseudo code
 Input: READ, OBTAIN, GET or PROMPT
 Output: PRINT, DISPLAY or SHOW
 Compute: COMPUTE, CALCULATE or DETERMINE
 Initialise: SET or INITIALISE
 Add One: INCREMENT
Rules for writing a Pseudo code
 Write only one statement per line
 Capitalize the keywords
 Indentation is followed=>It shows the boundary of conditional statements
 End multiline structure=>ENDIF for IF statement etc.,

1. Pseudo code to add two numbers


READ values of a and b
CALCULATE c by adding values of a and b
PRINT the result of c
8
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

2. Pseudo code to find the greatest of two numbers


READ values of a and b
IF a>b
PRINT a is greatest
ELSE
PRINT b is greatest
ENDIF
3. Pseudo code to find the greatest of three numbers
READ values of a, b and c
IF a>b and a>c
PRINT a is greatest
ELSE
IF b>c
PRINT b is greatest
ELSE
PRINT c is greatest
ENDIF
ENDIF
4. Pseudo code to find the average of N marks
READ limit n
READ N marks
CALCULATE total by adding N marks
CALCULATE average by dividing total by N
PRINT the total
PRINT the average
5. Pseudo code to display the value of n until it is less than 5
READ n
WHILE n<5
PRINT n
INCREMENT n value by 1
ENDWHILE
Advantages of Pseudo code
 Easily modified compared to flowchart
 Converting a pseudo code to programming language is easy compared to flowchart to programming language

9
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

Disadvantages Pseudo code


 Difficult to understand the logic or writing pseudo code for beginner
 It is not visual

HISTORY OF C
 ALGOL is the first computer programming language introduced in 1960s. This language introduced
a concept of structured programming.
 In 1967, BCPL(Basic Combined Programming Language) is developed primarily for writing system
software(Eg:Operating systems like windows).
 In 1970, language B is developed using many features of BCPL. It is used to develop early version of
UNIX operating systems.
 Language B and BCPL are typeless programming language. In 1972, C language is developed by
Dennis Ritchie at Bell labs.
FEATURES OF “C” LANGUAGE
 C is a structured programming language, where testing, debugging and maintenance is easier.
 C is a high level and portable language.
 It has separate data type for each data which leads to efficient usage of memory.
 C is a fast and efficient programming language due to the rich set of built-in functions and the data
types.
 It has a ability to extend itself.(i.e) we can add our own functions to c library.

BASIC STRUCTURE OF C PROGRAM


Header file section / Link Section
main( )
{
Declaration part
Executable part
}
Link section/Header File section
 Some of the functions in C programs was already and written in the header files. Whenever we need
to use the particular function, we will include a corresponding header file.
 All the input and output functions are declared in the header file <stdio.h> (standard input output .
header file)
#include<stdio.h>
 So in order to access those functions, we need to link the header file stdio.h to the program before
compilation

10
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

main( ) function section


 The execution of C program starts from the main function.
 Every C program must have a main function. It contains two parts.
 Declaration part declares all the variables which are to be used in a executable part.
 Executable part contains the actual operation to be performed
Example program to display a message:
#include<stdio.h>
void main( )
{
printf(“Hello World”);
getch( );
}
Note:
scanf is used to get the input from the user
printf is used to display the output
Syntax for scanf function:
scanf(“Format specifier”,&variablename); where format specifier tells the format we are going to get a
input and variable name specifies the location in which the input is stored.
Syntax for printf function:
printf(“Format specifier”,variablename); where format specifier tells the format we are going to display
and variable name specifies that the value stored in the variable should be displayed.

C CHARACTER SET
Character set denotes alphabet, digit, special character or a white space. Characters combine to form
variables. White Space may be used to separate words, but not used between characters of keywords or
identifiers.
The character set in C Language can be grouped into the following categories.
1. Letters 2. Digits 3. Special Characters 4. White Spaces
1. Letters:
Upper case letters: A to Z
Lower case letters: a to z
2. Digits: 0 to 9

11
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

3. Special Characters
& Ampersand # Number Sign { Left Flower . Dot
Brace
' Single < Opening Angle $ Dollar Sign : Colon
quotes (Less than
sign)
" Double ! Exclamation = Equal to ; Semicolon
quotes Mark

@ At symbol % Percentage ( Left / Slash


Sign Parenthesis
\ Backslash + Plus Sign ) Right ~ Tilde
Parenthesis
^ Caret - Minus sign [ Left _ Underscore
Bracket
> Closing * Multiplication ] Right | Vertical Bar
Angle Bracket
(Greater
than sign)
? Question } Right Flower , Comma $ Dollar Sign
Mark Brace

4. White Space Characters


It is used together with input and output statements. It has no meaning but it has the control to decide
the way an input has to be displayed.
1. Blank Space \b 2. Horizontal Tab \t
3. New line \n 4. Vertical tab \v

TOKENS:
 Tokens are the individual units in a C program
 C programs are written using these tokens and syntax of the language.
Types of tokens:
 Keyword
 Identifier
 Constant
 String
 Operators.

TOKENS

Keyword Identifier Constant String Special Operators


Symbol
12
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

KEYWORD
 Keywords are reserved words whose meaning is pre-defined.
 There are 32 keywords in C
The following are the Keyword set of C language.
auto const double float int short struct unsigned
break continue else for long signed switch void
case default enum goto register sizeof typedef volatile
char do extern if return static union while

IDENTIFIER
Identifier is a name of a variable, functions, arrays etc. Identifier consists of sequence of letters,
digits or combination of both.
Rules for naming a variable
 Variable name must begin wih an Alphabet or Underscore( _ ).
 Variable name should not be a keyword.
 Variable name must not contain any white space.
 No special characters can be used except underscore.
 Variable name can have a maximum of 31 characters.
CONSTANT
Constant is a fixed value that does not change during the execution of a program. It remains
same throughout the program. Its value cannot be altered or modified in a program. A variable is declared
as constant by the Keyword const.
Eg: const int a=5;
Types of constant:

13
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

NUMERIC CONSTANT
Numeric Constant is further classified into two main types. They are
(i) Integer Constants (ii) Real Constants
i) Integer constants :
 Integer constant consist of sequence of digit without decimal point. It is normally a whole number.
i) Decimal integer: It is a set of digits from 0 to 9 and preceded by + or –
Example: 123, -784, +458
ii) Octal Integer: It is a set of digits from 0 to 7 and preceded by 0
Example : 043, 052, 067
iii) Hexadecimal Integer: It is a set of digits from 0 to 9 and A to F and preceded by 0x
Example: 0x45, 0x52AF, 0x93C
ii) Real Constants
 Real Constants are otherwise known as Floating Point Constants.
 Real Constant consists of decimal number, exponent or combination of both.
Example: 43.5, 0.435e2
CHARACTER CONSTANT
Character Constant is categorized into
(i)Single character constant (ii) String constant
i) Single character constant
 Any single letter inside a single codes (‘’) is a single character constant. The letter may be a alphabet
or may be a number or any symbols or blank space.
 Example: ‘y’,‘6’,’*’, ‘ ’
ii) String constant:
 It is a sequence of characters enclosed with a pair of double quotes.
 Characters may be letters, numbers, special characters or a blank space.
 Example: “ Hello” , “1991”, “Good morning!”, “5+8”, “H”
Difference between the qualifier const and volatile:
Constant Volatile
Constant is a fixed value that does not A variable is volatile if the value gets changed at any
change during the execution of a program. It time by some of the external sources.
remains same throughout the program. Its value Example: volatile int num;
cannot be altered or modified in a program. A
when we declare a variable as volatile the compiler
variable is declared as constant by the Keyword
const. will examine the value of the variable each time it is
Example: const int a=5; encountered to see if an external factor has changed
the value.
14
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

DATA TYPE
 Data type defines the type of data that a variable can store.
Syntax for declaring a variable:
datatype variablename;
Syntax for defining a variable:
datatype variablename=value;
BASIC DATA TYPES IN C:

Format Declaration Number of


Data type Explanation Keyword
specifier
Defining the variable
of variable bytes allocated
Integer Used to store only Int %d int a; 2 bytes int a=5;
whole numbers
Character Used to store a char %c char b; 1 byte char b=’a’;
character
Floating Used to store decimal float %f float c; 4 bytes float c=5.593490;
numbers with
point
maximum of 6 digits
after decimal point
Double Used to store decimal double %lf double d; 8 bytes double d=3.45321234559843;
numbers with
maximum of 14
digits after decimal
point

Void Data Type


VOID is the empty data type. This data type is used before main function in a C Language. The
word void refers no return data type. It is used before the main function to specify the type of function. If a
function is of type void it does not return any value to the calling function.

OPERATOR
 Operator is a Symbol that performs some operation on operands.
Example: In c=a+b, + is a operator that performs addition operation on operands a and b.

TYPES OF OPERATORS
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Bitwise operators
6. Conditional operator

15
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

7. Comma operator
8. sizeof operator
1. ARITHMETIC OPERATORS
 Arithmetic operators are used to perform Arithmetic operations.
 Consider a=2, b=9
Operator Meaning Explanation Example Output
+ Unary Plus Unary plus denotes that the value is positive +a +2
- Unary Minus Unary minus denotes that the value is negative -a -2
++ Increment It increments the value of variable by 1 ++a 3
-- Decrement It decrements the value of variable by 1 - -b 8
+ Addition Performs addition on integer numbers or floating point numbers. a+b 11
- Subtraction Subtracts one number from another. a-b -7
* Multiplication Used to perform multiplication a*b 19
/ Division It produces the Quotient value as output. a/b 0
% Modulo division It returns the remainder value as output. a%b 2
It cannot be applied to real numbers

2. RELATIONAL OPERATOR
 Relational Operators are used to compare two same quantities and produce the output 1(true) or
0(false)
 Consider a=2,b=9
Operator
Meaning Explanation Example Output
< is less than Check whether first value is less than second value a<b 1
<= is less than or equal to Check whether first value is less than or equal to second value a<=b 1
> is greater than Check whether first value is greater than second value a>b 0
>= is greater than or equal to Check whether first value is greater than or equal to second value a>=b 0
== is equal to Check whether first value is equal to second value a==b 0
!= is not equal to Check whether first value is not equal to second value a!=b 1

3. LOGICAL OPERATORS
 Logical Operators are used when we need to check more than one condition.
 It is used to combine two or more relational expressions and produce the output 1(true) or 0(false).

16
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

Consider a=2,b=9
Operator Meaning Explanation Example Output
&& Logical AND It returns the value as 1, only if all the relational (a<b) && (a>b) 0
expressions are true else it returns 0
|| Logical OR It returns the value as 1, if at least one of the (a<b) | | (a>b) 1
relational expressions is true else it returns 0
! Logical NOT It returns the value as 1 if the relational !(a<b) 0
expression is false and returns 0 if the relational
expression is true

4. ASSIGNMENT OPERATORS
 It is used to assign a value to the variable
(i) Simple assignment operator
It is used to assign a value or an expression to a variable.
General form: Variable=value;
Example:
 x=10; Here the value on the right hand side is assigned to the variable on left hand side.
 x=a+b-c; Here the value of expression on right hand side is assigned to the variable on left hand side
Multiple assignment:
 A single value can be assigned to multiple variables
Example: a=b=c=d=5; Here the 5 is assigned to all variables a,b,c,d
(ii) Shorthand assignment operator
General form: variable operator = expression
The Short hand assignment operator must be an arithmetic operator or bitwise operator.
Consider a=2, b=9, c=2
Example for
Example for simple
Operator Meaning Shorthand assignment Output
assignment
operator
+= Assign sum a +=5 a=a+5 a=7
-= Assign difference b -=3 b=b–3 b=6
*= Assign product c*=(a+b) c=c*(a+b) c=22
/= Assign quotient a/=2 a=a/2 a=1
%= Assign remainder b%=c b=b%c b=1
&= Assign bitwise AND a&=b a= a&b a=0
|= Assign bitwise OR a|=b a= a | b a=11
^= Assign bitwise XOR a^=b a= a^b a=11
17
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

5.BITWISE OPERATOR
 It is used to manipulate data at bit level.
 It operates only on integers and character.
Bits & | ^
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

 Consider a=2, b=4


Operator Meaning Example Output
& Bitwise AND a&b 0
| Bitwise OR a|b 6
^ Bitwise XOR a^b 6
<< Shift left a << b 32
>> Shift right a >> b 0

Example:
i) Bitwise AND: ii) Bitwise OR: iii) Bitwise XOR:
a&b => 2 & 4 a | b => 2 | 4 a ^ b => 2 ^ 4
2=> 010 2=> 010 2=> 010
4=>100 4=> 100 4=> 100
2&4 => 000 2 | 4 => 110 2^4 => 110
2&4 =>0

iv) Shift left: Left shift operator v) Shift right: Right shift operator
shifts each bit to left shifts each bit to right
a<<b => 2 << 4 a>>b => 2>>4
2=> 0000 010 2=> 010
2<<4 => 010 0000 2>>4 => 0000000
2>>4 => 0

18
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

6. TERNARY OPERATOR (Or) CONDITIONAL OPERATOR


 Ternary operator operates on three operands.
Syntax
(exp1)?(exp2):(exp3);
where exp1 is the condition which is to be checked. If the condition is true, exp2 is evaluated otherwise
exp3 is evaluated.
Example: c = (a>b) ? a : b; //It displays a greatest of two numbers
d = ((a>b) && (a>c)) ? a : ((b>c)?b:c); //It displays a greatest of three numbers

7. SIZEOF OPERATOR
 Sizeof operator is used to return the number of bytes a variable occupy in system memory.
Syntax
sizeof(variable-name);
Example:
#include<stdio.h>
Output:
void main( )
{ The value of a is 2
int a;
printf(“The sizeof of a is %d”,sizeof(a));
getch( );
}

8. COMMA OPERATOR
 It is used to join multiple expression together.
 Expressions are executed from left to right.
#include<stdio.h>
void main( )
{ Output:
int a=1,b=2; -2 -1
a=-a,--a;
b=(--b,-b);
printf("%d..%d",a,b);
getch( );
}

19
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

PRECEDENCE OF OPERATORS
Rank Operator name Associativity
1. () [ ] Evaluates from Left to Right

2. Unary operators Evaluates from Right to Left


3. * / % Evaluates from Left to Right
4. + - Evaluates from Left to Right
5. << >> Evaluates from Left to Right
6. < <= > >= Evaluates from Left to Right
7. == != Evaluates from Left to Right
8. Bitwise AND (&) Evaluates from Left to Right
9. Bitwise EXOR (^) Evaluates from Left to Right
10. Bitwise OR ( | ) Evaluates from Left to Right
11. Logical AND (&&) Evaluates from Left to Right
12. Logical OR ( | | ) Evaluates from Left to Right
13. Conditional operator ( ? :) Evaluates from Right to Left
14. Assignment operators Evaluates from Right to Left
15. Comma operator Evaluates from Left to Right

EXPRESSION:
 An expression is a sequence of operands and operators that specifies the computation of a value.
 Example: c = a+b
Types:
1. Infix expression: The operator is written in between the operands. Example: c=a+b
2. Prefix expression: The operator is written before the operands. Example: c=+ab
3. Postfix expression: The operator is written after the operands. Example: c=ab+
EVALUATION OF AN EXPRESSION:
Consider a=1,b=2,c=3
Example 1: Example 2: Example 3:
(a+b)*c (a+b)*c-a/(b*c) (a+(b*(c-a)/b)*a)
=(1+2)*c =(1+2)*c-a/(2*3) =(a+(b*(3-1)/b)*a)
=(a+(b*2/2)*a)
=3*3 =3*c-a/6
=(a+(2*2/2)*a)
=9 =3*3 – 1/6 =(a+2*a)
=9 – 0 =1+2*1
=3
=9

20
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

TYPE CONVERSION IN EXPRESSIONS


 Type conversion is a process of converting a type of variable on right side of assignment operator to
the type of the variable on the left side.
Types:
i) Implicit type conversion:
 In implicit type conversion, type of variable on right side of assignment operator is automatically
converted to the type of the variable on the left side.
Example program:
#include<stdio.h>
void main( )
{
int a=5,b=2;
float c;
c=a/b; // Here 5/2 gives 2.500000. Since a and b are of integer type, 2 is only assigned to c
printf(“%f”,c);
getch( );
}
Output: 2.000000
ii) Explicit type conversion:
 In explicit type conversion, we need to specify the type of variable on right side of assignment
operator which needs to be converted.
Example program:
#include<stdio.h>
void main( )
{
int a=5,b=2;
float c;
c=(float)a/b; //Here 5/2 gives 2.500000. Since a and b are converted to float, 2.500000 is only assigned to c
printf(“%f”,c);
getch( );
}
Output: 2.500000

21
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

INPUT OUTPUT FUNCTIONS

Unformatted functions
Formatted functions
Input functions Output functions
scanf( ) printf( )
Character oriented functions String oriented functions
Input functions Output functions
Input Output
getchar( ) putchar( )
functions functions
getch( ) putch( ) gets( ) puts( )
getche( )

UNFORMATTED FUNCTIONS: It is divided into character oriented and string oriented functions
i) Character oriented functions:
 It performs input /output operation on a character.
i) getchar( ) Example Program Output
It is used to read a single character #include<stdio.h> Enter the character a
void main( ) The entered character is a
Example: char c;
{
c=getchar( );
char c;
ii) putchar( )
printf(“Enter the character “);
It is used to write a single c=getchar( );
printf(“The entered character is“);
character
putchar(c);
Example: putchar(c); getch( );
}
iii) getch( ) #include<stdio.h> Enter the character
void main( ) The entered character is a
It is used to read a single character
{
and does not echoes it to screen char c;
printf(“Enter the character “);
Example: char c;
c=getch( );
c=getch( );
printf(“The entered character is“);
iv)putch( )
putch(c);
It is used to write a single getch( );
character }
Example: putch(c);
iv) getche( ) #include<stdio.h> Enter the character a
void main( ) The entered character is a
It is used to read a single character {
and echoes it to screen char c;
printf(“Enter the character “);
Example: char c; c=getche( );
c=getche( ); printf(“The entered character is“);
putch(c);
getch( );
}

22
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

ii) String oriented functions:


 It performs input /output operation on a string.
i) gets( ) Example program Output
It is used to read a string until #include<stdio.h> If the input string is given as hai hello,
#include<string.h> it will get stored in str as
enter key is pressed
void main( )
Example: char str[10]; { h a i h e l l o \0
char str[10];
gets(str); 0 1 2 3 4 5 6 7 8 9
printf(“Enter the string”);
ii) puts( ) gets(str);
Output:
printf(“The entered string is “);
It is used to display a string
puts(str);
hai hello
Example: puts(str); getch( );
}

FORMATTED FUNCTIONS
 It specifies the format of input and the output.
scanf( ) Example program Output
scanf( ) is used to get input from #include<stdio.h> If the input string is given as
void main( ) hai hello, it will get stored in
the user at execution time.
{ str as
It is used to read integer, floating char str[10];
printf(“Enter the string”); h a i \0
point, character, double, string
scanf(“%s”, str); 0 1 2 3 4 5 6 7 8 9
etc. printf(“The entered string is “);
Output:
printf(“%s”, str);
Syntax:
getch( );
scanf(“Format specifier”, &variable name); hai
}
where variable name specifies the #include<stdio.h>
location in which the input is void main( ) Input
stored. { Enter the value of a,b,c,d
printf( ) int a; 12
float b; 4.5
printf( ) is used to display the char c; a
result in the output screen. double d; 4.34233338943
It is used to display integer, printf(“Enter the value of a,b,c,d”); Output
floating point, character, double, scanf(“%d%f%c%lf”,&a,&b,&c,&d); The value of a,b,c,d is
string etc. printf(“The value of a,b,c,d is”); 12
Syntax: scanf(“%d%f%c%lf”, a, b, c, d); 4.5
getch( ); a
printf(“Format specifier”, variable name); } 4.34233338943
where variable name specifies that
the value stored in the variable
should be displayed.

23
Computer Programming Unit II Prepared by S.Ashok Kumar, AP/CSE

Difference between scanf and gets function for reading string


scanf( ) gets( ) function
scanf reads a string up to the whitespace gets reads a string with whitespace
until enter key is pressed
Example: If we give input string as Example: If we give input string as
hai hello, only hai will be stored. hai hello, entire string hai hello will
be stored.

PART B University questions in IInd unit:


1. Explain the steps involved in program development cycle.
2. Explain the various input and output functions (formatted and unformatted I/O functions) used in C.
3. Explain the various operators and its precedence in C.
4. Write a C program to demonstrate scanf () and printf () statements.
5. Describe the purpose of the qualifier ‘const’ and ‘volatile’.
6. Discuss the various operators and data types in C.
7. Draw the flowchart and write the algorithm to print sum of n given numbers.
8. Discuss the problem solving techniques.
9. Explain C tokens and various types of expressions(with examples)
10. Explain the various relational and bitwise operators by giving suitable examples for the use of these
operators.
11. Discuss how the problem can be solved using a flowchart.
12. Explain the various data types in C.
13. Draw a flowchart for student mark processing.
14. Describe in detail the structure of a C program.

24

You might also like