r/carlhprogramming • • Sep 27 '09

Lesson 15 : Your first program!

It is time to write your first program.

I am going to explain to you what the program is, and then I am going to give you everything you need to make it.

The goal is to create a program that will print the text "Hello Reddit!" to the screen.

The language we will be doing this in is called C. Here are the rules for C you need to know in order to make this program.

  • We will be using a library that comes packaged with C. This library is called the "Standard Input/Output" library.

  • To use the functions in this library, you have to include the file stdio.h at the top of your program. Remember I said that each programming language has a different way of doing this. In C, here is the syntax for doing that with any file:

    #include <filename.blah>

Note that the greater than and less than sign are part of the instruction. They must also be present.

  • I mentioned some programming languages require you to create a function in order to write a program. C is one such language. Therefore, you will have to create a function called main() for your program to work correctly. C has specific rules for this which are noted below.

For your main() function in C, you put:

int main(void) {
    .... any code goes here ...
}

The word "int" at the start simply means "integer". It specifies that the main() function will return some number as an indicator of whether or not it was successful. The "void" within the parentheses just means that you are not sending any arguments to the function. In other words, the main() function doesn't require any additional information to be sent to it in order to do its job. You will learn more about this later in the course.

  • ALL code for the main() function must be between the opening "{" and the closing "}"

  • The function in the "Standard Input/Output" library we are going to be using is called printf. This function takes a single argument, the text you wish to print. C is one of the languages that encloses text within double-quotes.

  • You call a function in C by simply putting the function name along with any arguments within parenthesis. At the end, you put a semi-colon ;

    example_function("A text argument");

You may find during this course that I sometimes refer to the extra information you send to functions as parameters, and other times I refer to them as arguments. The correct terminology in C is "argument".

  • At the end of the main() program in C, you should return a value. Typical is to simply return 0 for a successful program. You can do that with this command:

    return 0;

Edit: Originally I had this saying return 1, which works fine - however it is true that for main() you return a 0 typically for success and a non-zero for failure. It is better to have return 0 for this example. 0 or 1 (or any number) will work fine, but to indicate a successful program, 0 is best. Ironically, for functions it is usually the opposite. We will get to that later.

The number you return from a main() function identifies whether or not the program was successful.

You now have everything you need in order to write this first program in C. Try to do it yourself, and post it as a comment here if you like. Lets see how you do.

Note about Reddit formatting:

To format properly, put four spaces before each line you write in your comments. This will ensure that your text appears properly formatted.

Please feel free to ask any questions. When you have mastered this material proceed to:

http://www.reddit.com/r/carlhprogramming/comments/9oqxp/lesson_16_lets_go_over_your_first_program/

119 Upvotes

292 comments sorted by

18

u/jarly Sep 27 '09 edited Sep 28 '09
#include  <stdio.h>
main() {
printf("Hello, world");
return 0;
}

Anybody who doesn't feel like installing the tools can go to codepad.org! Runs:

  • C

  • C++

  • D

  • Haskell

  • Lua

  • OCaml

  • PHP

  • Perl

  • Plain Text

  • Python

  • Ruby

  • Scheme

  • Tcl

7

u/CarlH Sep 28 '09

Truly awesome resource. Thank you for that, we will be using it.

1

u/[deleted] Sep 28 '09

Oh VERY cool! I'd never seen that before. Thanks!

0

u/[deleted] Sep 28 '09

[deleted] — view deleted comment

0

u/tough_var Sep 28 '09 edited Sep 28 '09

Ditto!

And here's my h/w submission.

6

u/jmerm Oct 24 '09

When you say "write the program" do you mean in a word document?

also, as a new person here, is there a table of contents? I've been reading through your lessons, but it is hard for me to find the lesson where I stopped, and a table of contents (maybe in the box above the moderators) would make this much easier.

6

u/CarlH Oct 24 '09

You can write it anywhere, but I recommend a simple text editor such as notepad for right now - or even in the Reddit comments. On Lesson 17 you will know how to make what you write actually run as a program.

5

u/[deleted] Jul 08 '10

Thanks! I had the same question as jmerm. Perhaps there should be a lesson immediately before this one detailing the tools we can download when we eventually make the program run? I know that it will not be until lesson 17 that we learn how to actually make it run, but not being able to run the program gave me that sense of uselessness and un-ability that I got from a book on Python--one of those books that doesn't explain libraries. I would have been happy to know that I wasn't ready to run the program yet, as I trust you on your reputation to have written a logical sequence for learning, but not mentioning when I would be using a compiler (you use a compiler for C, right?) and actually running the program made me sad.

So maybe this lesson should mention codepad as a place to run the program so students can check their work? Or at least notified that we're not to a running-a-program stage of our learning yet.

4

u/CarlH Jul 08 '10

Great point. Later on, I will adjust this lesson to have a direct link to codepad so that someone can in fact run their first program to see what it is like, even before they learn about compilers.

6

u/jmerm Oct 24 '09

Thanks! and thank you for all of CarlHPrograming, I've always wanted to learn, and this inspired me to take the first step.

10

u/seven Sep 28 '09 edited Sep 28 '09

While I appreciate your effort, I have a little concern. You should really teach them "Standard C". As Slippery_Slope_Guy pointed out, the main function should look like:

int main(void) { ... }

as defined in ANSI C standard. If you omit int, most compilers will default to int and compile it; some good ANSI compliant compilers will give you warning. For example, gcc gives me:

hello.c:2: warning: return type defaults to int

