3 Inputandoutput
3 Inputandoutput
Scientific notation
(same as float)
Some invalid input statements
General output (printf function)
• Used to print any type of data such as numeric, single character and string
• General form:
• printf(“control_string”, arg1,arg2… argn);
• It may be noted that the arguments of printf do not represent memory
address and hence no ampersand(&) sign required
Example printf
Format specifier output for integer
‘%d’
return 0;
}
Exercise 2.0: Read %d data (integer)
Given the scenario:
#include<stdio.h>
int main( )
{ int x=2,y=3,z=4;
scanf(“%1d%2d%2d%2d”,&x,&y,&x,&y);
printf(“%05d%+5d”,x,y);
return 0;
}
Exercise
int a,b,c,
float A=‘A’;
scanf(“%1d%2d%3d%3d%2d%d”,&a, &b, &a, &b, &c);
printf(“%5d,%+4d, %06d, %-5d”, A, a ,b , c);
Given value: 123456789012345
Example %c input and output
Input single character data “%c”
Example %c input and output
Exercise
• Char x;
• scanf("%c%c%*3c%c",&x,&x,&x);
• printf("%c",x);
Input: universityuthm
Input %s (string)
Input1 : Abu
Input2: bakar
Exercise 5.0: Read %c data
#include<stdio.h>
int main( )
{char x[5], y, z[5];
scanf(“%2s%c%2c”,x, &y, z);
printf(“%s%c%s”, x, y, z);
return 0;}
Exercise 6.0: Read %c & %s data
#include<stdio.h>
int main( )
{ int a = 65;
char b, c;
char d[5];
scanf(“%c%c%3s%2s”,&b, &c, d, d);
printf(“%c%c%c%s”,a,b,c,d);
return 0;
}
Format specifier output for float (%f)
• Format : %w.pf –w- width and p precision
Input: %f
• Scanf(“%2f%3f”,&x, &y)
• Input: 123.456.78.90
• Scanf(“%4f%2f%1f”,&x,&y)
• Input: 8.9032.21.23
•
Exercise 3.0: Read %f data
#include<stdio.h>
int main( )
{ float x,y,z;
scanf(“%2f%3f%2f”,&x ,&y, &z);
printf(“%.2f %06.1f %5.2f”,z, y, x);
return 0;}
Exercise
Scanf(“%2d%*3d%2d”,&a,&a);
Input: 1234 5678 read 12 by pass 34 read 56 Consider blank space
return 0;
}
Reading mixed data (%d and %c)
Example: %d and %f
• Input : 123.456
• First %2d is used to store integer in variable c
• Next, %3f is used to store 3 points float value in
variable j.
• Display the output on %d: 12 and %.2f: 3.40
Exercise reading mixed data (%d and %f)
Reading ‘blank space’ & * data
return 0;
}
*.*
Output; %*.*f number number
e.g. K=2 e.g. j=3