×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

Formatted Input & Output using printf() and scanf()

printf()

This function is used to print text as well as value of the variables on the standard output device (monitor), printf is very basic library function in c language that is declared in stdio.h header file.

Syntax:

   printf(“message”);
   printf(“message + format-specifier”,variable-list);

First printf() style printf the simple text on the monitor, while second printf() prints the message with values of the variable list.

#include <stdio.h>

int main()
{
	printf("Message-1");
	printf("Message-2");
	printf("Message-3");
	return 0;
}

Output

Message-1Message-2Message-3

How to print value of the variables?

To print values of the variables, you need to understand about format specifiers are the special characters followed by % sign, which are used to print values of the variable s from variable list.

Format specifiers

Here are the list some of the format specifiers, use them in printf() & scanf() to format & print values of the variables:

    Character           (char)          %c
    Integer             (int)           %d
    Insigned integer    (unsigned int)  %ld
    Long                (long)          %ld
    Unsigned long       (unsigned long) %lu
    Float               (float)         %f
    Double              (double)        %lf
    Octal Value         (octal value)   %o
    Hexadecimal Value   (hex value)     %x
    String              (char[])        %s
    **NOTE** Use ‘u' for unsigned type modifier, ‘l' for long.

Escape Sequences

To print special extra line/spaces etc, we use escape sequences, these characters are followed by ‘\' (slash).

    \\			\
    \”			“
    \'			‘
    \?			?
    \a			Alert
    \b			Back space 
    \n			New Line
    \t			Horizontal tab
    \v			Vertical tab
    \r			Carriage return

Consider the following examples:

#include <stdio.h>

int main()
{
	int	num=100;
	float	val=1.23f;
	char	sex='M';

	//print values using different printf
	printf("Output1:");
	printf("%d",num);
	printf("%f",val);
	printf("%c",sex);

	//print values using single printf
	printf("\nOutput2:"); // \n: for new line in c
	printf("%d,%f,%c",num,val,sex);
	return 0;
}

Output

Output1:1001.230000M
Output2:100,1.230000,M

Padding integers with 0's / Spaces

Another important and useful concept is padding values with 0's or Spaces.

Padding with Space: Use %[n]d, here [n] is the number of characters, use %-[n]d for right space padding.

#include <stdio.h>
int main()
{
	int a=10;
	int b=1234;
	int c=11111;

	printf("\nLeft padded with spaces:");
	printf("\na=%5d \nb=%5d \nc=%5d",a,b,c);

	printf("\nRight padded with spaces:");
	printf("\na=%-5d,b=%-5d,c=%-5d",a,b,c);
	return 0;
}

Output

Left padded with spaces:
a=   10
b= 1234
c=11111
Right padded with spaces:
a=10   ,b=1234 ,c=11111

Padding with Zeros

Use %0[n]d, here [n] is the number of characters.

#include <stdio.h>
int main()
{
	int a=10;
	int b=1234;
	int c=11111;

	printf("\nLeft padded with 0's:");
	printf("\na=%05d \nb=%05d \nc=%05d",a,b,c);
	return 0;
}

Output

Left padded with 0's:
a=00010
b=01234
c=11111

Padding float values with 0's

Consider the following examples:

#include <stdio.h>
int main()
{
	float a=1.23f;
	float b=1.234f;
	float c=1.0f;

	printf("\na=%05f \nb=%08.3f \nc=%.2f",a,b,c);
	return 0;
}

Output

a=1.230000
b=0001.234
c=1.00

%05f – Since default float value prints 6 digits after precision & here is %05f, so no changes will be made.

%08.3f – “.3f” prints 3 digits after precision and “08” means padding with Zero (8 digits – including digits before and after the precision).

%.2f – 2 Digits will print after precision.

String formatting & padding with spaces

#include <stdio.h>
int main()
{
	char text1[]="includehelp";
	char text2[]="includehelp.com";
	char text3[]="http://www.includehelp.com";

	printf("\nWithout padding:");
	printf("\ntext1:%s \ntext2:%s \ntext3:%s \n",text1,text2,text3);

	printf("\nWith left space padding:");
	printf("\ntext1:%30s \ntext2:%30s \ntext3:%30s \n",text1,text2,text3);

	printf("\nWith right space padding:");
	printf("\ntext1:%-30s \ntext2:%-30s \ntext3:%-30s \n",text1,text2,text3);

	return 0;
}

Output

Without padding:
text1:includehelp
text2:includehelp.com
text3:http://www.includehelp.com

With left space padding:
text1:                   includehelp
text2:               includehelp.com
text3:    http://www.includehelp.com

With right space padding:
text1:includehelp
text2:includehelp.com
text3:http://www.includehelp.com

Print value in Decimal, Octal & Hexadecimal format

You can print integer value in following formats using following format specifiers:

    %d		-	Decimal
    %o		-	Octal (small ‘o')
    %x		-	Hexadecimal (alphabets will print in small case)
    %X		-	Hexadecimal (alphabets will print in upper case)

Consider the following example

#include <stdio.h>
int main()
{
	int val=32106;
	
	printf("\nDecimal	: %d",val);
	printf("\nOctal	    : %o",val);
	printf("\nHex		: %x",val);
	printf("\nHex		: %X",val);
	return 0;
}

Output

Decimal     : 32106
Octal       : 76552
Hex         : 7d6a
Hex         : 7D6A

scanf()

This function is used to get (input) value from the keyboard. We pass format specifiers, in which format we want to take input.

Syntax:

   scanf(“format-specifier”, &var-name);
   scanf(“fromat-specifier-list”, &var-name-list);

First type of scanf() takes the single value for the variable and second type of scanf() will take the multiple values for the variable list.

Consider the following examples:

#include <stdio.h>

int main()
{

	int	a;
	float	b;
	char	c;

	printf("Enter an integer number (value of a)?:");
	scanf("%d",&a);
	
	printf("Enter a float number (value of b)?:");
	scanf("%f",&b);
	
	printf("Enter a character  (value of c)?:");
	fflush(stdin); // to flush (clear) input buffer
	scanf("%c",&c);

	printf("\na=%d,b=%f,c=%c",a,b,c);
	return 0;
}

Output

Enter an integer number (value of a)?:1234
Enter a float number (value of b)?:1.2345
Enter a character  (value of c)?:G

a=1234,b=1.234500,c=G

Consider the following examples to read multiple value in single scanf statement:

#include <stdio.h>

int main()
{

	int	a;
	float	b;
	char	c;

	printf("\nEnter value of a,b,c (an integer, a float, a character):");
	scanf("%d%f%c",&a,&b,&c);

	printf("\na=%d,b=%f,c=%c",a,b,c);
	return 0;
}

Output

Enter value of a,b,c (an integer, a float, a character):1234 1.2345 G
a=1234,b=1.234500,c=  

Here, G will not store into c variable, because we are not flushing input buffer here. So either you will have to take input of c first or you will have to read value of c separately.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.