Having a variable
h = get_int()
how do I print (using printf
) this variable
e = " "
h times? I know it may sound stupid, but I´m a rooky.
Having a variable
h = get_int()
how do I print (using printf
) this variable
e = " "
h times? I know it may sound stupid, but I´m a rooky.
Read up on C loops here
for(int i = 0; i < h; i = i + 1 ) {
printf("%s", e);
}
you probably mean printf...
int i;
for(i = 0; i < h; i++)
printf("%s ",e);
A while-loop would also be applicable. You can use the variable h
as a counter. It a while loop you would first print the number and then count the variable h
in a count-down manner until it is 0. This way you will have printed it exactly h-times
while(h>0){
printf("%s", e);
h--;
}
Disclaimer: this will of course change the value of h! If you depend on it to use it unchanged somewhere else then you should go for the for-loop solution
I guess this is what you asks.
#include <stdio.h>
#include <stdlib.h>
char *inputString(size_t size){
char *str;
int ch;
size_t len = 0;
str = realloc(NULL, sizeof(char)*size);
if(!str)return str;
while(EOF!=(ch=fgetc(stdin)) && ch != '\n'){
str[len++]=ch;
if(len==size){
str = realloc(str, sizeof(char)*(size+=16));
if(!str)return str;
}
}
str[len++]='\0';
return realloc(str, sizeof(char)*len);
}
int main(void){
char *e;
int times,i=0;
printf("input string : ");
e = inputString( 10);
printf("Number: ");
scanf("%d",×);
for(i=0;i<times;i++)
printf("%s ", e);
free(e);
return 0;
}
A for loop is the typical way to count iterations, but the syntax of a while loop may be more clear for a beginner:
int count = 0;
while (count < h) {
printf("%s", e);
count = count + 1;
}