Suppose my code is
void main()
{
for(i=1;i<5;i++)
{
printf("%d, ",i);
}
}
The output of this program will be
1, 2, 3, 4,
How can I get output like
1, 2, 3, 4
The last , should be omitted.
Suppose my code is
void main()
{
for(i=1;i<5;i++)
{
printf("%d, ",i);
}
}
The output of this program will be
1, 2, 3, 4,
How can I get output like
1, 2, 3, 4
The last , should be omitted.
#include <stdio.h>
int main(void)
{
const char *pad = "";
for (int i = 1; i < 5; i++)
{
printf("%s%d", pad, i);
pad = ", ";
}
putchar('\n');
return 0;
}
You can't "delete" the character once you've printed it. You have to code so that you don't print what isn't actually wanted.
Use an if statement. For example
#include <stdio.h>
int main( void )
{
for ( int i = 1; i < 5; i++ )
{
if ( i != 1 ) printf( ", " );
printf( "%d", i );
}
putchar( '\n' );
}
The program output is
1, 2, 3, 4
Or for outputting a string.
#include <stdio.h>
int main( void )
{
const char *s = "1234";
for ( const char *p = s; *p; ++p )
{
if ( p != s ) printf( ", " );
putchar( *p );
}
putchar( '\n' );
}
Again the program output is
1, 2, 3, 4
By using if and else....!!!!
#include <stdio.h>
int main() {
// Write C code here
int i;
for(i=1;i<5;i++){
if(i==4){
printf("%d",i);
}
else{
printf("%d, ",i);}
}
return 0;
}