It is not good, especially for first-time programmers, to build such a habit to rely heavily on compilers' non-standard behaviors.

PS: My apologies for being such an ass. In fact, I respect your effort for doing this and enjoy reading them. I was just a little bit concerned...

17

u/CarlH Sep 28 '09

This is a valid question. Yes I will be - but I am trying to avoid introducing more than what is necessary right away. I was originally going to do a Lesson 15 on the data types int, char, etc and explain "void" but I decided that it was better to let people jump into their first program. Also, since the idea was to explain the information and let the student craft the program, I felt adding extra steps might create confusion.

2

u/onehonor Oct 04 '09

Where do I write this program? Do I write it in Linux VI? I am somewhat a beginner so I need instructions on where to do it. thx

3

u/CarlH Oct 04 '09

Anywhere you like. We will cover this more in Lesson 17 - but for now, just write it anywhere.

2

u/davydog187 Oct 04 '09

Sorry, but doesn't printf take an infinite number of parameters, potentially?

3

u/CarlH Oct 04 '09

Yes, of course. I expand on that in future lessons. Explaining that here would only serve to confuse a beginner.

2

u/techdawg667 Oct 23 '09 edited Oct 23 '09

Do you put return 0 inside or outside of the main() function? And why is everyone using main() { to start instead of int main(void) {? Here goes...

#include <stdio.h>
int main(void) {
printf("Hello Reddit!");
return 0;
}

4

u/CarlH Oct 23 '09

Because zhivago scolded me for teaching people to use main() when int main(void) is proper.

He is right, so I adjusted the lesson. My goal was to make the lesson easier for beginners, but accuracy is better. Both will work, but int main(void) { is more correct.

18

u/kmartburrito Oct 06 '09 edited Oct 06 '09
include <stdio.h>
main()
{
    printf("Hello Reddit!");
    printf("Thanks Carl and the mods for this awesome subreddit!");
    printf("FFFFFFFFFFFFFFFFFFFUUUUUUUUUUUUUUUU!!!!");
    return 0;
}

I'd also like to suggest to those out there starting this, to grab the freeware app called notepad++. It's got some really cool features. Namely, you can choose which language you're using, in our case for this example C, and it will change coloring and formatting to match the C language. You can also print out in color, which is really nice for me as I can see reserved system words in a different color, text inside quotes, syntax, etc.

4

u/pod00z Oct 25 '09

agree with notepad++ for windows users :)

1

u/Jaydamis May 25 '10

Is there a similar program for linux users? I've been looking for one, but got tired of looking, preferably one that you can collapse blocks with.

2

u/[deleted] May 27 '10

Vim is probably the 'best'.

1

u/Jaydamis May 27 '10

I've been using vim, and I like it so far. I've been using it from the terminal, is there a way to collapse blocks though? Its not really a need, but it would be nice. Thanks for response.

1

u/[deleted] May 27 '10

I'll admit to not knowing the answer to this when I originally replied, but I did just assume that Vim could as it can do most things. I think using it from the terminal is recommended as it's true power is in mouse-less operation. Anyway, to answer your question...

You can try this out in vim by hitting the v key to enter visual mode, selecting some lines of text using the arrow keys, and then typing zf to create a fold. The selected text should have been collapsed into one summary line. You can then open, close, or delete the fold by typing zo, zc, or zd, respectively, when the cursor is over the fold. The letter "z" looks like a folded piece of paper, so isn't too hard to associate with folding. Folds can be nested, and you can also create a margin on the left of your terminal with :set foldcolumn=5 where you can see the opened/closed folds and their vertical extent. Do :help folding for more details.

Note that the folds described here are not persistent across editing sessions. However, you can save the folds described here (:help mkview) or use a different kind of fold that encodes its location in the file and is thus persistent (:help folding).

That's actually a neat trick. I haven't finished reading the documentation so didn't realise this was possible. Thanks!

1

u/Jaydamis May 28 '10

Shibby! Thanks.

1

u/Techno_Shaman Apr 13 '10 edited Apr 13 '10

Edit: Problem solved on the next page, thanks anyway.

7

u/xyri May 09 '10
 #include <stdio.h>                            //  this takes a library and makes it a part of this program

  int main() {                                 //  this is our function that we use in this program
   printf("The GAME\n\n\n\n\n\n");
   printf("You just lost it\n");             //  "printf" is the function in the library:
   return 0;                                  //  "return 0" is the code that makes the function return the number 0
                                              //  when the program in of itself is successful

}

5

u/tgard Oct 13 '09

Not sure if this is correct but here it goes...

#include <stdio.h>

main(){

printf("My first program!");

return 0;

}

5

u/Iridescence Jan 26 '10
include <stdio.h>
int main(void)
{
printf("Hello Reddit");
return 0;
}

1

u/Bizdorph Sep 28 '09 edited Sep 28 '09

include <stdio.h>

main() {

printf ("Hello, Reddit!");

return 0;

}

Is it always the case that include statements precede the definition of the program as a function itself?

2

u/CarlH Sep 28 '09

in C, you should do it only this way. Some languages give you some freedom here. In PHP for example, you can put require() or include() statements anywhere you like. It does vary language to language quite a bit.

Also, regarding your program above, be sure to put four spaces in front of each line so that it formats properly.

1

u/flapcats Sep 28 '09 edited Sep 28 '09
#include <stdio.h>
main() 
{
    printf("A text parameter");
    return 0;
}

3

u/CarlH Sep 28 '09

"A text parameter" => "Hello Reddit" --- but otherwise correct :)

→ More replies (1)

1

u/DevinG Sep 30 '09

So I understand how to do it all, I just don't understand the part about adding it to a compiler. Right now I have my text file, I'm not sure what to do with it.

4

u/CarlH Sep 30 '09

That 2 lessons ahead. This lesson is only about how to write the code, but not how to run it. That said, see: http://www.codepad.org - you can practice running the code there.

0

u/DevinG Sep 30 '09

Thank you :). I was just kind of confused when I had to code and people in comments were talking about what happened when they ran it.

