Bill Cunningham said:
I don't know how to do this with spaces or for.
OK, it appears that you've not "got it" as I had hoped you might, so
here are the underlying ideas you need to move from "print a thing
that's hard-coded in the source" to "print a sequence of things that
can be computed".
- an 'int' variable can hold values from 0 up to INT_MAX (and down to
INT_MIN, but that's not important right now), where INT_MAX is at
least 32767
- 'printf()' can print the value of an 'int' variable, as well as a
literal string
- a 'for' loop can initialize a variable, loop around "doing stuff"
until that variable hits an upper limit, and increment the variable
after each time it has "done stuff"
(There are other concepts that could be used to implement this, like
'unsigned int', 'if', etc. They are also Not Important Right Now.)
Since you appear to need it, here's a template for you. Replace the
comments with source that does what's suggested.
#include <stdio.h>
int main(void) {
/* define an int variable called i */
for (/* set i to the value 0 */ ;
/* test to see that i is still less than 7 */ ;
/* increment i*/) {
/* print the value of i as a decimal integer */
/* print a space */
}
/* print a newline, since you only need one of them */
return 0;
}
The "a-ha!" moment I'm hoping you'll have here is the realisation that
the program does not need to have _everything_ laid out explicitly for
it, but instead its behaviour can be described at a higher level. For
instance, if question 3 was changed to ask for all the integers from 0
to 100 as output, then your first answer would need to have the string
extended by around 300 characters, but the above program would merely
need the test changed from "is i less than 7?" to "is i less than
101?". In the real world, specifications _do_ change like this, so
having a tool to make handling the change easy is an advantage.
So I will post another way of doing it and I don't know how to
include spaces. But the program works.
It only "works" because you were unlucky. Ben has given you an
example of a place where it doesn't "work", but you obviously don't
understand why.
#include <stdio.h>
int main (void) {
char a[]={'0','1','2','3','4','5','6'};
The line above creates an array of 7 characters only. What sits after
those characters in memory could be anything.
The "%s" format specifier must be given a string.
A string is a sequence of characters ending with a '\0'.
The array whose starting address you have passed is not a string.
The standard does not define what happens now.
In your case there just happened to be a '\0' sitting in the chunk of
memory immediately after 'a[]'; in Ben's there wasn't.
For now, don't think about using array notation until I suggest that
it might be handy for solving a particular problem.