C Programming PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 119

1

Unit 1 : Introduction to Programming:

What is programming, how to convert given


problem into a pseudo code, writing algorithm,
efficiency of algorithms, loops and repetitions,
writing algorithms for simple problems, writing
flowcharts, flowchart symbols.

2
Unit 2:
Introduction to C-Programming
Data types and structures: Integers, float, real,
characters, logical Declaration of variables,
Input and Output of data: printf, scanf reading
and writing data from files, formatting input
and output, operators, writing simple programs
using data types, Arrays and pointers: uses,
simple programs using arrays.

3
Unit 3 : Introduction to C-Programming - II:
Control statements: if, if-else, for, do, while loops
etc.
Functions and Subroutines: simple examples.

Unit 4 : Graphics : Using graphics libraries in C.

References:
1. C-Programming for Physicists, by W. H. Bell.
2. Computer Basics and C-Programming, by Y. Rajaraman
(PHY Learning Publications).
3. Let us C, by Yashwant Kanetkar.
4. Any book of C programming
4
C is a programming language developed at AT &
T’s Bell Lab. of USA in 1972 by Dennis Ritchie.

Any programming Language


Problem oriented Machine oriented
(High level language) (Low level language)

C ---- Middle level Language.

5
• C Code can be partitioned C using functions
or block.

• C is well structured language compare to other.

General purpose language

• It is an ideal language for system programming.


• It can also used for business and scientific
application.

6
• C was invented to write an operating system
like UNIX.
• C is a successor of Basic language that was
introduced around 1970.

• The language was formalized in 1988 by the


American National Standard Institute (ANSI).

• The UNIX OS was totally written in C.


• Today C is the most widely used as System
Programming (OS) Language.

7
• Most of the software have been written in C.

• Linux Operating system have been written in


C.

To write a Processing
Steps
Program
Understand
Logic

8
Algorithms
Finite sequence of instructions that is carried
out to solve a particular problem in order
to get desired results

Characteristics

Input &output
Effectiveness
Definiteness Properly
organized Finiteness Guarantee to
give o/p

9
Language and hardware independent
Easy to understand the logic of program
Easily find out error
In general algorithm is in English –
easy to understand

10
Time consuming process
Difficult to show branching and looping
action
Easy to understand the logic of program
For big task algorithm becomes lengthy
& complicated

11
Example: To write Algorithm to swap and print
values of two variable A and B

Step 1 : Start.
Step 2 : Read A and B .
Step 3 : Let temp. =A.
Step 4 : A= B.
Step 5 : B= temp.
Step 6 : Print the values A and B.
Step 7 : Stop.

12
Example: To write Algorithm to obtain Fibonacci
series 0 1,1,2,3,5,8,13,21,34,55,89,…..
Step 1 : Start.
Step 2 : Read N ( number of terms)
Step 3 : Assign first term F1=0 & second term F2=1
Step 4 : print F1 and F2.
Step 5 : Let counter =3.
Step 6 : Calculate third term F3 = F1+F2
Step 7: Print F3
Step 7 : counter = counter +1
Step 8: If counter > N , go to step 10
Step 9: F1=F2, F2=F3
Step 10: Stop
13
Exam: To write Algorithm to solve series 1-x+x2-x3.. xn
Step 1 : Start.
Step 2 : Read N ( number of terms) and x
Step 3 : : Let counter I =1.
Step 4 : Sum = 1
Step 5 : sign = -1
Step 6 : Term = sign*x
Step 7: Sum = sum + term
Step 8 : sign = Term*(-1)
Step 9: I = I +1
Step 10: If I  N, go to Step 6
Step 11:Print sum
Step 12: Stop

14
FlowchArt :
It is a pictorial representation of an algorithm
that uses different shapes to denote different
types of instructions

Algorithm flowchart Program code

15
Terminal … start or end of program

Input / Output … for input or output data

Processing … data processing or calculations

Decision … comparison or decision

Subroutine or functions

Block

16
Flow lines

A connector
B

17
Better communication
Effective coding
Effective analysis
Systematic debugging
Effective synthesis
Proper program documentation
Easily find out error
In general language independent –
easy to understand it is general purpose

