• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!
  • It's time for the first HD Modeling Contest of 2024. Join the theme discussion for Hive's HD Modeling Contest #6! Click here to post your idea!

[C] Beginner Examples Tutorial

Status
Not open for further replies.
Level 6
Joined
Nov 1, 2007
Messages
42
Beginner C Examples
By GoSu.SpeeD
http://hiveworkshop.com

Disclaimer:
This tutorial was created for hiveworkshop.
If you would like to display this tutorial on your website,
i would appreciate it if you would ask my permission before doing so and
keep the credit box at the top of the post.

-GoSu.SpeeD

Contents
1. Background Information
2. Compiler
3. The Hello World Application
3.1 Indentation
3.2 Comments

4. Variables
5. User Input
7. If and Else statements
8. Arithmetic
9. Loops
10. Ending Notes
11. Updates

Background Information:


C was invented by a man named Dennis Ritchie. C is the predecessor to the language B (invented by Ken Thompson) and the language B was influenced by the language BCPL(invented by Martin Richards). C "took the crown" so to speak from Language B in the 1970s (1972 to be exact).

C was originally designed for use on UNIX operating systems, but it very quickly spread to multiple platforms. When Invented, C was mainly used for creating programs that would control hardware but not so long after, it became common to see C applications being programmed for regular computer use.

Compiler

Well before we start programming, you will need a compiler. What is a compiler you might ask.

A compiler (in the C sense) is a program that will "convert" your C source code into a lower level language, such as ASM(Assembly) or Machine Language, then produce the output as an executable.

There are alot of free compilers out there than even have IDEs (Integrated Developement Environments). An IDE is basically all the seperate programs needed for compiling bunched into one (sometimes graphical) interface.

For Windows, i find the most user-friendly and easy to navigate(also good because it's free) IDE is Dev-CPP (My personal opinion), which is originally a C++ compiler but gives the option to create C or C++ projects. The link is below.


Most (if not all) UNIX-based operating systems come with a C compiler when installed you just have to know the correct syntax for compilation and which compiler you are using (all this information should be available in the documentation).

Let's get started

now that you know a little bit about the history of C and have got a compiler (hopefully), i think we can get started on some simple applications.

The Hello World Application


Well, nearly every first tutorial for any programming language you will come across will start with this traditional example, the standard "Hello World" program.

Code:
#include <stdio.h>

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

Now, lets break the program down.

#include <stdio.h> -

With this line, we include the standard input/output C library this allows us to call functions that are within this specific library. One of these functions happens to be "printf".

int main() -

On the third line we initialize our main function with the type "int" (Integer). Your main function just acts like the main body of your program. the main starts and ends where the braces start and end {}.

printf("Hello World \n"); -

The function printf is pretty straight-forward, it will print whatever is inside the double quotes to the console, in this case it is "Hello World". note that
the whole function is in lowercase, all standard functions must be typed in lowercase else the compiler will not know which function we are referring to.

"\n" - represents the NEW LINE character which will - like its name - start the next piece of output on the next line.

you may have noticed already that semi-colon (;) at the end, all statements must end with a semi-colon, this tells the program that the statement is finished. if you forget the semi-colon the compiler will start giving you compiling errors, a common one is "Missing terminating character".

return 0; -

The main() function returns an integer to the calling process, which is the operating system (Windows, UNIX etc.) most of the time. Returning a value from the main function is basically the equivalent (most of the time) of calling the exit function with the same value. It is generally a good programming practice to always return a value at the end of your main function (unless your main function is type void, which i will explain about later) because if you don't return a value it might work on your current operating system but it is not wise to depend on it to exit correctly on other operating systems.

Congratulations you just created your first C program! Now that wasn't too hard now was it?

Indentation & Whitespace

so by reading the title of this mini section you will probably not know what indentation means, and you will probably will know what whitespace is, if you don't know the both of them, don't worry i will go over it :).

Ok, so let's go over indentation first, for those of you who don't know what indentation is i'll show you by a quick example.

Indented Source:

Code:
#include <stdio.h>

int main()
{
    printf("hey, this source is indented");
    return 0;
}

Not Indented Source:

Code:
#include <stdio.h>

int main()
{
printf("hey, this source isn't indented");
return 0;
}

