Friday, December 2, 2016

Getting good at: C | #1 - Integers and printf()

1 - int a = 9

No, that's not a typo. C is a programming language published in 1978 by a company called 'Bell Labs'. (later AT&T)

C and C++ are very similar in syntax (They both look similar), but there are a few differences, a big one being that you can't make a class the same way you could in C++. With that out of the way, let's get right into this.

NOTE: If you have not installed Code::Blocks prior to reading this tutorial, do so now. If you're having trouble installing it, refer to this post.

So before we get started, we need to first make a C project. (Most projects are C++ by default.) 

Step 1: Click on 'Create a new project'.

Step 2: Click on 'Console Application'.

Step 3: Click 'Next >' once.

Step 4: Choose 'C' from the list.

Step 5: Continue as normal.

So after you're done, you should see something like this:

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

int main()
{
     printf("Hello World\n");
     return 0;
}

This is a program that prints 'Hello World' on the screen. This is how it works:

#include - This tells the compiler to include a header file, usually stdio.h

int main() -  This is your main function. You can put statements like 'printf()' in it. 

NOTE: Don't forget to include this function in your program, or else it won't compile.

printf("words") - This statement prints words, values, or other stuff on the screen.

return 0 - When a program runs successfully, it returns a value of '0' to the system, telling it that the program ran without errors.

NOTE: Don't forget to put semi-colons at the end of your statements. Otherwise, you'll 
T R I G G E R your compiler.

To make a variable in C, you type 'int ' (without the quotes) and then your variable name. Then set it equal to something. (The bold letters signify that it was typed recently. You don't have to copy and paste the entire function to write a new statement.) It should look like this:

#include <stdio.h>

int main()
{
     int a = 2;
     return 0;
}

After that's done, press 'enter' and type 'printf("")' (without the ' quotes). In the " quotes, type %d . Outside the " quotes but still in the parentheses, put a comma, and then your variable name, in this case it's a. It should look like this:

#include <stdio.h>

int main()
{
     int a = 2;
     printf("%d", a);
     return 0;
}

After you're done, you should see something like this:

2
Process returned 0 (0x0)
Press any key to continue.


homework

You don't have to do these, but you can if you want to. I highly recommend you do so, because they will make learning programming languages a lot easier.

Exercise 1-1: Write a program that prints 5 on the screen, but make a variable and pass it to printf() rather than doing something like 'printf("5");'.


That's all I've got for today.

No comments:

Post a Comment