18
Time consuming

Any change or modification in flow chart is


difficult.

Very often it become lengthy.

19
start

Read A,B

Temp =0

Temp =A
A=B
B=Temp

Print A,B

stop
Data swapping of A and B
20
start

A=1,B=0

Print A,B

A=A+2, B=B+2

If Yes
A<100,
B<100
No
stop
21
Exam: Flowchart to find the largest of set of given numbers

start A

Read Number 5 3 11 No Is
Number
Largest number > largest

No Yes
Is any
Largest number
number?
Yes
Read next Print largest
Number
stop
A
22
Exercise :

1. Write an algorithm and flowchart to print


first 100 prime numbers.
2. Draw a flowchart to find all numbers in the
Fibonacci
series less than 200
3. Write algorithm and flowchart to check a given
Number is prime or not.
4. For falling spherical body in viscous medium,
The net acceleration is given by
a = g -6rv

23
24
2. List of arguments declarations
3. A compound statements that form remaining
part of program

Each compound statement is enclosed in


pair of braces i.e. { }

2. Comment : are placed within the delimiters


3. /* */ comment may appear any where
within the program.
4. Comments are helpful in explaining logic of
program

25
2. Next to comment we begin with

#include<stdio.h>
# is called as preprocessor and stdio.h is
standard input output header file
Preprocessors are
#include
#define
#if
#else etc

26
Simple C program
To display your name on the screen
“ Hellow, I am Vijay”

Program:
1 /* my name*/
2
3 #include<stdio.h>
4 void main( ) /* int main() */
5 {
6 printf(“ ------”);
7 /*return 0;*/
8 }
27
Example 2
Calculate area of circle
/* To calculate area of circle */
#include <stdio.h>
void main ( )
{
float r, A;
printf(“ enter value of radius r =”);
scanf(“%f ”, &r);
A= 3.14159*r*r;
printf(“A= %f”, A);
}
28
Characters are used to form ---- words, numbers
and expressions

Characters

Letters Digits Special White space


characters

29
The complete character set consists of
Letter a ----z Special characters
A---Z & and
Digit 0---9 , comma

White space ! exclamation mark


Blank space : colon
Horizontal tab “ quotation mark
Carriage return / slash
New line _ underscore
etc # hash
% percentage etc
30
The smallest individual units in C are known as
tokens.
Keywords Identifiers
e.g. int, char e.g. main, amount

Operators Tokens Constants


e.g. +,-,*,/ e.g. 9.8, 3.1415
++, -- String
Special symbols e.g.“Hellow”
e.g. { },#,$
31
Key word
• These are reserved words which can not be
used in program as variable names.
• They have standard and predefined meaning
which already used in C compiler
• All key words are in lower case
e.g.
auto do goto signed unsigned
back double if sizeof void
char enum int stastic volatile
const extern switch struct while
continue float return typeof union
----- etc
32
Identifiers

• Identifiers are the names given to the various


program element such as variables, functions
& Arrays.
• These are user defined names
• They consists of sequence of letters and digits,
with first letter as character.
• Lower case letters are commonly used
(but not rule)
• _ (underscore) character is also used

33
The valid identifiers are
X , x/2, sum_1, names, Tax_free, TABLE

Invalid identifiers
4th first character must be letter
“W” “” special character is not allowed
Order-no - is not allowed
my name blank space is not allowed

34
Constants

Numerical Constant Character Constant

Integer Real Single String

Decimal Octal Hexa decimal


35
• Integer constant are integer valued numbers
• Sequence of digits

• Decimal Integer : any combination of digit


fro 0 to 9

e.g. 0 1 345 9999999

13,445
38.0 not valid decimal integers
5 5 0700

36
Octal Integer : any combination of digit from 0 to
7

• First letter must be 0

e.g. 0 0345 07777

445
0380 not valid octal integers
07.00