Ok so, by looking at the examples it's not really hard (or shouldn't be) to recognise the differences. Indentation is the method of inserting whitespace at the start of your line. Now some people might be thinking, what is whitespace? Well to put it simple, whitespace is just WHITE SPACE or any kind of open space in your source (hard to grasp the concept isn't it? /sarcasm :D).

So now you might be thinking - "Hmmm but why do i need to space out everything?"
Well the answer is simple:

1. To make your code look neater.
2. To be able to find portions of your code faster.
3. If other people are to view and/or learn from your source, it's nice to make your code readable.

Comments

Yes, that's right. Like every other programming language C has comments, i don't think i need to explain the use for comments but just in case. Comments are used to leave notes on your source that will not be compiled by the compiler but they are kept there for people to read.

Comments are easily placed so if your source code has some very confusing functions that you created or just generally confusing code it's always nice to comment it, so if you decide to release it to the public eyes, people can easily understand what is happening at that specific part of the code, it is not necessary to comment EVERY variable declaration and EVERY single value assignment unless you are releasing the source as a part of a tutorial.

Now comments are done like the following:

Code:
#include <stdio.h>

int main()
{
    printf("I'm showing how to use comments"); /* this is the older way to comment */
    return 0; // this is the newest way to comment
}

now both ways are fine, just use them both according to your situation. The older way to comment has the ability to create multiple line comments like so

Code:
#include <stdio.h>

int main()
{
    printf("Showing a multiple Line Comment");
    return 0;
    /* 1
        2
        3 */
}

I find that i only use the older way of commenting when placing a banner at the top of my source with website information,author information etc. For usual comments actually commenting what's going on in the source i would mostly use the newer way.

Variables

Before we go any further i think i should explain what variables are and how they are used. Variables are like storage boxes, whenever they are made they are made for a specific purpose, in C variables are made with a specific DATA TYPE such as INT and CHAR. Once Created and assigned a data type, the variable will only accept values in that data type.

For example, if we create a variable with the name "tutorial" and we assign a data type of INT(Integer) we will not be able to store a value such as "a" into it. Why? because we specified when declaring the variable that we only want to store INT values such as "1","2" and "3" into the variable named "tutorial".

Just like storage boxes we can put things into variables and use them when we like. All variables must be declared before they are used.

Declare basically means create in a sense.

To declare a variable in C, we do the following:

Code:
#include <stdio.h>

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

This tells the program that we want to DECLARE an integer variable with the name of "a". Now that we've DECLARED our INT variable and gve it the name "a". Now i'll show you how to store a value in our variable "a".

Code:
#include <stdio.h>

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

So we start off as usual by declaring our variable "a" then we use the assignment operator "=" to store the value "1" in the variable "a". We can also do the declaration and assigning on the same line, like so:

Code:
#include <stdio.h>

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

This is a quicker way as you can see and is useful to save time when working with a lot of variables. We can also print variables to the console for the user to see, like so:

Code:
#include <stdio.h>

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

"%d" tells the program that we wish to print a DECIMAL value and the value is stored in the variable "a". If done correctly, when ran the program will display in the console window the number "1" which we earlier stored in the variable "a". By now you have probably noticed that when you try to run the program that it will run then close immediately, you might be thinking why this is happening or that you've done something wrong - don't worry it's simply because we didn't tell the program to pause after displaying the output in the console. To fix this problem, we do the following:

Code:
#include <stdio.h>

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

getchar() -
will create a pause because the function getchar is used to take one character of input from the user so - the program will run then wait for you to press a key then it will exit.

On a lot of Windows compilers when you start a C project by default it will give you a template ending with the function:

Code:
system("pause");

while this function was designed for the purpose of pausing it is considering bad programming to use this because:

1. you are borrowing functions from the operating system.
2. by borrowing functions from the operating system, this means that your program is no longer multi-platform (can no longer run on any other operating system).

Ok, so now that you have a basic knowledge of variables (hopefully) lets continue.

User Input

The following program will show how to implement basic input and output in your C program

Code:
#include <stdio.h>

int main()
{
    char a[10];

    printf("Hello, what is your name?\n");
    scanf("%s", a);
    printf("You entered: %s", a);

    fflush(stdin);
    getchar();
    return 0;
}

char a[10] - We declare a char (character) array (which has the ability to contain 9 characters, i know it says 10, i'll explain that part later) so the variable can hold more than one character, enabling us to store a string inside the variable instead of just one letter. C unfortunately does not have a "string" data type but char arrays fill the void pretty well :).

scanf("%s", a); - we use the function scanf to tell the program that we wish to wait for user input and we want that user input to be a string (%s = string) and that we want to store the input in the variable "a".

fflush(stdin); - will basically flush everything that got caught in the user input.

getchar(); will pause(wait for user input) the program at the end (as i explained before) so that we can see the input and output.

Ok, so i said earlier i would explain about the array that was assigned 10 spaces can only hold 9 characters. This is because we must leave 1 space for the null byte, the null byte signals the end of a string, we do not have to place the null byte into the array although this is what the null byte looks like in C:

Code:
\0

If and Else Statements

Hello again, this section will be dedicated to teaching you about using IF statements. Now some people don't know what IF statements are so i'll give a brief explanation. If statements work like this, i'll give a PseudoCode example.

PseudoCode meaning:

a way of writing program descriptions that is similar to programming languages but may include English descriptions and does not have a precise syntax.
http://www.cs.utexas.edu/users/novak/cs307vocab.html

Example If statement using PseudoCode:

Code:
if this condition is true
{
    then do this action
}

so basically, the if statement will check if the condition provided is true and if it is it will do the action provided in the braces, if it is found that the condition is not true then the program will just continue, unless you add in an else statement then it obviously execute whatever is provided inside the else function. Now i'll show you a PseudoCode example of using If and Else:

Code:
if this condition is true
{
    execute this statement
}
else
{
    execute this statement instead
}

as you can see it's not that hard to remember what goes where if you just think of it in a logical sense. Now i'll show some real examples of if and else working together.

Code:
#include <stdio.h>

int main()
{
    int age;

    printf("Hello, what age are you?\n");
    scanf("%d", &age);
    
    if (age == 17)
    {
        printf("\n17 eh? that's the same age as my creator");
    }
    else
    {
        printf("\nSo, you're really %d?", age);
    }

    fflush(stdin);
    getchar();
    return 0;
}

Now hopefully, the above code isn't too confusing for you, i'll start at the line of the "if". We start our if statement by typing "if" then we open our parenthesis and place our condition inside, which is "age == 17" which in english translates to "age is equal to 17", then we close our parenthesis. Next we open our braces on the line below then on the next line we call the printf function to display a unique message to the user if the user's input is equal to the number 17, we then close our braces and begin our else statement.

So we start our else statement with a simple "else" and nothing else, then we move to the next line and open our braces and on the next line we call printf again to display a different message to the console if the user enters a number which is not equal to 17.

You will notice that there is a ampersand(&) before the variable "age" when we call scanf before the if statement. This is needed because the variable parameter of scanf in this case "age" needs to be a pointer when dealing with decimal values, not the contents of a variable. Simply put - A pointer is a reference to a memory address, i'll speak more about pointers later.

Well there you go, you just used your first if and else statement, congrats :). Now a little ending note to this section, we do not always have to use the relational operator "is equal to" (==) there is a few others that we can use that together will help you create any condition that you would like, here is a list:

Code:
>     greater than              5 > 4 is TRUE
<     less than                 4 < 5 is TRUE
>=    greater than or equal     4 >= 4 is TRUE
<=    less than or equal        3 <= 4 is TRUE
==    equal to                  5 == 5 is TRUE
!=    not equal to              5 != 4 is TRUE

Arithmetic

Performing Arithmetic in C is actually quite easy, i will try to guide you through the basics of Arithmetic in this section. The seven operators for Arithmetic are as follows:

Code:
+ means Add
- means Subtract
/ means Divide
* means multiply
% means modulus (grants the ability to grab remainders)
-- means Decrement
++ means increment

most of you should know the concept of the first five operators, but i think only some of you will know them meaning of the last two, so i'll give an explanation. C gives us two operators: Increment(++) and Decrement(--). Now what increment will do is add 1 to it's operand and decrement will decrease it's operand by 1, not too hard to understand. Here is an example using the Increment and Decrement operators:

Code:
#include <stdio.h>

int main()
{
    int option;
    int startingnumber = 5;

    printf("Hello, your starting number is 5, Press and enter 1 to Increment or 2 to decrement\n");
    scanf("%d", &option);
    
    if (option == 1)
    {
        startingnumber++;
        printf("Increment Successful! Your new number is now %d", startingnumber);
    }
    else if (option == 2)
    {
        startingnumber--;
        printf("Decrement Successful! Your new number is now %d", startingnumber);
    }
    else
    {
        printf("Invalid option selection. Please try again");
    }
    
    fflush(stdin);
    getchar();
    return 0;
}

the code shouldn't be too hard to understand, everything i have used in the code has been explained in previous sections so if your a bit hazey about a part of the code just check the previous sections.

Ok, so you can see once we call scanf to grab the user input we use an if statement and a else if statement (we can't use two if statements in a row or else when it comes to creating the else statement the program will get confused and print what it's not supposed to) to determine what will happen depending on the option if the user entered 1, the program will increment the starting number by one, this simply done by naming the variable and placing the increment operator at the end (startingnumber++;) and end the statement with a semi-colon. The decrementing process is pretty much the same apart from the fact that the operator has changed but it still remains in the same position.

Finally we end with an else statement to give the user an error if they enter anything apart from the options granted, flush the standard input, getchar for the pause and then finally return a value of 0.

Now, let's try using some of the other operators, i'll show you how to use them seperately then i'll show you how to make a basic calculator:

Addition:

Code:
#include <stdio.h>

int main()
{
    int num1 = 2;
    int num2 = 2;
    
    printf("num1 + num2 = %d", num1 + num2);
    getchar();
    return 0;
}

Subtraction:

Code:
#include <stdio.h>

int main()
{
    int num1 = 2;
    int num2 = 2;
    
    printf("num1 - num2 = %d", num1 - num2);
    getchar();
    return 0;
}

Division:

Code:
#include <stdio.h>

int main()
{
    int num1 = 2;
    int num2 = 2;
    
    printf("num1 / num2 = %d", num1 / num2);
    getchar();
    return 0;
}

Multiplication:

Code:
#include <stdio.h>

int main()
{
    int num1 = 2;
    int num2 = 2;
    
    printf("num1 * num2 = %d", num1 * num2);
    getchar();
    return 0;
}

Modulus:

Code:
#include <stdio.h>

int main()
{
    int num1 = 3;
    int num2 = 2;
    
    printf("The remainder of num1 / num2 = %d", num1 % num2); // will print 1, because it's the remainder of 3 divided by 2
    getchar();
    return 0;
}

as you can see, it's nothing complicated, but i find it's always good to practice everything a little bit at a time so you will absorb it more and hopefully remember it for a long time, now we piece everything together that i've taught in this section and make a simple calculator:

Code:
#include <stdio.h>

int main()
{
    int n1, n2, loop; 
    char op;                                                                
    loop = 0;
                  
    while(loop != 1) 
    {
        printf("\nPlease enter your first number"); 
        printf("\n\n> ");
        scanf("%d", &n1);
        
        printf("Please enter your second number");
        printf("\n\n> ");
        scanf("%d", &n2);
                  
        printf("Which operator would you like to use? (+ - / *)");
        printf("\n\n> ");
        scanf("%s", &op);

        if (op == '+') 
        {
            printf("The result of: %d + %d is %d\n", n1, n2, n1 + n2);
        }
        if (op == '-')
        {
            printf("The result of: %d - %d is %d\n", n1, n2, n1 - n2);
        }
        if (op == '/')
        {
            printf("The result of: %d / %d is %d\n", n1, n2, n1 / n2);
        }
        if (op == '*')
        {
            printf("The result of: %d * %d is %d\n", n1, n2, n1 * n2);
        }
        printf("-----------------------------\n");
    }   
    fflush(stdin);
    getchar(); 
    return 0;
}

Now remember earlier i said about you can't use two or more if statements in a row? don't forget that it's alright to do it if you aren't planning on using an else statement.

i'd advise you to read over the code a couple of times and maybe type it out at least twice just to soak it into your head, since i gave a pretty good explanation about operators and how to use them so far in this section, i don't think i need to explain what is happening above, there is only one part of the source that we have not went over here but i'll explain it now:

Code:
while(loop != 1)
{

}

this, in C is what we call a loop. Loops like their name indicates will loop whatever is inside the braces if the condition gave in the parenthesis is true, since this section is not covering loops i will only give a brief explanation and i will save the rest for the next section.

this loop is pretty simple and can be interpreted to english quite easily, C to English translation =

Code:
while(loop is not equal to 1)
{
   do this
}

well, that's all for this section, i hope i explained it well, if you didn't quite get a certain part of this section or any section of this tutorial, don't hesitate to PM and i'll be glad to help as best i can.


Loops

In this section we will discuss different types of loops and how to use them correctly. So first of all, i assume the majority of you already know what a loop is, for those who don't, a loop simply executes whatever is inside the loop continuously until the condition specified is true, you can create an infinite loop, we will talk more about this later. I'm guessing that most people realize the advantages of using loops, the main reason in my opinion is for speed: e.g.

Let's say we have programmed a password protection program, and all the program does is prompt the user for a user name and password, once the correct account details are received the password protection program transfers control to the main program. For this program, we don't want the program to exit immediately after a user has a failed attempt (unless you were implementing a sort of lock out feature after X amount of failed attempts) so what is the quickest solution? A loop of course.

Including a loop in our program will allow to user to attempt to login many times without having to re-execute the program every time, here's some example source:

Code:
#include <stdio.h>

int main()
{
    int input;
    int code = 1094;
    
    while (input != 1094)
    {
        printf("Enter PIN Code: ");  
        scanf("%d", &input);  
        
        if (input != code)
        {
            printf("\nUnrecognised PIN Code\n\n");
        }
    }
    printf("\nPIN Code Accepted");
    
    fflush(stdin);
    getchar();	
    return 0;
}

Ok, so i shouldn't have to explain anything apart from the loop because i've covered everything else in previous sections. The loop i used in this program is a simple while loop, it can be translated to english very easily:

Code:
while(user input is not equal to the correct PIN code)
{// Loop Starts
    // CODE HERE
}// Loop Ends

It's pretty similar to the if statement, While is called, the parenthesis contain the condition, braces contain the code to be looped. an Infinite loop can be achieved very easily as well:

Code:
while(1)
{
  
}

Some of you might be wondering why this induces an infinite loop, well remember earlier when i said a loop will continue until the condition specified is true? Well when we make the condition to only contain 1, the program can see that 1 is a nonzero value so that itself makes the result ALWAYS true (0 = false , 1 = true) but when using this type of infinite loop it is advised to add a sleep function just after the opening brace because this type of infinite loop hogs ALL computer usage, to do so:

Code:
while(1)
{
    sleep(10);
}

the sleep command does exactly what it's named, it makes the program sleep for the time specified in the parameter which in this case is "10", sleep on windows ratio: 1000 = 1 second, so the above example makes the program sleep for 10 milliseconds at the start of the loop every time. We do this because it stops the cpu usage from being eaten up and also won't interfere with the program. To use the sleep function we must include the windows header file so:

Code:
#include <windows.h>

The next and quite uncommon loop is the "Do While" loop, which works like this:

Code:
#include <stdio.h>

int main()
{
    int input;
    int code = 1094;
    
    do
    {
        printf("Enter PIN Code: ");  
        scanf("%d", &input);  
        
        if (input != code)
        {
            printf("\nUnrecognised PIN Code\n\n");
        }
    }while(input != 1094);

    printf("\nPIN Code Accepted");
    
    fflush(stdin);
    getchar();	
    return 0;
}

pretty similar to the regular while loop, DO whatever is inside the braces, while condition is true. I think the only part i need to explain about this loop is the semi-colon after the last round bracket which contains the condition. The semi-colon is basically need to tell the program whether the "While" that was performed is the beginning of a normal while loop or the end of a "Do While" loop.

Note: Remember when using the do while loop that, the body will always be executed at least once, because the DO comes before the while.


The last loop to discuss is the "For" loop. The for loop is a little more complicated than the while loops i've shown. If you think about it logically it's easier to make sense of it, in real life i doubt any of you would say this but let's just go along with it:

For A equals 0; A is less than or equal to 1000; Increment A
{Do this until condition is met}

That's the best way i can explain it, the For loop has 4 different parts:

Code:
For (Initialization; Conditions; Increment/Decrement Value)
{
    //CODE
}

So if i include the code portion it has 4 parts, Incrementing and Decrementing is simply increasing/decreasing the current value by 1, and can be as simple as adding ++(incrementing) or --(decrementing) to the end of the variable name. in my opinion For loops are hard to explain, the best way to learn how to use For loops is to view examples:

Prints from 0-1000 in console:

Code:
#include <stdio.h>

int main()
{
    int start;
    
    for (start = 0; start <= 1000; start++)
    {
        printf("%d\n", start);
    }
    getchar();	
    return 0;
}

Starts at 500 then counts down to 0:

Code:
#include <stdio.h>

int main()
{
    int start;
    
    for (start = 500; start >= 0; start--)
    {
        printf("%d\n", start);
    }
    getchar();	
    return 0;
}

Just like the while loop had it's simple fix for an infinite loop, the For loop has something similar:

Code:
For(;;)
{
    sleep(10);
}

just simply edit your For loop to have no initializer, condition or increment/decrement value, also do not forget to add the sleep command to stop cpu usage getting too high. Finally, to break out of a loop, we do the following:

Code:
while(1)
{
    if (condition is true)
    {
        break;
    }
}

That's it for the loops section, as usual, i'll add more as i get time. If you have any ideas on what topic i should write the next section on, PM me.

Strings & Arrays

I have showed examples of using char arrays in previous chapters, but i didn't really give an explanation so i thought i'd do a sort of mini section for arrays. Unfortunately, in C there is no STRING datatype like there is in many programming languages nowadays, but we have a simple solution to that problem, CHAR Arrays! You might be thinking, what is an array? well to put it as simple as possible, an array is a group of elements stored in a variable. Still don't get it? ok well i'll show some examples of arrays being used vs normal variables:

Normal Variables:

Code:
#include <stdio.h>

int main()
{
    char output1 = 'H';
    char output2 = 'e';
    char output3 = 'l';
    char output4 = 'l';
    char output5 = 'o';

    printf("%c%c%c%c%c", output1, output2, output3, output4, output5);
    
    getchar();
    return 0;
}

Array:

Code:
#include <stdio.h>

int main()
{
    char output[6] = "Hello";
    
    printf("%s", output);
    
    getchar();
    return 0;
}

as you can see the first example takes much longer and takes up much more space than the second example. New programmers to C or new to programming in general often forget that the index of the first element in C is '0'. What this means is that just say we declare an CHAR array and store 3 values inside like so:

Code:
#include <stdio.h>

int main()
{
    char test[3] = {'a', 'b', 'c'};
}

alright, so now, what do we do if we wish to print "a" which is inside the variable test?

Code:
#include <stdio.h>

int main()
{
    char test[3] = {'a', 'b', 'c'};

    printf("%c", test[0]);
}

Now you will probably know what i meant by saying the first element of the array index is 0, it means that the first value gets stored in '0' element, then '1' and so on. I heard that C is what made the number '0' as the first element so popular, practically every programming language developed after C used this method, although, VB6 grants you the option of creating a "start from 1 index".

Now, arrays are good for many more things than just creating strings from a CHAR, such as creating INT arrays. You might think "Why would i need an int array?". Well let's say you needed to store a load of different integer values somewhere, well an INT array would be the most efficient solution, like so:

Code:
#include <stdio.h>

int main()
{
    int store[4];
    
    printf("Enter the numbers\n\n");
    
    printf("> ");
    scanf("%d", &store[0]);
    printf("\n> ");
    scanf("%d", &store[1]);
    printf("\n> ");
    scanf("%d", &store[2]);
    printf("\n> ");
    scanf("%d", &store[3]);
    
    fflush(stdin);
    getchar();
    return 0;
}

we can also combine a do while loop and a char array to create a simple program which will check for lets say a space:

Code:
#include <stdio.h>

int main()
{
    char input[10];
    int a;
    int i;
    int SPACECOUNT = 0;

    printf("Enter input, finish with a 9 e.g. \"asdf a 9\"\n\n");
    printf("> ");

    do 
    {
        a = getchar();
              
        if (a == ' ')
        {
            SPACECOUNT++;
        }
    }while (a != '9');
    
    printf("\nYou entered %d Space(s)", SPACECOUNT);
    
    fflush(stdin);
    getchar();
    return 0;
}

Now, the only thing i should have to explain is assigning getchar to the variable "a". This is possible because the characters read by the function getchar are returned as int values, so that's why we can pass getchar to the INT variable a. Another reason for passing the return value to an integer value is incase getchar returns EOF. EOF means End Of File and signals to the program when there is no more input, i don't think any char variable can hold the EOF value, so we use INT.

Code:
    do 
    {
        a = getchar();
              
        if (a == ' ')
        {
            SPACECOUNT++;
        }
    }while (a != '9');

Ok, so what is happening here is our loop starts, and getchar is called then our if statement executes and checks wether or not the character that was caught in the input was the same as a space, if it was then increment the variable "SPACECOUNT" then continue to the while part which contains our condition, if '9' is caught in the input then break from the loop and continue to the end of the program which tells the user how many spaces he/she entered by printing from the spacecount variable.

That's all about arrays for now, i will discuss more about arrays and multi-dimensional arrays in a later chapter.

Ending Notes:

That's all for now, I will keep adding more to this tutorial as i get time. If you find any mistakes in this tutorial please feel free to inform me as i just finished typing this all in one go and i'm tired.

Thanks to Samuraid for error checking

All comments & criticisms are welcome.
i am also open to suggestions for improvements, thanks.

Updates:

6/11/07 - Fixed a few syntax errors, Typos, Added returns and explanation about returns.
8/11/07 - Added Section "If and Else statements"
--------- Added Sub-sections "Indentation & Whitespace" and "Comments"
11/11/07 - Added Section "Arithmetic".
10/02/08 - Added Section "Loops".
12/02/08 - Added Section "Strings & Arrays".
 
Last edited:
Level 15
Joined
Nov 1, 2004
Messages
1,058
Just a few small things...

char a[10] in the last example should be char a[10];

int main() {} needs a return value, otherwise it would have to be void.

Code:
char a[10];
scanf("%s", &a);
I think it's actually supposed to be scanf("%s", a); because "a" is an array of chars which is inherently a memory address and doesn't need an & applied to it. ("a" already points to the 0th element of the char array) Also, these lines of code introduce an overflow vulnerability.

system("pause");
I'm not sure about windows, but you will need to include stdlib.h under linux to get system().

Looks like a good start for aspiring C programmers to learn. Keep up the work on it. :thumbs_up:
 
Level 6
Joined
Nov 1, 2007
Messages
42
thanks for your comment.

char a[10] in the last example should be char a[10];

must've forgot the semi-colon, fixed, thanks.

int main() {} needs a return value, otherwise it would have to be void.

yeah, i was writing most of my programs with the void type for main so i developed a habit of not returning a value, fixed.

Code:
char a[10];
scanf("%s", &a);
I think it's actually supposed to be scanf("%s", a); because "a" is an array of chars which is inherently a memory address and doesn't need an & applied to it. ("a" already points to the 0th element of the char array)

yes, you're right, well it was 6am when i got to this example and i was feeling quite tired, i fixed it, i forgot that most of the time you only have to use a pointer to the variable if it's a decimal-based data type.

Also, these lines of code introduce an overflow vulnerability.

yes, when i get more time i'll add to the code and write an explanation on how to fix this.

system("pause");
I'm not sure about windows, but you will need to include stdlib.h under linux to get system().

i don't know for sure because i don't use linux much, last time i used linux was about a year ago on PHLAK, but i don't think linux comes with stdlib.h with a fresh install but i'm not sure so correct me if i'm wrong. Although i still prefer to use getchar or getch because nearly every programmer i know frowns upon borrowing system functions unless there is no other library alternative.

Looks like a good start for aspiring C programmers to learn. Keep up the work on it. :thumbs_up:

thanks again.
 
Level 6
Joined
Nov 1, 2007
Messages
42
dude, why are you teaching a dead language? at least use C++ with it's improvements (STL Library!)

...you may think it's dead but it's clearly not considering C still has thousands of programmers, C and ASM are used to create most operating systems, the OS you're on now was probably coded primarily in C and the boot-loader in ASM, C has much more flexibility than C++ and is much easier to make portable.

Also, if you start with C and master it, mastering both C++ and C# can be done in a month or two. I have a friend who's been programming in C for 8 years and in his fourth year he decided to learn C++ and mastered it in around a month and C# in about 3 weeks. C is not a dead language, it's just not as common as it used to be, there's a difference.
 
Level 15
Joined
Nov 1, 2004
Messages
1,058
dude, why are you teaching a dead language? at least use C++ with it's improvements (STL Library!)

If C were dead, we'd be all in a tough place.

C is still the language of choice for most hardware and computer developers as it is just high enough off assembly to be easily written but low-level enough for developers to do what they want in most cases. (my university degree is in Computer Engineering, and I can wholeheartedly vouch for this fact)

Also, C++ contains a lot of extra baggage that some developers don't need at all.

Additionally, C is the basis for a number of large software projects (ex: the Linux kernel), and it was chosen as such for a number of reasons, compiling speed being one of them. Such reasons may not be as relevant today with current hardware (or they may still be!).

Finally, (and this is the most important point), C++ is an extension of the C language and everything in C is contained within C++. So it seems silly to say "learn C++ instead". Technically, if you learn C, you have already learned part of C++ and vice versa.
 
Level 15
Joined
Nov 1, 2004
Messages
1,058
as far as I know, Windows from XP is written in C++
It is, and some parts are written on higher-level languages. However, the language Windows XP is written in doesn't really matter for this discussion.

if you learn C, you have problems in C++, because you are used to clumsy contraptions such as "char*" instead of "std::string"
On the contrary, if someone has problems moving from a char array to an STL string, then they should reconsider whether they should be programming or not. :wink: An STL string is just a char array wrapped in a class.

For anyone serious about programming, it's good to know the underlying data structures for the language anyway. If you write a program with any sort of complexity in C++, you will have to know the underlying details whether you use the STL or not.
 
Level 15
Joined
Nov 1, 2004
Messages
1,058
C++ is already high level, I don't think there is higher level
C++ is very low level compared to many aspects of other languages. You can still get directly at the memory and other such things. (in other words, you can use a lot of the low level functionality; you are not limited to high-level objects)

stl string has nothing to do with char*... almost nothing
:eekani: So, the fact that the STL string has a c_str() method means nothing then? :eekani:

but w/e, I've interrupted this thread too much, I won't be continuing this discussion here
As you wish.
 
Level 6
Joined
Nov 1, 2007
Messages
42
Updated the tutorial, added 2 sub-sections and a section - check updates for more information.

As usual, if you find any mistakes feel free to tell me and i will fix them as quick as possible.
 
Level 20
Joined
Apr 22, 2007
Messages
1,960
Ahh this is nice. I think I'll start learning C soon :D

Yay, my first little script thingy:
#include <stdio.h>

int main()
{
int a;
int b;
int c;
int start;
printf("Welcome to the multiplication program!\n");
printf("*****************************\n");
printf("Enter factor one now:\n");
scanf("%d",&a);
printf("Enter factor two now:\n");
scanf("%d",&b);
c=a*b;
printf("Result: %d\n",c);
printf("Restart? (0/1)");
scanf("%d",&start);
if (start==0)
{
fflush(stdin);
getchar();
return 0;
}
else
{
main();
}
fflush(stdin);
getchar();
return 0;
}

I probably got loads of stuff wrong, but it works, so lol@dat.
 
Last edited:
Level 6
Joined
Nov 1, 2007
Messages
42
Can you find me a good organized list with all functions and statements, like the one of java? The documentation is the main reason why I prefer java over C/C++.

And I do not see much difference between C and C++.

C++ Functions

Useful C function but not all

Ahh this is nice. I think I'll start learning C soon :D

Yay, my first little script thingy:


I probably got loads of stuff wrong, but it works, so lol@dat.

thanks, and there's only one small problem with your code, inside the if statement you called:

Code:
fflush(stdin);
getchar();
return 0;

and you also called it at the end of your program, all you need to do is one or the other, you don't need it in both places, of course you need your return but since the call at the very bottom will only happen when the user decides to quit, there's no need to pause. Also, you probably indented yours before you posted it but but you put the code in quote tags it remove indentation, so next time you post code, use the code tags, here is the corrected version, indented and also spaced out.

Code:
#include <stdio.h>

int main()
{
    int a;
    int b;
    int c;
    int start;
    
    printf("Welcome to the multiplication program!\n");
    printf("*****************************\n");
    printf("Enter factor one now:\n");
    
    scanf("%d",&a);
    printf("Enter factor two now:\n");
    scanf("%d",&b);
    c = a * b;
    
    printf("Result: %d\n",c);
    printf("Restart? (0/1)");
    scanf("%d",&start);
    
    if (start==0)
    {
        fflush(stdin);
        getchar();
        return 0;
    }
    else
    {
        main();
    }
    
    return 0;
}

but that's only a minor problem, which won't do your program any harm, it will just save you some space :thumbs_up: good job
 
Level 20
Joined
Apr 22, 2007
Messages
1,960
Yay!

How can I compile this into a ".exe"?
NVM I just saw that it creates a .exe of the script right after I compile.

EDIT: I also got that I can directly do the multiplication in the printing function:
Code:
printf("Result: %d\n",a*b);
So I wouldn't need the "c" int. yay
 
Level 6
Joined
Nov 1, 2007
Messages
42
Sorry for the lack of updates guys, i was busy with life, then christmas came, i'm one of those people that has too many things to do over christmas hehe. Added the loops section today, i'll try to add a bit more soon.
 
Level 15
Joined
Nov 1, 2004
Messages
1,058
Just some notes:

The "Prints from 1-1000 in console:" loop actually would print 0-1000.

Also, the ( and ) characters are generally referred to as parentheses.

It may also be worth mentioning that the body of a Do-While loop always executes at least once, regardless of the guard.

Keep up the good work. :smile:
 
Level 6
Joined
Nov 1, 2007
Messages
42
Thanks for the effort you put in this. Good tutorial. Keep up the good work

Thanks and no problem :thumbs_up:

The "Prints from 1-1000 in console:" loop actually would print 0-1000.

Thanks, i didn't notice that typo Corrected

Also, the ( and ) characters are generally referred to as parentheses.

I can't seem to find the the part where i call ( and ) braces, so if you could quote it, it would be much appreciated :grin:

It may also be worth mentioning that the body of a Do-While loop always executes at least once, regardless of the guard.

Thanks, i forgot to mention that, i haven't actually used a do while since i started learning C (no joke) :eek: Corrected
 
Level 15
Joined
Nov 1, 2004
Messages
1,058
I can't seem to find the the part where i call ( and ) braces, so if you could quote it, it would be much appreciated :grin:

Here's the spot it showed up:

It's pretty similar to the if statement, While is called, the round brackets contain the condition, braces contain the code to be looped. an Infinite loop can be achieved very easily as well:
 
Level 15
Joined
Nov 1, 2004
Messages
1,058
For clarification, VB6 does allow you to create arrays with a 0 starting index; however, you can specify a 1-based starting index as well if you want:
Code:
Dim intArray1(0 To 49) As Integer
Dim intArray2(1 To 50) As Integer

' And the shorthand notation creates a zero-index-based array:
Dim intArray3(50) As Integer
 
Level 6
Joined
Nov 1, 2007
Messages
42
For clarification, VB6 does allow you to create arrays with a 0 starting index; however, you can specify a 1-based starting index as well if you want:
Code:
Dim intArray1(0 To 49) As Integer
Dim intArray2(1 To 50) As Integer

' And the shorthand notation creates a zero-index-based array:
Dim intArray3(50) As Integer

thanks for clearing that up, i haven't dabbled in VB at all, so i didn't know for sure :smile:
 
Status
Not open for further replies.
Top