Right Justified Float Output in C
Right Justified Float Output in C
Whenever a program is written, it will mainly have certain input values from the users for which
the program will do some operations/calculations and its result will be displayed to the user.
There should be some devices to enter the value to the program (system or keyboard or files) and
there should be some devices to accept the result (system, screen or files). But C treats all these
devices as files and calls it as standard files. It terms input devices / input files as standard input
file or stdin file and output files as standard output file or stdout file. Like any other programs, C
programs can also have errors. When compiler encounters error, it displays them on the screen.
This error files are termed as standard error files or stderr file in C.
Input : It is a process of feeding/transferring data from input devices into program. C provides a
set of built-in functions to read given input and feed it to the program as per requirement.
The user inputs can be anything – may be integer values, float / double values, character/string
values. The code should be strong enough to accept any of these kinds of inputs from the user
and should able to differentiate its type. These entered input values are accepted by using the
functions like scanf(), getchar(), getche(), getch(), gets () etc. Similarly, the result of operations
inside the program can be anything from numbers to string. This can be displayed on the screen
using different output functions like printf(), putchar(), putch(), puts() etc. Both input and output
functions are defined in the header file stdio.h. Hence we need to add this preprocessor directive
before starting the main function in any C program.
The input/output functions are classified into two types :- Formatted and Unformatted functions
Formatted functions : Formatted functions allow input or output data to format according to
user's requirements. The input function scanf() and output function printf() are formatted
functions. The printf() is used to convert data stored in the program into a text stream for output
to the monitor, while scanf() is used to convert the text stream coming from keyboard to data
values and stored them in program variables.
Formatted Input: Formatted input refers to an input data that has been arranged in a particular
format. For example : Mohan, 24, 34.45
Where control string refers to a string containing certain formatting information of input data
item. It may include :
Format specifications, consisting of a percentage sign (%), field width (optional) and a
conversion character. Format specification is the compulsory part of the control string.
Blank, tab (\t) and new line (\n) characters. These are optional in control string. If these
are used in the control string to separate the different format specifications, they must be
entered consecutively while inputting the data but they will not be stored in memory.
Arguments arg1, arg2, .... argn are the arguments that represents the individual input data items.
The data items may be variables. Each variable name must be preceded by an ampersand (&)
(address operator) except string (array of characters) to denote memory address.
Inputting (scanning) integer numbers : The format specification for reading an integer looks
like %wd. It means, scanf function reads an integer number of field width w.
Example : This example illustrates different format specifications for reading integer numbers.
void main(){
int a,b;
printf("Enter an integer number:");
scanf("%d",&a);
printf("The read and stored value of a =%d",a);
printf("Enter another integer number:");
scanf("%3d",&b);
printf("The read and stored value of b =%d",b);
}
Output:
Enter a integer number:12567 ( No field width specified in format specification.)
The read and stored value of a =12567
Enter a integer number:12567 (Field width of 3 columns is specified. So value in first
The read and stored value of b=125 three field is read and stored in memory location specified
by &b.)
Run 2 : Enter two integer numbers:23459 678 (Only first 3 digits 123 are read and assigned to
The read and stored value of a is =234 a and remaining two digits are read and assigned
The read and stored value of b is =59 to b. Second 678 is ignored.)
Run 3 : Enter two integer numbers:123 1234567 (First number has 3 digits, it is read and
The read and stored value of a is =123 assigned to a. But 2nd number has 7 digits,
The read and stored value of b is =12345 only first five digits are read and stored in
memory location specified by &b.)
Inputting real numbers : Reading real number is easier than the integer number because it is
not required to specify the field width.
Example : This example also illustrates different format specifications for inputting different
type of real numbers.
void main(){
float a,b;
double x,y;
long double g,h;
printf("Enter values of a and b:");
scanf("%f%e",&a,&b);
printf("Value of a=%f and value of b=%e",a,b);
printf("\nEnter values of x and y:");
scanf("%1f%1f",&x,&y);
printf("\nValue of x=%1f and value of y=%1f",x,y);
printf("Enter value of g and h:");
scanf("%Lf%Lf",&g,&h);
printf("value of g=%Lf and value of h=%Lf",g,h);}
Inputting a character using scanf() : It can be done using getchar() function and scanf() also.
Inputting strings : String is a sequence of characters. We use gets() to read a string. There are
three ways of reading strings using scanf() function. The first way is to use %ws format
specification.
Example : This example also illustrates different specifications for scanning strings.
void main(){
char str[50];
printf("Enter a string:");
scanf("%10s",str);
printf("Read string is=%s",str);
printf("Enter a string:");
scanf("%10s",str);
printf("Read string is=%s",str);
printf("Enter a string:");
The great limitation of scanf function to read string is that it can't read the string having multiple
words because %s terminates reading at the encounter of any arbitrary white space. There are
different techniques to solve this problem. Another way to read string is to specify the field
width in %c format. Whose format specification is %wc. It means reading characters in the field
width w. When this format is used for reading a string, the system will wait until the wth
character is keyed in.
Example : This example illustrates the concept of reading strings using %wc format
specification.
void main(){
char str[50];
printf("Enter a string:");
scanf("%10c",str);
printf("Read string is:%s",str);
}
Output :
Run 1 : Enter a string: pppppppppppppppp (Reading only 1st 10 characters of given string)
Read string is: pppppppppp
Run 2 : Enter a string:Nepal is a beautiful nation. (Reading 1st 10 characters with white space
Read string is:Nepal is a characters also.)
Example: Write a program to take input string from user. Your program should allow to input
uppercase letter only.
#include<stdio.h>
#include<conio.h>
int main(){
char str[30];
printf("Enter your name in uppercase:");
scanf("%[A-Z]",str);
printf("Your name is %s.",str);
getch();
return 0;
}
Output:
Your name is R
Your name is
Example: Write a program to read a string with multiple word (i.e. with space) using scanf()
function and display on the screen.
#include<stdio.h>
#include<conio.h>
Explanation : Only %s control string in scanf() function can't be used to read string with blank
spaces. It is possible by using %[^\n] specification. This tells the compiler to read a string until a
new line character is entered.
Example : Write a program to read some text from user. The reading process should continue
until user enters a character 'q' as input. Finally display entered text except character terminating
character q.
#include<stdion.h> Output:
q
void main(){
Your text is Hello Mohan
char str[100];
printf("Enter some text:");
scanf("%[^q]s",str);
printf("Your text is %s",str);
getch();}
Example : This example illustrates the concept of reading mixed data input.
#include<stdio.h> Output:
#include<conio.h> Enter name, roll number and marks in B.E. entrance:Mohan 234 90.6
Marks:90.6
int roll;
float marks;
scanf("%s%d%f",name,&roll,&marks);
printf("Name=%s\nRoll=%d\nMarks=%f",name,roll,marks);
getch();}
Except control string each of the other arguments must be address of the a variable
(pointer).
Format specifications must match the arguments in order.
Input data item must be separated by any white space and must match the variables
receiving the input in the same order.
When scanf() encounters as invalid value of the data item being read, the reading will be
terminated.
While searching for a value, scanf() ignores all the white spaces like tabs, new line.
Any unread data items in a line will be considered as a part of the data input line to the
next scanf() call.
If field width is used, it should be large enough to the size of input data.
Formatted Output
Formatted output functions are used to display or store data in a particular specified format. It
can be accomplished by formatting output. For this purpose, there is well known library function
named printf() in stdio.h header file. Its general form looks like :
printf("control string",arg1,arg2,arg3.............,argn);
Flags : The flags may be -, +, 0, or # . A '-' flag is used to indicate data item to be left-justified. A
'+' flag is used to display sign (i.e. either positive or negative whatever data item has) to precede
each signed numerical data item. A '0' flag is used to indicate leading 0s to appear instead of
leading blanks in right justified data item whose minimum width is larger than the data item. The
flag '#' is used with %o or %x to indicate octal and hexadecimal items to be preceded by0 and
0x respectively. Similarly, the flag '#' is used with %e, %f or %g to enforce a decimal point in
floating point numbers, even if it is a whole number.
Field width : The field width is an integer which specifies the minimum number of characters or
digits to be displayed in output operation. If the number of characters in the corresponding data
item is less than the specified field width, then the data item will be preceded by enough leading
blanks to fill the specified field. If the number of characters in the data item exceeds the specified
field width, then the entire data item will be displayed.
Printing integer numbers : The general form of format specification for printing integer
number is %wd. This means integer number will be printed in w columns (field width) with
right justification.
void main()
{
int a=12345;
printf("\ncase 1=%d",a);
printf("\ncase 2=%i",a);
printf("\ncase 3=%15d",a);
printf("\ncase 4=%-15d",a);
printf("\ncase 5=%015d",a);
printf("\ncase 6=%-+15d",a);
printf("\ncase 7=%3d",a);
getch();}
Output:
case 1=1 2 3 4 5
case 2=1 2 3 4 5
case 3=_ _ _ _ _ _ _ _ _ _ 1 2 3 4 5 (with field width, default justification to right)
case 4=1 2 3 4 5_ _ _ _ _ _ _ _ _ _ (Using flag - to make left alignment)
case 5=0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 (Using flag 0 to fill the blank before the number)
case 6=+ 1 2 3 4 5 (Number preceded by a + sign in left alignment)
case 7=1 2 3 4 5
Printing real numbers : The general form of format specification for printing real numbers is
%[Link]. This means the number will be printed in w columns (field width) on the screen with p
digits after the decimal point (precision) with right justification. The value, when displayed, is
rounded to p decimal places. The default precision is 6 decimal places. The number will be
displayed in the form [-] [Link]. The general form to print real number in exponential form is
%w.p e. The display takes the form [-] [Link][+-]xx. Where number of q's depend on p. The
default precision is 6. The field width w should satisfy the condition w>=p+7. The value
rounded off and printed in the field of w column with right justification.
void main(){
float n=123.9876;
printf("\ncase 1=%f",n);
printf("\ncase 1=%e",n);
printf("\ncase 1=%g",n);
printf("\ncase 1=%15.4f",n);
printf("\ncase 1=%-15.3f",n);
printf("\ncase 1=%015.4f",n);
printf("\ncase 1=%.8f",n);
printf("\ncase 8=%2.2f",n);
getch();
Output:
case 3=1 2 3 . 9 8 8 (Occupies minimum field width to print in g format, vary n and observe various g format)
Printing a single character : The general form of format specification to print a single character
in a desired position on the screen looks like :
%wc . This means a character will be printed on the field width of w columns with right
justification.
void main(){
char ch='a';
printf("\ncase 1=%c",ch);
printf("\ncase 3=%-10c",ch);
Output :
case 1=a
case 2= a
case 3=a
Printing strings : Printing strings is similar to real numbers. The general form of printing string
on the screen in a field width of w columns in %[Link]. It will print first p characters of the string
in the specified field width with right justification.
Example : This example illustrates different format specifications for printing strings.
void main(){
printf("\ncase 1=%s",str);
printf("\ncase 2=%18s",str);
printf("\ncase 3=%-18s",str);
printf("\ncase 4=%18.8s",str);
printf("\ncase 5=%18.9s",str);
printf("\ncase 6=%5s",str);
printf("\ncase 7=%.10s",str);
case 1=I_Love_Baglung.
case 3=I_Love_Baglung._ _ _
case 5=I_Love_Ba_ _ _ _ _ _ _ _ _
case 6=I_love_Baglung._ _ _
case 7=I_Love_Bag_ _ _ _ _ _ _ _
Printing mixed data : More than one data type can be printed using function printf.
void main(){
int n=12345;
float m=123.9876;
char ch='a';
printf("n=%7dm=%12.5fch=%-2cstr=%16s",n,m,ch,str);
Output :
n=_ _ 1 2 3 4 5 m = _ _ _ 1 2 3 . 9 8 7 6 0 c h = a
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 5051 52 52 53 54 55 56
str=__I_love_Nepal
Single Character Input / Output : The macro getchar() reads a character from the standard
input device, while the macro putchar() writes a character to the standard output device.
String Input / Output : Functions gets and puts are used for inputting and outputting strings.
[Link] : The function accepts string variable (the name of string) as a parameter, and fills the
string with characters that are read from the keyboard, till a new line character is encountered (
i.e., until we pass the enter key). At the end the string, gets appends a null character and returns
the string. The new line character is not added to the string.
In this example stdio.h (standard input/output header file) is included for function printf().
Similarly, conio.h() (console input/out header file) for functions clrscr() and getch(). Function
clrscr clears the screen. Function getch() is a character input funcion and it waits until a
character is pressed on the keyboard. But it is not compulsory to include stdio.h() and conio.h in
the above example to run the program. str[40] means the size o string is 40 characters. Function
gets() read a sequence of characters from the standard input device and store them in string str.
In the sequence, the number of characters should not be greater then 39 because each string must
be terminated by a null character and one byte is for null character. Function puts displays the
string stored in the string str.
Unformatted Function
Unformatted functions do not allow the user to read or display data in desired format. These type
of library functions basically deal with a single character or a string of characters. The functions
getchar(), putchar(), puts(), getch(), getche(), putch() are considered as unformatted functions.
The getchar() function makes wait until a key is pressed and then assigns this character to
character_variable.
Syntax : putchar(character_variable);
Example : Write a program to read a character from keyboard using getchar() function and
display on the screen using putchar() function.
int main(){
char gender;
printf("Enter gender M or F:");
gender=getchar();
getch() : This is a function gets a character from keyboard but does not echo to the screen. It
allows a character to be entered without having to press the Enter key afterwards.
Syntax : character_variable=getch();
getche() : This is a function that gets a character from the keyboard and echoes to the screen. It
allows characters to be entered without having to press the Enter key afterwards.
Syntax : character_variable=getche();
Syntax : putch(character_variable);
Example: Write a program to read two characters from keyboard: one using getch() & another
using getche() function and displays the characters using putch() function.
int main(){
char ch1, ch2;
printf("Enter 1st character:"); Output:
1st character: a
ch2=getch();
2nd character: b
printf("\n1st character: ");
putch(ch1);
printf("\n2nd character: ") ;
putch(ch2); getch();return 0;}
gets() : The gets function is used to read string of text, containing white space, until a newline
character is encountered. It can be used as alternative function for scanf() function for reading
strings. Unlike scanf() function, it does not skip white space (i.e. It can be used to read multiple
words string).
Syntax : gets(string_variable);
Example : Write a program to read a string with multiple words (i.e. string with space) using
gets() function and display on the screen using puts() function.
int main()
char name[20];
gets(name);
puts(name);
getch();
return 0;}
Output:
Unformatted input/output is the simplest and most efficient form of input/output. It is usually the
most compact way to store data. Unformatted input/output is the least portable form of
input/output. Unformatted data files can only be moved easily to and from computers that share
the same internal data representation. It should be noted that XDR (eXternal Data
Representation) files, described in Portable Unformatted Input/Output, can be used to produce
portable binary data. Unformatted input/output is not directly human readable, so you cannot
type it out on a terminal screen or edit it with a text editor.
Formatted input/output is very portable. It is a simple process to move formatted data files to
various computers, even computers running different operating systems, as long as they all use
the ASCII character set. (ASCII is the American Standard Code for Information Interchange. It is
the character set used by almost all current computers, with the notable exception of large IBM
mainframes.) Formatted files are human readable and can be typed to the terminal screen or
edited with a text editor.