37
Hexadecimal Integer : A sequence of digits
which begins with 0x or 0X is considered as
Hexadecimal integers. It can be followed by
combination of digit from 0 to 9 and through a
or A to f or F
• First two letters must be 0x or 0X
e.g.
0x 0X345 0X7f 0xbcd OX7FFF ….
Valid hexadecimal integers
0X12.34
0BE80
0XDEFG invalid hexadecimal integers
Hex3456
38
•The largest integer value that can be stored is
machine dependent
•It is 32767 on 16bit machine ( i.e. 215 -1)
•The range for integer is
215 to 215 -1 i.e. -32768 to 32767
Real Constant or Floating point constant
•It is base 10 number that consist of either a decimal point
or exponent ( or both)

Valid floating point number


0.0 0.3 980.012 0.00012 1.234E+3
0.0005e-5

39
• Non Valid floating point number

2,00.0 4E+10.2 2E 10 or ½

• Notation in exponent form is useful when the number


if either verge or very small
e.g. the number 3x 108 can be written in following
ways
300000000 3e8 3e+8 3E8 0.3e9 0.3E9 30.0E7

• The floating points have greater range than integer


The range is 3.4E-38 to 3.4E+38
• Floating point constant are represented as double
precision quantities.

40
Each floating point occupies 8 bytes (1 byte = 8
bit ) of memory

Character constant:
•Single character constant : contains single
character enclosed in single quote mark.

•It can be single alphabet, single digit or single


special character e.g. ‘a’ ‘5’ ‘\n’ ….. Valid
single character constant
41
‘ab’ or ‘54’ ….. Invalid
Character constant have integer value known as ASCII.
(American Standard Code for Information Interchange)
character ASCII character ASCII
value value
null 0 a 97
/ 47 b 98
1 48 . .
2 49 . .
. . z 122
. . { 123
A 65 } 125
. Del 127
Z 90

42
String constant :
•It is sequence of any number of character/s enclosed in
double quote. It can be alphabet, digit or single special
character
e.g. “abc” “5YZ”
“ Hellow” “5+3=8” or “x” -- Valid string constant

Back Slash character constant: (escape sequence)


Certain character can represented in character and
string constant by escape sequence like \n (new line)
‘\n’ new line ‘\b’ back space ‘\a’ sound beep
‘\t’ horizontal tab ‘\v’ vertical tab

43
VARIABLES:
• Variable is an entity that has value and known to
program by name
.
• Variable definition associates a memory location
with variable name.

• Variable can have only one value assigned to it at


any given time during execution of program. But
it may change during execution of program.
e.g. F = 1.8*C+32
Here F and C are variables

44
VARIABLES NAMES:
• Variable names are identifiers
• They are symbolic names given to the
memory locations.
• Variable names consists of sequence of
letters and digits. First letter should be
alphabet

• Rules for naming variable:


•First letter should be alphabet.
•Many compiler allows only first 8 digit.
e.g. average_height
average_weight same
45
Rules for naming variable:
• Upper and lower case letters are significant.
i.e. Total , total TOTAL are different
• No comma, blank space or special symbols are
allowed within variable name
• Variable name should not be keyword
Basic Data types: C support following data types
Char a single byte can hold one character
int an integer
float a single precision floating point number
double double precision floating point number
Precision refers to no. of significant digit after
decimal point
Qualifiers alters the characteristic of data.
Qualifiers that alters the size are short and long.
• short int integer represented by less number
of bits (16bit)
• long int integer represented by large number
of bits (32bit)
The sign qualifiers are signed and unsigned.
signed qualifiers results six more integer data
signed short int unsigned short int
signed int unsigned int
signed long int unsigned long int
The sign qualifiers are also applied to char data
Signed char unsigned char
47
• Normally size qualifier (short or long) can
not applied to char and float data
• Sign qualifier can not applied to float double
and long double
Data types: C supports 4 data types

1. Primary data type (fundamental)


2. User defined data type
3. Derived data type
4. Empty data set

48
Size and range of basic data type

Data type Range of value


char -128 to 127
int -32768 to 32767
float 3.4E-38 to 3.4E+38
double 1.7E-308 to 1.7E+308

49
Data type Size Range of value
(bit)
char or sign 8 -128 to 127
char
unsigned char 8 0 to 255
int or 16 -32768 to 32767
sign int
unsigned int 16 0 to 65535
short int or 8 0 to 255
unsigned short
int

