DEVTOME.COM HOSTING COSTS HAVE BEGUN TO EXCEED 115$ MONTHLY. THE ADMINISTRATION IS NO LONGER ABLE TO HANDLE THE COST WITHOUT ASSISTANCE DUE TO THE RISING COST. THIS HAS BEEN OCCURRING FOR ALMOST A YEAR, BUT WE HAVE BEEN HANDLING IT FROM OUR OWN POCKETS. HOWEVER, WITH LITERALLY NO DONATIONS FOR THE PAST 2+ YEARS IT HAS DEPLETED THE BUDGET IN SHORT ORDER WITH THE INCREASE IN ACTIVITY ON THE SITE IN THE PAST 6 MONTHS. OUR CPU USAGE HAS BECOME TOO HIGH TO REMAIN ON A REASONABLE COSTING PLAN THAT WE COULD MAINTAIN. IF YOU WOULD LIKE TO SUPPORT THE DEVTOME PROJECT AND KEEP THE SITE UP/ALIVE PLEASE DONATE (EVEN IF ITS A SATOSHI) TO OUR DEVCOIN 1M4PCuMXvpWX6LHPkBEf3LJ2z1boZv4EQa OR OUR BTC WALLET 16eqEcqfw4zHUh2znvMcmRzGVwCn7CJLxR TO ALLOW US TO AFFORD THE HOSTING.

THE DEVCOIN AND DEVTOME PROJECTS ARE BOTH VERY IMPORTANT TO THE COMMUNITY. PLEASE CONTRIBUTE TO ITS FURTHER SUCCESS FOR ANOTHER 5 OR MORE YEARS!

C Programming Tutorials

Introduction

Hello, my name is TheDischarger, yes an alias, but we’ll use that anyway. Now, i’m going to assume that you are new to this whole programming and coding biz (which are both the same) so don’t expect anything very useful if you have previous experience with coding beforehand. So with that introduction, lets get started.

Installing your software