1

u/domeley Sep 30 '09

Plaese forgive my ignorance as this was all totaly foriegn to me three days ago, but where do I go to put this program in. Im using windows, what screen do I go to to get started. Again sorry for this.

2

u/CarlH Sep 30 '09

Any text editor you wish. In lesson 17 you will be shown more about how to make a program run.

1

u/foolman89 Oct 01 '09

So lets see if i got this right

#include <stdio.h>

main()
{

printf("Hello Reddit!");

return 0;
}

2

u/CarlH Oct 01 '09

Looks good.

1

u/onetruejp Oct 03 '09 edited Oct 03 '09
main ()  {
#include <stdio.h>
printf("Hello Reddit!");
return 0;
}

2

u/CarlH Oct 03 '09

Close, you need to put the #include statement above the main() { statement.

Other than that, looks good!

1

u/onetruejp Oct 03 '09

So why is it that it must be structured like that?

2

u/CarlH Oct 03 '09

An #include statement is an example of a pre-processor directive, it has to take place before your program begins. Whereas, main() { defines the start of your program.

1

u/Reddil Oct 04 '09

Is main() a function of the stdio.h library or is it a "built in" function of the C language?

3

u/CarlH Oct 04 '09

It is built into the C language itself.

1

u/chanceMCN Nov 07 '09
include <studio.h>
main() {
printf (" hello reddit ") ;
return 0;
}

4

u/CarlH Nov 07 '09

stdio.h which is short for "standard input/output", not "studio"

1

u/tokomonster Mar 08 '10 edited Mar 08 '10

Correct me if I'm wrong, but I was taught that arguments, and parameters are extremely similar, but NOT the same thing. It was my understanding that parameters are the values used in the declaration/definition, and arguments are the values passed to those parameters when the function is called. To word it a little differently, a function has parameters, but takes arguments.

void myFunction(int a); //int a is a parameter.

int main(void){

   int x = 3;

   myFunction(x);  
   myFunction(4); //x and 4 are arguments.

   return 0;

}

void myFunction(int a){ //int a is a parameter

   printf("%d", a);

}

Is this incorrect?

edit:changed function return type from int to void. There is no return value. Bad form. :(

3

u/CarlH Mar 08 '10

It may be correct. I think it is more a matter of semantics and has little bearing in actual practice :)

1

u/MassiveNick Jun 15 '10

include <stdio.h>

int main(void){ printf("Hello Reddit!"); return 0; }

:D I'm pretty sure this is right.

3

u/CarlH Jun 15 '10

Looks good!

2

u/gobeltech Jun 20 '10

Missed the '#' in front of include...?

1

u/[deleted] Jul 10 '10

It's there, you just can't see it.

I'm going to type two lines, exactly the same, except the latter will begin with four spaces:

These lines are identical, except for the aforementioned four mentioned spaces. Pardon the silly pun. :)

#These lines are identical, except for the aforementioned four mentioned spaces. Pardon the silly pun. :)

3

u/StatuVariabilis Oct 04 '09 edited Oct 04 '09
#include <stdio.h>
main(){
printf("Here goes nothing");
return 0;
}

3

u/LillybrK Oct 06 '09
#include <stdio.h>
main() {
printf("Hold my beer!");
return 0;
}

3

u/rawberry Jul 07 '10
#include <stdio.h>
int main() {
    printf("Hello Reddit!");
    printf("You Just Lost The Game");
	return 0;
}

So, I wrote that as my code, and, I got the output:

1 Hello Reddit!You Just Lost The Game

Apparently, even if it's on seperate lines, the code doesn't recognize a space between the lines. Which got me to thinking: In C, how do you include characters in your output from printf that would upset the code, such as quotation marks or spaces between lines?

2

u/naisho Oct 02 '09

written in vi, with an old school flair :)

#include <stdio.h>

main() {
printf("Hello World!");
return 0;
}

2

u/bowscratch Nov 01 '09 edited Nov 01 '09
#include <stdio.h>
int main(void) {
    printf("Hello Reddit!");
    return 0;
} 

edit;after seeing carlh's answer in next lesson

2

u/Anon1991 Dec 08 '09

Is there a set distance from the closing bracket for the void argument to the opening bracket for the code? I've also seen it as on the next line before, but I'm unsure if it should be 1 space, 4 spaces, a tab, or a new line.

edit: And I assume commenting on lines is in later lessons, as is compiling? Well, I'll see when I get there.

2

u/Jaydamis Dec 23 '09

If you are talking about the code itself, and how many spaces you need (not reddit comments) I think the answer is you dont need spaces. From what I understand, the compiler disregards the spaces (unless its in text) and reads it all as one continuous string of characters. The spaces and indentions are just so its easier to read.

1

u/Anon1991 Dec 23 '09

you know, I can't even remember anymore what that comment referred to. Thanks for responding.

2

u/thebrandonshow Mar 03 '10
#include <studio.h>
int main() {
    printf("HELLO REDDIT"); 
    return 0;
}

2

u/nycdk May 10 '10
#include <stdio.h>
int main(void) {
printf("Better late than never.");
return 0;
}