50
Data type Size Range of value
(bit)
long int or 32 -2147,483,648 to
signed long 2147,483,647
unsigned 32 0 to 4,294,967,295
long int
float 32 3.4E-38 to 3.4E+38
double 64 1.7E-308 to
1.7E+308
long double 80 3.4E-4932 to
1.1E+4932

51
Primary data declaration
A variable can used to store value of any data type
The syntax for declaring a variable is
Data-type name of variable (v1, v2,v3, ……,vn);
e.g.
int a, b, c;
float root1,root2;
double ratio;
char flag;
int Text[100];

52
Integer type variable can be declared as
short int for smaller integer
long int for longer integer

for
short int memory capacity 2 byte
int 4 byte
long int 8byte

int variable can be declared as signed or unsigned


e.g. unsigned int a;
signed int a;

53
Declaring constant
• In C value can be assigned to a variable name.
• If no value is assigned then it is undefined
e.g.
int a =2, p =-456, val = 1234;
float z = 2.5634E-2, pi =3.1415;
char c =‘x’, float y;

here y is undefined.
Unless variable is not defined it can not be used in
arithmetic operation

54
Symbolic constant
• In program we often use certain unique constant.
• Such constant can appear many times in the
program
• E.g. Pi = 3.14159 can be used many times.
• For this case we have to define value of pi as
symbolic constant.
• Thus symbolic constant is a name is name that
substitute for sequence of characters. These
character may be numeric constant, character
constant or string constant.

55
Syntax for declaring symbolic constant

#define symbolic constant_name value of constant


e.g.
#define PI 3.14159
#define TRUE 1
#define C 3E+8
#define PASS_MARKS 40

Symbolic constant are also called as constant


identifiers

56
Rules for defining symbolic constant
1. Symbolic names are written in capital letters
2. No blank space between # and define
3. # must be first character in line
4. A blank space must be there between define and
name of symbolic constant and the value of
constant
5. #define statement must not end with semicolon
6. No = sign between symbolic constant name and
its value
7. Symbolic names are not declared for data type
8. After definition symbolic constant name should
not be assign any other value in the program
57
Operators and Expressions

• Operators are symbols that operates on certain data


• Operators are used to manipulate data and variable
Arithmetic +, -, *, / ,%
Relational <, >, <= ,>=, ==,!=
Logical &&, ||, !
Incremental /Decremental ++, --
Types of operators Assignment =
Conditional ?:
Bitwise
Special operators

58
Types of operators

Arithmetic Operator
+ Addition or unary plus

- Subtraction or unary minus

* Multiplication

/ Division

% Modulo division (Reminder after


division)

59
Integer Arithmetic
e.g.
int a=17, b = 4,C;
then
C = a + b; 21
C =a-b 13
C =a*b 68
C = a/b 4 result is truncated, decimal
point is discarded
C = a%b 1 The result of reminder and sign of
reminder is always sign of first operand

60
Floating point Arithmetic
e.g.
float a=17.0, b = 4.0, C;
then
C = a+b (21.00000000)
C = a-b (13.00000000)
C= a*b (68.00000000)
C = a/b (4.25000000)
C = b/a (0.23529411)
• Reminder operator is not applicable for
floating point modulo division

61
Relational Operator

• It is used to compare arithmetic, logical and


character expressions
• We have to compare two quantities and
depending on result we have to take decision
• Each of these operators compares from L.H.S
to RHS
• The whole expression involving relational
operator then evaluated to integer
• If integer is 0 the condition is false
And if it is 1 the condition is true
62
< Lessthan

<= Lessthan or equal to

> Greater than

>= Greater than or equal to

== equal to

!= Not equal to

63
e.g. int i =2, j = 4, k = 6;

i <j Yes (true) 1


i+j > = k Yes (true) 1
(i +j) > (i+10) No (false) 0
j == 4 Yes (true) 1
k !=6 No (false) 0

64
Logical operator
Logical operators are used when we want to
test more than one condition and take decision
&& Logical AND

|| Logical OR

! Logical NOT
In case of && if both condition are true then only
corresponding loop will executed
In case of || if both condition are false then only
corresponding loop will not executed
65
e.g. int i =14, float f = 11.1, char c =‘a’;

