0

I have a question

"Write a C program that accepts as input a single integer k, then writes a pattern consisting of a single 1 on the first line, two 2s on the second line, three 3s on the third line, and so forth, until it writes k occurrences of k on the last line."

For example, if the input is 5, the output should be the following:

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

I have written the below code to achieve this.

#include <stdio.h>
#include <stdlib.h>


int main() {
int k = 5;
int i;
int j;
for(i = 1; i<=k; i++){
    for(j = 1; j<=i; j++){
        printf('%d',i);
        }
    printf('\n');
    }
return 0;
}

When I run this program, Eclipse crashes. Is there something I am missing in the code I wrote ?

1
  • There should be at least a warning for printf('%d',i);. Commented Jul 24, 2015 at 18:46

5 Answers 5

3
printf('%d',i);

should be

printf("%d",i);

The first argument of printf() expects const char * and what you have is a character for it. Compiler should have thrown a warning for this before you went ahead and hit a crash. Don't ignore warnings!!

Sign up to request clarification or add additional context in comments.

Comments

3

You need to change

printf('%d',i);

to

printf("%d",i);

and also,

printf('\n');

to

printf("\n");

Reason: As per the man page of printf(), the function prototype is

int printf(const char *format, ...);

which says, the first argument should be a const char *.

Usually, " " is used to denote (const) char * as oppossed to ' ' which is used to denote a char constant.

Note: Enable warnings in your compiler and pay heed to them. Most of the time compiler warns you about the mistatch in agument and parameter type mismatch.

Comments

0

In printf, you have to pass the character pointer.

change this

printf('%d',i);

into

printf("%d",i);

printf definition.

   int printf(const char *format, ...);

Comments

0

If you look into documentation of C programming printf function require a string i.e. const char *format, and string is represented by double quotes(" "). So replace single quotes (' ') by double quotes (" ").

Comments

0

The output format for printf in c library is

printf("data type representation", the data to be printed);

So in output stream you must use double quotes instead of single. Following code will work fine,

 #include <stdio.h>

int main(void) {
    // your code goes here
    int k,i,j;
    scanf("%d",&k);
    for(i=1;i<=k;i++)
    {
        for(j=1;j<=i;j++)
        printf("%d",i);

        printf("\n");
    }
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.