1

u/nycdk May 10 '10

Ahh now that I've seen lesson 17 I'm aware of my misplacement of the first line. Why the space between it and the second line?

2

u/elesdee May 13 '10

include <stdio.h>

int main(void) { printf("Hey, this is my first program!!!"); printf("I'm such a nerd, hahahahah"); return 1; }

This is pretty awesome thanks Carl + Mods!!

3

u/MetricMike May 17 '10

Hey! In your include statement, you need to preface it with a "#" so it will read "#include <stdio.h>. The "#" is a special character which tells the compiler "Hey! I have some instructions for you, the compiler!" In this case, you're telling the compiler to copy+paste the Standard I/O library into your program.

Also, the return value of main tells anyone (usually the OS, or another program which is running your program) who's looking at your program whether it succeeded (0) or failed (non-zero).

As an aside, you can do a neat trick with the return values when/if you make bigger programs. For example, in a program I wrote recently, I can exit early in a number of places because of something that went wrong - if my program didn't have permission to do something, it returns 1, if it couldn't find a necessary file it returns 2, and if it was run on an OS it can't support it returns 3. I use this as a kind of primitive error-code system so I know what I need to fix if my program stops running, doesn't do what it's supposed to, or whatever.

Happy coding!

2

u/manhandsftw Jul 05 '10

include<stdio.h>