(i >= 12) && (c==‘a’) Yes (true) 1


(i >=12)||(c==97) Yes (true) 1
(f < 20) && (i >50) No 0
(false)
(c!=‘w’)||(i+f)<=10) Yes (true) 1
! (i > (f+1) No 0
(false)

66
Assignment Operator
• They are used to assign the result of expression
to the variable
• Assigning operator is =
• Operator evaluates the expression from left to right
And assign the resulting value to the variable

Identifer = expression

e.g. i =3 means 3 is assign to i


Sum = a + b; means sum of a and b is assign to Sum
If
int i =3.3 then i will be 3
67
Incremental/Decremental Operator
(Unary operators)

• These operators are used in loops.


• In the class of operators that acts upon a single
operand to produce new value called as unary
operators.
• In unary minus operators the value of variables
is negated
• Unary minus operator has higher precedence
over all other Arithmetic operators

68
Operator Symbol Action e.g.
Incremental ++ Increase X++, ++X
operand
value by 1
Decremental -- decrease X--, --X
operand
value by 1

++X , --X prefix


int t, x =1;
t= ++x;
printf(“prefix operator : t=%d, x =%d\n”, t, x);
Value is increased first and
Prefix operator : t=2, x=2 then assign
69
int t, x =1;
t= x++;
printf(“postfix operator : t=%d, x =%d\n”, t, x);

Postfix operator : t = 1, x =2 Value is assign first and


Then increased

Conditional operator:
• An operator that makes use of condition (?:) is
called as Conditional operator.
• They are used in if - else statement
• Conditional operator can be written in the form
Exp1? Exp2 : Exp 3;

70
Same as
True False e.g
If (exp1) int a =10,b =15, c;
c = (a>b)?a:b
(exp2)
Else Then c = b =15
Exp(3); is assign to c

71
sizeof Operator –
•It gives the size of data type of the variable in
terms of byte occupied in memory
•Pointer operator * and & and
•comma operators are also there

Operator Precedence and Associatively


Operator precedence is the order of evaluation
int a=10,b=15,c=3, d;
d =a+b*c;
1

72
If
d = (a+b)*c

1 2

73
Operation category operator Associatively
in order of
precedence
1. Unary operator ++, -- R --> L
2. Arithmetic */% L --> R
Add and subtract +- L --> R
3. Relational <<== >>== L --> R
equality == != L --> R

4. logical && || L --> R

5. conditional ?: R ---> L
6. Assignment = += *= /= %= R ---> L
operator

74
Program: use of operators
/* Use of Operators */

#include<stdio.h>
void main()
{
int a, b, c, d;
a= 15,b=10;
c= ++a - b; /* 16-10 =6*/
/*16 10 6 */
printf("a=%d b=%d c=%d\n",a, b, c);
D = b++ +a; /* 10 +16 = 26 */

75
printf("a=%d b=%d d=%d\n",a, b, d); /*16 11 26 */
printf("a/b = %d\n",a/b); /* 16/11 =1*/
printf("a%b = %d\n",a%b); /* 16%11 = 5 */
printf("a*=b = %d b=%d\n",a*=b); /a*=b =16x11 =176*/
printf("%d\n", (c>d)? 1:0); /* 6>26 No -- 0*/
printf("%d\n',(c<d)?1:0);); /* 6<26 Yes -- 1*/
}
Output
a=16 b = 10 c=6
a=16 b = 11 d=26
a/b =1
a%b =5
A*=b = 176
0
1
76
Write a program to calculate area of Triangle
/* calculate area of triangle*/
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,s,area;
clrscr ();
printf(" enter the valu of three sides=");

77
scanf("%f %f %f",&a,&b,&c);
s= (a+b+c)/2;
area= sqrt(s*(s-a)*(s-b)*(s-c));
printf("The area of triangle = %f ",area);
getch();
}
------------------------------------------------------------
Write program to calculate simple interest
/* simple interest */
#include<stdio.h>
Void main()
{
float p, r, t, simple;
78
printf(" enter the value of rate of interest=");
scanf("%f", &r);
printf(" enter the value of time period=");
scanf("%f", &t);
simple=p*r*t/100;
printf(" the simple intrest is = %f\n",simple);
}

79
Assignment II
rdnarhe@fergusson.edu

1.Write C program to calculate percentage of


marks of student and give grade . If percentage of
marks is above 70 grade is A and if it is below 70
then grade is B
2. write C program to calculate the distance
between two point using distance formula.

80
Input / Output Functions

C does not have any build in input/output


statements.
All i/o operations are carried out by functions
such as
scanf(), getchar(), gets()
printf(),putchar() ,puts() Standard I/O
library function

81
Single character input function
getchar ( )
• A single character can be entered into computer
using C lib. Function i.e. getchar()
• The getchar returns a single character from
standard input device such as keyboard
• It does not required any argument
character _variable = getchar();
e.g char c;
C = getchar();

82
Single character out function
putchar ( )
• A single character can be displayed using C lib.
Function i.e. putchar()
• The putchar() transmit a single character to
standard output device such as monitor
• The character being transmitted will be
normally represented by character type variable
• It does not required any argument
putchar (charracter_variable);
e.g char answer = 'N'
putchar(answer);
83
Example:
/* Use of character I/O function*/

#include<stdio.h>
void main()
{
char c;
printf(" print one character:");
c = getchar(); /* input a character and assign to c*/
printf(" The character you entered is:");
putchar(c); /* assigned char to c is display on screen*/
}

84
getch () function
getch() function is similar to getchar() function.
But it waits to keypress afterwhich it returns it
immediately. It reads character without echo to
screen
// Example for getch() in C
#include <stdio.h>
// Library where getch() is stored
#include <conio.h>
void main()
{
printf("%c", getch());
}
85
Important Points regarding getch() method:
• getch( ) method pauses the Output untill a key
is pressed.
• It does not use any buffer to store the input
character.
• The entered character is immediately returned
without waiting for the enter key.
• The entered character does not show up on the
console.
• The getch() method can be used to accept
hidden inputs like password, ATM pin
numbers,

86
Formatted input
It refers to input data that has been arranged in particular
manner.
The input data can be entered in the computer by using
scanf function.
This function can be used to enter the data by combination
of numerical value, single character or string

87
scanf(" The control string", &arg1, &arg2, ----argn);

Control string containg pointers that


Certain required formatting indicate address of
Information data
Control string includes field or
format specification
It contains conversion character
%, a datatype character
Each character must begin with
% sign
Multiple character can be separated
By blank space
88
Conversi Type of Meaning
on Argument
characte
r
%d integer Signed decimal
integer
%i integer Signed decimal
integer
%O integer unsigned decimal
octal
%u Integer unsigned decimal
integer
%X integer unsigned
hexadecimal
89

%f Floating Signed floating


Conversion Type of Meaning
character Argument
%g or %G Floating Signed value
point either in e or
f
%h Integer Signed
integer
%l Integer or Long integer
float or double
%L Integer Long double
%S character Signed
character
90
• Arguments are written as variable or Array.
• Each Variable must be preceded by an ampersand
(&)
• But Array name must not begin with &.

main( )
{
char item[10];
int part_no, float price;
--------
scanf("%s %d %f", item, &part_no ,&price);
}
White space

91
Field:
• The consecutive non white character that
defines the data item collectively is called
as field.
• It is possible to limit the number of such
character
by specifying a maximum field width for
the data.
• So an unsigned integer containing the
field width is
%wd , w is integer no data is integer type
placed within controlled string between
% and conversion character
92
main ()
{
int x, y, z;
-----
scanf("%3d%3d%3d\n", &x, &y, &z);
-----
}
When program execute
Three integer quantity entered through keyboard
Result
1 2 3 X=1 y =2 z = 3
123 456 789 X=123 y =456 z = 789
123456789 X=123 y =456 z = 789
1234 5678 9 X=123 y =4 z = 567

93
Formatted Output
It refers to output data that has been arranged in particular
manner.
The output data can be written from the computer by using
printf function.
This function can be used to output the data by
combination of numerical value, single character or string

printf(" The control string", arg1, arg2, --


argn);

94
printf(" %3d", 1234); 1 2 3 4

printf(" %6d", 1234); 1 2 3 4

printf(" %2d", 1234); 1 2 3 4

printf(" %-6d", 1234); 1 2 3 4

printf(" %06d", 1234); 0 0 1 2 3 4

95
Out put of real number
• F type conversion and e type conversion are both
used to output floating point values
• The format specification is

%w.pf or %w.pe
number of
minimum number of digits that are to be
Positions that are to displayed after decimal
be used for display point (precision)

96
e.g. float x = 12.3456

printf(" %7.4f", x); 1 2 . 3 4 5 6

printf(" %7.2f", x); 1 2 . 3 5

printf(" %-7.2f", x); 1 2 . 3 5

printf(" %f", x); 1 2 . 3 4 5 6

printf(" %10.2e", x); 1 . 2 3 e + 01

printf(" %11.4e", -x); - 1 . 2 3 4 6e + 0 1

printf(" %e", x); 1 . 23 4 5 6 e + 0 1

97
String input and Output
• The function gets receives the string
from the standard Input device,
• while puts output the string to
standard
Output device.

If input string have blank character, we can


not read such String in Array using scanf
function. So we have to use gets function

98
Consider following program

void main()
{
char name[40];
printf("\n enter name:");
scanf("% s", name);
printf("%s", name);
}
Output
enter the name: Sachin Patil

Sachin
blank space

99
Name Patil never get stored in array name
After Sachin the scanf assumes that the name entered
has ended after white space.

So we have to use gets( ) for input and and puts() output

void main()
{
char name[40];
Output
printf("\n enter name:");
enter the name: Sachin Patil
gets( name);
puts(name);
Sachin Patil
}

100
Character test function
Character test function meaning
isalnumeric(c) Is c an alphanumeric character?
isalpha(c ) Is c an alphabetic character?

isdigit( c) Is c cdigit

islower(c ) or isupper( c) Is c a lower or upper character?


isprint( c) Is c printable character
ispunct(c ) Is c is punctuation mark?
isspace(c ) Is c a white space?

101
Flag
•Is a character group within Control string
can include a flag which affects the output.

•The flag must be placed immediately after


% sign.

•Some compiler allows you to more than one


flags to appear consecutively within same
character group

102
flag meaning
- Data item is left justified, remaining field will blank
+ A sign( + or -) will precede the sign numeric data.
Without this flag only negative items are preced by
sign
0 causes leading 0 to appear instead of blank spac. It
is applied to data are right justified.
#(with 0 or X Causes octal and hexadecimal data items to precede
type conversion by 0 and 0x respectively.
#(with e,f, g Causes decimal point to be present in all floating
type conversion numbers even it is whole number. It also prevent
truncation of trailing zero and g type conversion
Blank space All blank space will precede each +ve signed numeric
data

103
Example of flag.
/* use of flag */
void main()
{
int i = 123;
float x=12.0, y = -3.3;
printf(" :%6d %7.0f %10.1e:\n\n", i,x,y);
printf(" :%-6d %-7.0f %-10.1e:\n\n", i,x,y);
printf(" :%6d +%7.0f %+10.1e:\n\n", i,x,y);
printf(" :%-+6d %-+7.0f %-+10.1e:\n\n", i,x,y);
printf(" :%7.0f %#7.0f % 7g. %#7g:\n\n", x,x,y,y);

104
Output
: ...123 …..12 …-3.3e+00 : right justified
:123… 12…… -3.3e+00..: left justified
:..+123 12…….3.3e+00
:+123.. 12…. -3.3e+00..
:…..12….12 …-3.3 -3.30000

Decimal point due to #flag

105
Program to calculate exponential series
ex =1 + x + x2/2! + x3/3!+ ….. +xn/n!
#include<stdio.h>
void main()
{
float x, t, s;
int i, n, fact;
printf("enter the value of x and n =");
scanf("%f %d", &x, &n);
t=1;
s=1;
for(i=1;i<n; i++)

106
{
fact =1;
fact = i
t = t*x/fact;
s=s + t;
printf(The value of e raised to x=%10.4f\n", s);
}

107
108
109
110
111
112
113
114
115
116
117
118
119

You might also like