C is a programming language that you are most likely using right now. Almost every single application, device, operating system uses something like C (Whether it is Objective-C, C++, C# or plain old C). Learning C is the essentials of all programming languages (Like learning how to multiply before you divide!). C is quite popular as you can see, so there are many environments you can download and work in (Your coding setup). The one I use and recommend highly is DevC++ by Bloodshed. There isn’t much to setup, it’s pretty much a download, install and run application. I do have to tell you though, in order to make a C source file (The file you’re going to code in), you would have to goto ‘File>New>Source File. Then click on File>Save As..>Select ‘C source files (*.c)’>Then save with any name. As you can see, you can also use this program for C++ (Hence the name), but C and C++ isn’t exactly the same, so nevermind that part (If we were to use C, you wouldn’t have to save as a C file). You should be in your text environment now, ready to code. We’ll see you in the next section.

Hello World!

All programmers first tries to output the text “Hello World!” to the compilers console. “Hello World” is the most basic of all code, telling the basic syntax of a language. We are exactly going to do just that, let's get started:

#include <stdio.h>

int main (void) {
    printf("Hello World!");
}

As usual, let’s do a basic rundown as usual:

  • The ‘#include <stdio.h>’ tells C to import libraries from the compiler. You would do ‘#include <(Name of a libary)>’ usually. Without this, there would be errors present in the code, as C has nowhere to get these, or even recognize it.
  • ‘int main (void) { }’ This initializes a method, or a block of code to put our actual coding in. You can choose any name instead of ‘main’, but if you have multiple methods of code, you would have to put the name of ‘main’ for your first method you want to run.
  • ‘printf(“Hello World!”);’ This should output “Hello World!” for you. ‘printf’ tells C to output what's in the arguments (parenthesis).
  • It’s very important to have a semicolon ( ; ) which tells C to end the line of code (Note that you can’t add these towards the end of a bracket, like the ending of the method).

Ok, so we’ve typed in out code, how do we compile and run it? If you look at the toolbars on the top of your environment, you should see the windows logo colors in the form of four squares. There are two, the one with the brown border on the top would compile our code (put it into a .exe file) and run the code in a command prompt. Ok, so i’ve just ran the code, a window popped up, and disappeared, what do I do? We would have to do this first:

#include <stdio.h>

int main (void) {
    printf("Hello World!");
    
    getch();
}

We placed the line ‘getch();’ which tells C to stop the command prompt from closing itself. Now you should be able to get “Hello World!”, see? This concludes our tutorial on printing basic text. I will see you later in our Math tutorial, ciao!

But can you do math?

Like all programming languages and computers themselves, they all do compute numbers. We’re going to learn the simplest of all math that will sure be useful: Addition:

#include <stdio.h>
int main(void) {
    int result = 2 + 2;
    printf("%d\n", result);
    getch();
    return 0;
}

Now, let’s talk about this code:

  • We made a integer data type variable (One that uses whole numbers, so no decimals) and named it ‘result’. We then made it equal to 2 + 2 (which is 4 obviously).
  • We made our ‘result’ variable print into the console by adding in “%d” in the arguments (parenthesis), added a comma ( , ), then placed the name of the variable. Then, the ‘\n’ (make sure its the slash above your enter key) simply means a new line (If you would try to make two separate ‘printf’ lines, the next printf would group its output within the previous printf). Of course, addition is not the only operator we can do. Math is fully expendable in all languages, so here are the other basics:

Subtraction:

#include <stdio.h>
int main(void) {
    int result = 2 - 2;
    printf("%d\n", result);
    getch();
    return 0;
}

Multiplication:

#include <stdio.h>
int main(void) {
    int result = 2 * 2;
    printf("%d\n", result);
    getch();
    return 0;
}

Division:

#include <stdio.h>
int main(void) {
    int result = 2 / 2;
    printf("%d\n", result);
    getch();
    return 0;
}

Modulo (It divides and returns the remainder):

#include <stdio.h>
int main(void) {
    int result = 2 % 2;
    printf("%d\n", result);
    getch();
    return 0;
}

Hopefully you got the basic math in your head. With this newborn knowledge, you can start calculating in C! Until then, I’ll see you in the next section.

Variables

There are many variable types to use. Why use a variable type we might ask? C is a fairly low level programming language (next to Assembly and BASIC). Essentially for most languages, we need to tell a new variable what’s going to be in it, before actually putting anything in it. There are multiple variable data types in all languages, C is not an exception:

  • An ‘int’ is an 32-bit integer number that can store whole numbers up to a value of 2,147,483,647 , It can also go low as -2,147,483,648.
  • An ‘string’ is an text value that can hold words, letters or simply text (and any kind of digit of course). Usually you do not need to put massive amounts of text in such value.
  • A Boolean is a true or false datatype that can hold two different values, true or false. Booleans are usually used in to determine of a variable is ‘Yes’ or ‘No’. Mainly used in If and Else statements.
  • An Float is a 32-bit variable that can also hold decimals.
  • A Double is a 64-bit variable that can hold decimals, but much more than a standard ‘Float’
  • A Char is simple one letter word, useful for grading applications.

In order to declare a data type to a variable (which is required in most low/medium-level programming languages), you will need to place either the following behind your name of your variable:

  • int
  • string
  • bool
  • float
  • double
  • char

But what if you don’t want to modify a variable after declaring it? You can use a constant variable then, just simply add ‘const’ right before the variable type:

#include <stdio.h>

int main (void) {
const int constant = 42;
    printf("%d", constant);
getch();
}

Alright, that’s cool, but what if we want to use variables in all of our methods? All we have to do is simply create a variable outside of our method: But what if you don’t want to modify a variable after declaring it? You can use a constant variable then, just simply add ‘const’ right before the variable type:

#include <stdio.h>

int global = 42;

int main (void) {
printf("%d", global);
getch();
}
<pre>
== Our first program ==
Alright, now that we know the extreme basics of C, we can get to programming out first program! What we have here is a simple simple interest calculator, allowing our user to input his/her own values rather than a static number set by the programmer:
<pre>
#include <stdio.h>
int main(void) {
    double principal, rate, time, afterrate, result;
    printf("Type in the amount of money you want to start off with: ");
    scanf("%lf",&principal);
    printf("Type in the rate in percentage (Without the Percent sign): ");
    scanf("%lf",&rate);
    rate = rate * 0.01;
    printf("Type in the time in months: ");
    scanf("%lf",&time);
    time = time/12;
    
    printf("Money: %lf\nRate: %lf\nTime: %lf Year(s)", principal, rate, time);
    afterrate = principle * rate;
    result = afterrate + principle;
    
    printf("\n\nResult: %f", result);
getch();
return 0;
}

As always, I will explain what a function does:

  • ‘double principal, rate, time, afterrate, result;’ Tells C to initialize multiple variables with the double variable type. Since we are dealing with money here, why not?
  • ‘scanf(”%lf”,&principal);’ now this is new, ‘scanf’ is a function that allows the user to input their own variable into the command prompt. Notice that we use ‘%lf’ instead of the good ole ‘%d’, this is because that since we are dealing with doubles here, would we use ‘%d’, it will not work properly. Finally, adding a ‘&’ is required before the name of the variable you want to assign user input to.
  • ‘rate = rate * 0.01;’ Simple of all math operators, this is simply taking ‘rate’ which is the percentage given by the user (input), and multiply it by a hundredth decimal (which is how you convert whole numbers into percent). We finally assign the result to ‘rate’ making it the percent to whatever the user typed in.
  • ‘printf(“Money: %lf\nRate: %lf\nTime: %lf Year(s)”, principal, rate, time);’ note that ‘%lf’ gets assigned to the variable in order

And after that, you should be getting the right output. That wasn’t so bad, wasn’t it? Next thing you know, you’ll be doing these quickly and smoothly. Until then, i’ll see you in the next section for if and else statements, cya!

If and else?

We talked about booleans before in the variables section, right? If you recall, a boolean has only two values: true and false. With these set in mind, an If and Else statement will run a line of code determining on the condition, if its true, the code in the brackets of ‘If’ will run, if it’s false, the code will run the ‘Else’ statement, or maybe not even run anything depending if the programmer adds it or not. Multiple if and else statements can be issued too, here’s an example of an If and Else statement:

#include <stdio.h>
int main(void) {
    int decide = 1;
       if (decide==1){
           printf("Yes");
        }
        else{
           printf("No");
        }
getch();
return 0;
}

You would probably already guess, but this will return ‘Yes’, here’s an explanation:

  • We created a integer called ‘decide’ and gave it a value of ‘1’.
  • We created an if and else statements, with a condition (in the parentheses). If the condition is true, it will run the code inside the ‘If’ block (which is enclosed in brackets). If the condition is false however, it will run the code inside the ‘else’ block (again, enclosed in brackets). You only need brackets though if you have multiple lines of code, so this would also work if you only needed to run one line of code, so something like this would work also:
#include <stdio.h>
int main(void) {
    int decide = 1;
       if (decide==1)
           printf("Yes");
        else
           printf("No");
getch();
return 0;
}

If and Else statements are used to decide on which code to run depending on the conditions. There are many comparing operators that can be used, here’s a list of them:

  • == equal to
  • != not equal to
  • > greater than
  • >= greater than or equal to
  • < less than
  • ⇐ less than or equal to

Now let’s say that I want to compare ages, this simple if, else statement would work just fine:

#include <stdio.h>
int main(void) {
    int age = 19;
        if (age>=18)
            printf("You may Enter this site!");
        else
            printf("You are too young. Access Denied!");
getch();
return 0;
}

You would probably guessed, the output is “You are too young. Access Denied!”. We use a >= operator to say that if our age (16) greater than or equal to 18, we would output our ‘true’ statement (in the ‘if’ code block). However, our ‘false’ statement was returned (in the ‘Else’ code block) since our age does not meet the conditions. However, what if we want multiple else statements? For example, what if we were making a program to make multiple decisions instead of just 2 (Or one if you leave out the ‘else’ statement, so you can run a code in the ‘if’ statement code block if it matches the condition, or continue running the rest of the code and skip the ‘if’ code if it’s false). This is exactly how e would have do it:

#include <stdio.h>
int main(void) {
    int age = 17;
    if (age>=18)
                printf("You may Enter this site!");
        else if (age>=16)
                printf("You're almost there...");
        else
                printf("You are too young. Access Denied!");
getch();
return 0;
}

You should get a output of “You’re almost there…”. What we did we placed in a ‘else if’ statement along with a condition right in the middle of the function. Now, you can place these as much as you want (Hopefully with non-colliding conditions), so you can have a ton of decisions (Although, before you do anything crazy, you might want to wait up a bit on another function that handles this specific task). If and Else statements are one of the most useful functions in programming, and they’re practically used in almost every single application you can think of. With that said, we’ll go into more functions. See you in the next section!

The Switch Statement

Lets say that you want to have a program that based on a number of a given variable (Like a product number), it returns a output. In this program, let us pretend that a customer is buying some potatoes , I want to create a statement that will go through a list, and try equal a serial number on those potatoes, and match it up with one of our conditions, it will then return “Potato selected!”:

#include <stdio.h>
int main(void) {
int serialnumber = 103;
        switch (serialnumber) {
            case 100:
                    printf("Cucumbers selected!");
                break;
            case 101:
                    printf("Avocado selected!");
            break;
            case 102:
                    printf("Pineapple selected!");
            break;
            case 103:
                    printf("Potato selected!");
            break;
            case 104:
                    printf("Strawberries selected!");
            break;
            case 105:
                    printf("Watermelon selected!");
            break;
            case 106:
                    printf("Tomatoes selected!");
            break;
            default:
                    printf("Invalid Serial!");
        }
getch();
return 0;
}

Ok, by looking at the list, you’re probably guessing that I just made a list of standard grocery supplies. Like any other tutorial I did, I’ll start by explaining:

  • We assigned an integer variable ‘serialnumber’ the number ‘103’.
  • We created a switch statement that’ll take the value of ‘serialnumber’ and try to find a match within one of the ‘case’. If a match is found, it’ll run that code in that case code block. If a case doesn’t match up, it’ll run the ‘default’ case, which will return “Invalid Serial!” in this case (No pun intended).

As I said, it will output the text “Potato selected!”, well how about that?

Functions

What if I told you can initialize variables inside of a single variable with parenthesis, and then later you can assign a variable to that variable without using precious resources and space? This is where Functions come in, then of it like a handy helper when it comes to massive amounts of variables. While Functions are a little confusing to use, they will surely help a lot in the long run:





For Loops

Lets say that we want a piece of code to run as many times as we tell it too. While you can just write a bunch of duplicates of the same line of code, that is not only wasting space, but that’s just plain easy. In programming, you always want a shorter, cleaner workaround. Luckily, such exists within the world of coding:

#include <stdio.h>
int main()
{
    int x;
    for ( x = 1; x <= 10; x++ ) {
            printf( "%d\n", x );
    }
getch();
}

These are called for loops. Essentially, it is a function in which you initialize and assign a variable, add a condition and what should you do with it. Let me explain as usual:

  • ‘for ( x = 1; x ⇐ 10; x++ )’ Inside the parenthesis, notice how we separate each of the three requirements.
    • ‘x = 1’ simply means we are creating a integer with the name ‘x’ and assigning it ‘1’, in other words, we are starting off with 1.
    • ‘x ⇐ 10’ is a condition telling the loop how many times should it loop.
    • ‘x++’ is simply telling how should the ‘for loop’ loop the code.

Programming


QR Code
QR Code c_programming_tutorials (generated for current page)
 

Advertise with Anonymous Ads