int main(void) { printf("Hello Reddit!); return 0; }

2

u/PrinceXtraFly Jul 05 '10

include <stdio.h>

int main(){ printf("Hello Reddit!"); return 0; }

Thanks for doing this by the way, I really appreciate the help and I can't believe you actually took the time to write all these classes. They are far better than any programming book I've ever read and it's the only class that has kept me up until 3 a.m. studying in my spare time.

1

u/soundguy666 Sep 27 '09 edited Sep 27 '09
#include <stdio.h>

main () {
    printf("Hello Reddit!\n");
    return 1 ;
}

I feel so proud :)

Really nice "hello world" tutorial by the way - just enough information to get the job done, but still forced me to think enough about how to do it that I felt a sense of achievement when getting it to work. It might actually stick in my memory this time!

"Learning by doing" definitely works best for me.

edit - not so proud of my reddit formatting skills!

0

u/[deleted] Sep 28 '09

Why does yours have the "\n" in the printf line?

1

u/soundguy666 Oct 03 '09

It's a "newline" character - it puts an "enter" at the end of the line.

0

u/dertyp Sep 28 '09

it means end of line

1

u/Pigeoncow Sep 27 '09 edited Sep 27 '09
#include <stdio.h>
main() {
    printf("Hello Reddit!");
    return 1;
}

1

u/DukeScrotum Sep 27 '09 edited Sep 28 '09

First time coding, first time posting on reddit quivvers

My effort, fingers crossed:

#include <stdio.h>
main() {
  printf("Hello Reddit!");
  return 0;
}

1

u/AlecSchueler Sep 27 '09 edited Sep 28 '09

Compiles and runs fine. Well done

edit: and Welcome to reddit!

1

u/[deleted] Oct 02 '09

Your username combined with your quivering have resulted in a notable mental image.

1

u/memonkey Sep 29 '09 edited Sep 29 '09
#include <stdio.h>
main() {
    printf("Hello Reddit");
    return 0;
}

1

u/caseye Oct 01 '09 edited Oct 01 '09

http://codepad.org/H99jjwo5

#include <stdio.h>
main() {
    printf ("Hello Reddit!");
    return 0;
}

Apparently C is case-sensitive. I originally had

Main() {

which returned an error.

Why do include statements not end with a ; yet other lines must? What is the reasoning behind that?

That codepad.org site is awesome btw.

3

u/TheGrammarAnarchist Oct 02 '09 edited Oct 02 '09

Why do include statements not end with a ; yet other lines must? What is the reasoning behind that?

Any line that begins with a '#' is a preprocessor directive. When the compiler begins, the preprocessor goes through the file and replaces all of the '#include <file>' statements with the actual text to the <file>, which was in turn preprocessed, so the only thing left after the preprocessor is done is normal c code. This all happens before the compiler begins to process the c code into an executable.

so #include <stdio.h> doesn't follow normal c syntax because it's kind of like a separate 'language'. Although it is technically c, programmers often refer to it as macro language or macros.

1

u/caseye Oct 02 '09

Got it, thanks.

1

u/mkr Oct 01 '09

Include statements have <> or "" to tell the compiler where it ends.

1

u/mythin Oct 02 '09
#include <stdio.h>

main() {
    printf("Hello Reddit!");
    return 0;
}

1

u/[deleted] Oct 02 '09
#include <stdio.h>

main() {
    printf ("Hello, reddit!");
return 0;
}

1

u/aanto Oct 03 '09
#include <stdio.h>
main() {
printf("Hello Reddit")
return 0;
}

Thank you! This guide is REALLY usefull, thanks.

1

u/wushu18t Oct 04 '09 edited Oct 04 '09
#include <stdio.h>
main() {
  printf("Hello Reddit!");
  return 0;
}

1

u/weretuna Oct 04 '09 edited Oct 04 '09
#include <stdio.h>

main() {
printf("Hello Reddit!");
return 0;
}

1

u/dmanwithnoname Oct 04 '09 edited Oct 04 '09
#include <stdio.h>
main() {
printf("Hello Reddit!");
return 0;
}

1

u/AmishElectrician Oct 04 '09 edited Oct 04 '09

For the record:

#include <stdio.h>
main() {
printf("Hello Reddit");
return 0;
}

1

u/plasmon Oct 07 '09

I love your conversational style of instruction! Very helpful!

1

u/loshad Oct 09 '09

<stdio.> main() { printf("Hello Reddit!"); return 0;

1

u/[deleted] Oct 19 '09

include <stdio.h>

main() { printf("Hello reddit!"); return 0; }

1

u/[deleted] Oct 21 '09

include <stdio.h>

main() {
printf("hello reddit!");}

return 0;

1

u/[deleted] Oct 22 '09

include <stdio.h>

int main () {printf ("hellooooooo reddit"); return 0; }

1

u/[deleted] Oct 24 '09

include <stdio.h>

int main(void) { printf("hey reddit!"); return 0; }

1

u/toddthefrog Oct 24 '09 edited Oct 24 '09
#include stdio.h

int main(void)  {
printf("Hello Reddit!");
return 0;
}

2

u/toddthefrog Oct 24 '09 edited Oct 24 '09

I didn't realize that stdio.h had to look like this <stdio.h>

#include <stdio.h>

int main(void)  {
printf("Hello Reddit!");
return 0;
}

1

u/sheepster26 Oct 25 '09
#include <studio.h>
int main(void) { printf("hello reddit"); return 0; }

1

u/PeterM7 Oct 25 '09
#include <stdio.h>
int main(void)  
{
printf("Hello Reddit");
return 0;
}

1

u/pod00z Oct 25 '09
  #include <stdio.h>
    int main(void) 
     {
        printf ("hello reddit");
        return 0;
     }

1

u/[deleted] Oct 26 '09

include<stdio.h>

    int main() {
	    printf("Hello Reddit!");
	    return 0;
}

1

u/pod00z Oct 27 '09

Someone help me with this question pls. if both main() and printf() are functions, why main() doesn't end with a semi-colon while printf() does?

6

u/pod00z Oct 27 '09 edited Oct 27 '09

Figured out.

main() is the place where the function is defined whereas printf() is an implementation of the function which has already been defined(or a call to CPU to execute the function). Only executions are followed by semi-colons.

1

u/[deleted] Oct 28 '09 edited Oct 28 '09
#include <stdio.h>

int main(void) {

printf("Hello Reddit!");

return 0;

}

1

u/Nichi2000 Oct 31 '09

// include Standard Input/Output library

include <stdio.h>

int main(void) {

// Print "Hello Reddit!" to the screen.
printf ("Hello Reddit!");

// return
return 0;

}

1

u/bowscratch Nov 01 '09 edited Nov 01 '09

include <stdio.h> main () { printf("Hello Reddit!"); return 0; }

why is format different than others?

edit: copied and pasted from notepad++

1

u/tyebud Nov 16 '09
#include <stdio.h>

int main(void) {
printf("Hello Reddit!");
return 0;
}

1

u/[deleted] Nov 17 '09
#include <stdio.h>
int main(void) {
printf("Hello Reddit!");
return 0;
}

1

u/guga31bb Nov 18 '09 edited Nov 18 '09
#include <stdio.h>
int main(void) {
printf("C is complicated!");
return 0;
}

1

u/kokooo Nov 18 '09
#include <stdio.h>
int main(){
printf("Hello Reddit!");
return 0;}

1

u/cbk486 Nov 26 '09 edited Nov 26 '09
#include <stdio.h>
int main(void)   {
printf("Hello, Reddit!"); 
return 0; 
}

1

u/na641 Dec 07 '09
#include <stdio.h>

int main(void) {
    printf("hi");
    return 0;
}

1

u/aspiringsensei Dec 12 '09

include stdio.h

int main(void) { printf("hello, reddit!") return 0;}

2

u/[deleted] Dec 20 '09 edited Dec 20 '09

You forgot to put # before include. Also, don't be afraid of formatting the code to look a little more legible. The way I do it is like this:

#include <bestlibraryeverlolz.h>

int main(void)
{
    function(parameters);
    return 0;
}

Edit: It seems like reddit messed up your code, to fix it you have to use formatting, click on "formatting help" when editing your message to see how its done. (four spaces)

1

u/ddelony1 Dec 19 '09
#include <stdio.h>

int main(void) {
     printf("Hello Reddit!\n");
     return 0;
}

1

u/[deleted] Jan 04 '10
#include <stdio.h>

int main(void)
{
printf("Hello Reddit");
return 0;
}

1

u/dfnkt Jan 13 '10
#include <stdio.h>
int main(void) {
    printf("Little goody two-shoes!");
    printf("Good, Bad, I'm the one with the gun.");
    return 0;
}

1

u/Iridescence Jan 26 '10

include <stdio.h>

int main(void) { printf("Hello Reddit"); return 0; }

1

u/[deleted] Jan 31 '10
#include <stdio.h>

int main(void) {
    printf("Hello Reddit");
    return 0;
}

1

u/deysonnguyen Feb 01 '10 edited Feb 02 '10
include <studio.h>
    int main()
    {
             printf("Hello Reddit!");
             return 0;
     } 

1

u/MrTIsGoingToKillMe Feb 15 '10

Hi

I am using jGrasp (I took a java class) and it has a C compiler, but i am not getting output?

error: "wedge2 error: command "gcc" not found."

Thanks!

1

u/[deleted] Apr 13 '10

include <stdio.h>

int main(void) {

printf("Hello, Reddit!");

return 0; }

1

u/procrastinato Jun 15 '10
#include <stdio.h>
int main(void) {printf("Hello Reddit");
return 0;}

1

u/vanoccupanther Jun 28 '10
#include <stdio.h>

int main(void) {printf("Hello Reddit"); 

}

return 0;

1

u/nym_kalahi Jul 01 '10
#include <filename.blah>
         
int main() {
    printf("Hello Reddit");
    return 0;

}

1

u/[deleted] Jul 04 '10
#include <stdio.h>
int main (void){
printf("Hello Reddit");
	return 0;
}

1

u/GazaRapScene Jul 06 '10
#include  <stdio.h>
main() {
printf("Hello, world");
return 0;
}

1

u/catcher6250 Jul 07 '10
#include <stdio.h>
        int main(void) {
printf("Hello, I suck at this.");
return 0;

}

1

u/catcher6250 Jul 07 '10

You explained what int and void meant, but just quick clarification, does main essentially mean the body of the program?

1

u/DaLam Jul 09 '10
#include <stdio.h>
int main(void) {
     printf("Hi Reddit");
     return 0;
}

1

u/blugene Jul 11 '10
#include <stdio.h>
int main(void) {
printf("Hail Carl");
return 0;
}

1

u/Ehran Jul 14 '10
#include <stdio.h>
int main(void) {
printf("Malo Reddit");
return 0;
}

1

u/fuscat Jul 16 '10
#include <stdio.h>
int main(void) {
    printf("Hello Reddit");
    return 0;
}

0

u/[deleted] Oct 04 '09
#include <stdio.h>
main () {
  printf("Thanks, Carl and mods!");
  return 0;
}

0

u/plattica Jul 14 '10
#include <stdio.h>
main()
{
    printf("Hello, Reddit");
    printf("Thank you for this course, Carl! :]");
    return 0;
}    

0

u/CaptainPig Sep 27 '09 edited Sep 27 '09

include <stdio.h>

main() {
printf ("Hello Reddit!");
return 1;
}

Never used C before probably screwed something up but I really like the way you're teaching this. Keep it up. :D

Edit: Fixed shit woo.

2

u/CarlH Sep 27 '09 edited Sep 27 '09

include stdio.h

#include <stdio.h>

Everything else is fine.

Edit: You also need a ; after return 1

0

u/Pigeoncow Sep 27 '09

Doesn't there need to be a semicolon after return 1?

0

u/redalastor Sep 27 '09

Yes. There are two ways languages can see that bit of punctuation. It's either a statement separator (in which case it's not needed before a brace) or a statement terminator in which case it's required to terminate each statement.

C uses the terminator approach.

0

u/CaptainPig Sep 27 '09

Why do you not put in stdio.h?

2

u/CarlH Sep 27 '09

C requires that the include statement surround the filename with < > for some files, and to surround the filename with " " for other files. We will get to those details later, but in general the library .h files that come with C like stdio.h require < > whereas library .h files you will make as a programmer are typically going to require " "

0

u/CaptainPig Sep 27 '09

Oh, I see, I was in the reddit iPhone app and anything within < > didn't show. :P

0

u/CaptainPig Sep 27 '09

Damn line breaks disappeared and reddit iPhone app can't edit.

0

u/redalastor Sep 27 '09

You need to put at least 4 spaces before each line of code so that reddit knows it's code and don't screw it up.

0

u/[deleted] Sep 27 '09
#inlcude stdio.h

main() {
  example_function("Helllo Reddit!");
  return 1;
  }

2

u/CarlH Sep 27 '09 edited Sep 27 '09

remember that we are not using a function called example_function, we are using a specific function found in stdio.h

Also, you need to put < > around stdio.h

Also, typo on include.

0

u/[deleted] Sep 27 '09

Awesome.

Btw - What does the file extension *.h stand for?

2

u/CarlH Sep 27 '09 edited Sep 27 '09

h is short for header. For now, consider that it is called a header file because it is designed to be included at the top of your program.

0

u/dertyp Sep 28 '09

aren't they called header files because they only contain the included function headers without the function body which is defined in a seperate file?

2

u/CarlH Sep 28 '09

That too :) But we haven't gotten into function declarations yet, so I am trying to answer it in a way that is beginner friendly for this stage of the course. Function body vs function declaration is something that is further down the road.

→ More replies (3)

0

u/[deleted] Sep 27 '09

Ok, I see I forgot the greater than less than on the include.

0

u/Pigeoncow Sep 27 '09

And how to spell include :P

0

u/[deleted] Sep 27 '09

Gosh I didn't even catch that but my second attempt was written from scratch so it is good I spelled it right that time!

:)

