×

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

Argument index specification in printf in C programming language

Learn: How to specify the argument indexing with format specifier in printf statement in C programming language?

Consider the code:

int a,b,c;
a=10; b= 20; c=30;
printf("%d,%d,%d\n",a,b,c);

Here, output will be 10, 20, 30

Have you ever thought about the argument specification?
No?
Okay, let's discuss about it.

What is argument specification in printf?

We can specify the argument to print within the printf statement without changing the order of arguments (passing variables).

For Examples: statement printf("%d,%d,%d\n",a,b,c); will print 10, 20, 30

If we want to print 30, 20, 10 without changing the order of a,b,c, we can print do this.

How?

We have to just specify the number (index) of argument starting with 1 (Here, a is the first argument, b is the second and c is the third argument), with format specifier (%d).

Consider the statement:

printf("%3$d,%2$d,%1$d\n",a,b,c);

This statement will print the value of argument 3 first then argument 2 and then argument 1, thus output will be 30, 20, 10.

Consider the complete program:

#include <stdio.h>

int main()
{
	int a,b,c;
	a=10; b=20; c=30;

	//print in default order 
	printf("%d,%d,%d\n",a,b,c);
	//print with specifi the arggument indexing
	printf("%3$d,%2$d,%1$d\n",a,b,c);

	return 0;
}

Output

10,20,30
30,20,10

C Language Tutorial »





Comments and Discussions!

Load comments ↻





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