Staircase - Hacker Rank.
Consider a staircase of size :
#
##
###
####
Observe that its base and height are both equal to , and the image is drawn using
#
symbols and spaces. The last line is not preceded by any spaces.
Write a program that prints a staircase of size .
Function Description
Complete the staircase function in the editor below. It should print a staircase as described above.
staircase has the following parameter(s):
- n: an integer
Constraints
.
Output Format
Print a staircase of size using
#
symbols and spaces.
Note: The last line must have spaces in it.
Sample Input
6
Sample Output
#
##
###
####
#####
######
Explanation
The staircase is right-aligned, composed of
#
symbols and spaces, and has a height and width of .
SOURCE CODE
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
// Complete the staircase function below.
void staircase(int n) {
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if((i+j)>=(n+1)){
printf("#");
}
else{
printf(" ");
}
}
printf("\n");
}
}
int main()
{
char* n_endptr;
char* n_str = readline();
int n = strtol(n_str, &n_endptr, 10);
if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); }
staircase(n);
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) { break; }
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }
size_t new_length = alloc_length << 1;
data = realloc(data, new_length);
if (!data) { break; }
alloc_length = new_length;
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
}
data = realloc(data, data_length);
return data;
}
Click here to Download
i want to know what is cursor in fgets function
ReplyDeletepointer to an initialized string in which characters are copied.
Delete