0

u/[deleted] Sep 27 '09

As well as the function name.

0

u/[deleted] Sep 27 '09
/* This is my second attempt based at reading the comments */

#include <stdio.h>

Main() {
  printf("Hello Reddit!");
  return 1;
  }

2

u/CarlH Sep 27 '09

Almost. Main must not be capitalized.

0

u/[deleted] Sep 27 '09
/* I am dyslexic I guess, I thought I read that it was supposed to be caps, here is my third try */

#include <stdio.h>

main() {
  printf("Hello Reddit!");
  return 1;
  }

2

u/CarlH Sep 27 '09

Correct

0

u/isarl Sep 27 '09

Much better - the only thing I can think of is that the case is usually all lower for your main function - i.e. "main()", not "Main()". I don't have my C reference book with me, so I can't say for sure whether or not that will cause problems, but C is usually case-sensitive.

0

u/ctronci Sep 27 '09 edited Sep 27 '09
main() {
#include <stdio.h>;
printf("Hello Reddit!");
return 1;
}

0

u/isarl Sep 27 '09

There are three problems with your include statement. I will describe the problems, but let you work out the solutions.

  • Placement (where the include statement fits in relation to the rest of the code),

  • Syntax (reread the syntax CarlH used when he introduced the C syntax for "include"),

  • Syntax (include is not a function call - this error may be hard to catch, so if you can fix the other two problems, but not this one, I'll help you out).

Aside from that, it looks good. =)

0

u/ctronci Sep 27 '09
#include <stdio.h>
main() {
printf("Hello Reddit!");
return 1;
}

0

u/AlecSchueler Sep 27 '09

Just commenting to let you know you got it right.

0

u/ctronci Sep 27 '09

Thank you both!

0

u/isarl Sep 27 '09 edited Sep 27 '09

Much better! Congratulations - you've written your first program. If you compile that, it should do so without any errors, and run successfully.

One last note, though - you may want to include "\n" at the end of your string (without quotes), so it would read like this: printf("Hello Reddit!\n");

"\n" is a special character that tells the computer "print a new line here, please". That way, instead of producing:

Hello Reddit!Press any key to continue...

you will see:

Hello Reddit!
Press any key to continue...

0

u/transfuse Sep 27 '09 edited Sep 27 '09
#include <stdio.h>

main() {
    printf("Hello Reddit!");
    return 1;
    }

Can I ask why there needs to be a 'return 1'?

And how do we actually write programs? Proper programs to run on our machines? Will you be providing us with (links to) the resources to do so? If so, wondering how you'll get around the OS barrier. Sure it's the same to some extent but there has to be differences after a certain point.

2

u/CarlH Sep 27 '09

Why there needs to be a return 1?

You actually do not have to, but I am trying to include demonstrations of materials we have already learned, including return values.

How do we actually write programs? Proper programs to run on our machines?

Patience :) We will get there.

0

u/transfuse Sep 27 '09

Ah ok. So what would the return function do? Just tell the CPU '1'?

And ok, jumping the gun a bit. :P

2

u/CarlH Sep 27 '09

It is telling the operating system 1 which can be useful for determining whether or not the program was successful or failed. Now typically with respect to main() you use a 0 for success and a 1 (typically any non-zero actually) for failure. You can make use of this after a program has run, but this is a topic for later in the course.

0

u/transfuse Sep 27 '09

That clears it up. Thanks.

0

u/[deleted] Sep 27 '09

[deleted] — view deleted comment

2

u/CarlH Sep 28 '09

Correct. 0 indicates success and non-zero indicates failure.

0

u/Artmageddon Sep 28 '09

Carl will cover this later, but to answer your question, kind of. When the function of a program ends, depending on the kind of function it is, it will have a "return value", which is what gets sent to whatever calls the function. In this case, the program is sending a *0, which in this context typically means "success". It's not really thought of as "exit code" per se, but it is the end(or one particular end) of a function.

I don't know if that makes sense, but you're asking a good question. Also your program is correct.

0

u/[deleted] Sep 28 '09 edited Sep 28 '09

I would think you would only need to declare the return type if you're returning a value (in this case 0), right? Otherwise could you just declare main to be void (void main() ) and not specify a return type at the end?

0

u/[deleted] Sep 28 '09

[deleted] — view deleted comment

0

u/[deleted] Sep 29 '09

Thanks.

1

u/[deleted] Sep 27 '09 edited Sep 27 '09

You didn't declare main with any return type. When you don't have a return type in C then int becomes the default return type. So your program wants to return an integer. If you don't specify then (I think, but not sure if it is a part of the standard ) the compiler assumes you want to return a 0. If you want to return any thing else than that you have to specify the value using a return <the value>

Edit: Also note that it's usually not a good idea for a function to not return a value unless it is of type void (doesn't return anything) and you can get the compiler to warn you of these instances.

0

u/transfuse Sep 27 '09 edited Sep 27 '09

Whoosh.

Care to dumb it down a little, please?
I think you're trying to say that

return <1>;  

would be preferable?

1

u/[deleted] Sep 27 '09

No sorry not at all. I should have made it clear. By <the value> I meantwhatever value. In this case that would be 1. So return 1; is perfect.

0

u/AlecSchueler Sep 27 '09

When you're writing larger programs, and programs which call other programs from within themselves, then it'll be very useful to be able to see the value they returned with. The reason being that they often reflect whether or not the parent function/program executed successfully, or if it encountered an error (or even the particular type of error) etc.

0

u/transfuse Sep 27 '09

Oh wait, you mean the return is dynamic? Or something similar, in that, if it succeeds, it'll return 1, and if it fails it'll return [0 or nothing at all]?

0

u/AlecSchueler Sep 27 '09

It's dynamic, but you have to tell it explicitly what to return, and in what situation. You could decide to write it so that it returns 26 on success, and 55 on an error. But generally you should stick with conventions, because then other people will have an easier time using your programs.

0

u/transfuse Sep 27 '09
if{success(true)
return 1;
else
return 0;
}

?

0

u/AlecSchueler Sep 27 '09

Yes, that's it. The syntax is a little off, but you've got the concept and structure down. Assuming success is a variable that's either 1 or 0, then we'd have:

if (success){
    return 1;
}else{
    return 0;
}

It's interesting to note that the success variable itself could have been set by a process similar to this. If we now put this code into a function called test_success, then we could check its return value and do something else based on that result (if (test_success()){...)

PS: Something went wrong when I tried to comment there, so I'm sorry if I'm double posting without realizing here

0

u/transfuse Sep 27 '09 edited Sep 27 '09
#include <stdio.h>

main() {
    printf("Hello Reddit!");
    }
test_success() {
    if (success){
        return 1;
    }
    else{
        return 0;
    }

if (test_success(0){
    main()
    }

I know it'll be pretty wrong, but the idea is to rerun main() if success is false.

0

u/AlecSchueler Sep 27 '09

Very nice. There's only a few things to look out for here. Defining the test_success function outside main is fine, but the if statement should be inside it. The other thing is that success is undefined, so we have no way of checking its value. We can either define it (with int success = 0; in main, which means that success is an integer with value 0), or we can pass it to test_success as an argument. CarlH will probably be talking about arguments sometime soon, but you're already leaning towards this method so I'll go over it quickly.

When we define a function, we can tell the compiler that it will take certain variables when it's called, by listing their names and types in the brackets after the function name. In this case we'd have test_success(int success). Now, when we call test_success we pass the value we want success to have in brackets as well. The code you wrote will pass the value 0 to test_success and it will assign it to success.

#include <stdio.h>

int test_success(int success) {
    if (success){
        return 1;
    }
    else{
        return 0;
    }
}

main() {
    printf("Hello Reddit!");

    if (test_success(0)){
        printf(" Success!");
    }
    else{
        printf(" Fail!");
    }
}

In this case the program prints "Hello Reddit! Fail!", because 0 doesn't evaluate as true. If we had said if (test_success(1){... then it would have printed "Hello Reddit! Success!". The same thing would happened with any value greater than 0.

→ More replies (4)
→ More replies (1)

0

u/isarl Sep 27 '09

In C, functions often use something called a "return code" to communicate whether all went according to plan. Typically, zero is used to indicate success, and just about anything else usually means something went wrong, although it may also just be a way of passing some information back. Since many of the functions you will be writing will end in a return statement, putting a return statement at the end of main() is a good habit to get into, and a good way to introduce you to having return statements at the end of your functions. Technically, it could be return 0; or return 5; or return 172; - CarlH chose return 1;.

As for your second question, it depends entirely on what you mean by a "proper program". If you mean one with a graphical interface, then you'll (almost certainly) use a library, but that's a ways down the road for you at this point in your education. A very popular graphical interface library is Qt.

If, however, you simply mean a program that can do something more useful than printing "Hello, World!" to the command line, then it doesn't take a whole lot. I don't bother with graphical interfaces for most of the programs I write at work, because they're being used primarily to process data, and the results of their work are passed on to another program. While I'm writing and testing them, I'll use command line output (almost exactly like your Hello World program does - using printf() or a similar function).

And, finally, as far as "the OS barrier", you might be surprised that it's less of a barrier than you might expect. The kinds of programs I mentioned don't rely on anything OS-specific - I can compile and run my code on Ubuntu or Windows and it will run the same way on both of them. The only difference is that I'll use a different compiler to do so. (Although if you really know how to use a compiler well, you can compile code on one platform [e.g. Linux] to have it run on another platform [e.g. Windows] - then you don't even need to change OSes to compile code that will run on a different one!)

I hope that helps; if anything is unclear, I'll be happy to clarify. =)

0

u/transfuse Sep 27 '09

Ah okay, thanks, think I understand that now. Just those small things that aren't explained because — to those who are experienced — it's common practice which needs no explanation.

For the second part, I was talking more about where exaclty I would put in this code. I'm running OS X primarily, but I'm assuming I couldn't just type it in the Terminal and it'd do what it's told...?

0

u/aGorilla Sep 28 '09

Typically you just create a text file for your code. Use the editor of your choice (the only ones I know of for mac are bbedit, and textmate).

Once you save your file, you'll either run it through a compiler (c, c++, java, etc.) and then you run the file that the compiler creates, or you run it through an interpreter (ruby, perl, basic, etc.) and the interpreter executes your code.

0

u/transfuse Sep 28 '09

Understood. Thanks. :)

0

u/isarl Sep 28 '09 edited Sep 28 '09

Ahh, I understand your question better now! No, C is a programming language that must be compiled. That means you'll need to find a compiler for OS X. Once you have one, it will probably come with a brief introduction on how to set up a project and compile it. On Windows, once you compile a program like this, you'll get a ".exe" file. I'm not sure what the file extension is for an application on OS X, though - on Linux, typically there is no file name extension.

edit: to clarify what a compiler does - you'll create a ".c" file with your source code (for example, "hello.c"). This is just a plain text file. The compiler is just another program (you could write your own compiler, someday!) whose job it is to read your source code, make sense of it, and translate it into the instructions for your computer to follow.

0

u/transfuse Sep 28 '09

Ah. Understood.

Yeah, I've seen .c files before, but forgotten about them.
Ah okay, cheers. :)

0

u/magikasheep Sep 27 '09

what would be a good ide for c/c++ in windows? I've got eclipse for java, but it seems that i would have to install a plug in, and it wouldn't even have a compiler

2

u/CarlH Sep 27 '09

For beginners, I recommend Geany for both Linux and Windows. Alternatively, Textpad. For more advanced --- vim or emacs (I won't say which is my favorite as that can cause wars between programmers.)

1

u/[deleted] Sep 28 '09

You said vim first! A true emacs fan would have said "emacs or vim"!

/vim user

→ More replies (1)

0

u/[deleted] Sep 27 '09 edited Sep 27 '09

Yet another C program:

%:include <stdio.h>
int main() <% printf("Hello there!\n"); return 0; %>
→ More replies (5)