Posted on February 28th, 2008
20671 views
Beginner C Examples By Komo http://www.Pixel2life.com - Published Feb/2008 My (OLD) Aliases - Encrypt, Shoxin, GoSu.SpeeD, Anko, Akimoko, skEncrypt and Many more.
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
Background Information: Most(if not all) UNIX-based operating systems come with a C compiler wheninstalled you just have to know the correct syntax for compilation andwhich compiler you are using (all this information should be availablein the documentation).
#include int main() { printf("Hello World\n"); return 0; } Now, lets break the program down. With this line, we include the standard input/output C library thisallows us to call functions that are within this specific library. Oneof these functions happens to be "printf".
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 tellsthe program that the statement is finished. if you forget the semi-colonthe compiler will start giving you compiling errors, a common one is"Missing terminating character". return 0; - #include int main() { printf("hey, this source is indented"); return 0; } Not Indented Source: #include 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'tbe) to recognise the differences. Indentation is the method of insertingwhitespace at the start of your line. Now some people might bethinking, what is whitespace? Well to put it simple, whitespace is justWHITE SPACE or any kind of open space in your source (hard to grasp theconcept isn't it? /sarcasm :D). #include 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 yoursituation. The older way to comment has the ability to create multipleline comments like so #include 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 abanner at the top of my source with website information,authorinformation etc. For commenting what's going on in the source i wouldmostly use the newer way. #include int main() { int a; return 0; } This tells the program that we want to DECLARE an integer variablewith the name of "a". Now that we've DECLARED our INT variable and gveit the name "a". Now i'll show you how to store a value in our variable"a". #include int main() { int a; a = 1; return 0; } So we start off as usual by declaring our variable "a" then we usethe 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: #include int main() { int a = 1; return 0; } This is a quicker way as you can see and is useful to save time whenworking with a lot of variables. We can also print variables to theconsole for the user to see, like so: #include int main() { int a = 1; printf("%d", a); return 0; } "%d" tells the program that we wish to print a DECIMAL value and thevalue is stored in the variable "a". If done correctly, when ran theprogram will display in the console window the number "1" which weearlier stored in the variable "a". By now you have probably noticedthat when you try to run the program that it will run then closeimmediately, you might be thinking why this is happening or that you'vedone something wrong - don't worry it's simply because we didn't tellthe program to pause after displaying the output in the console. To fixthis problem, we do the following: #include int main() { int a = 1; printf("%d", a); getchar(); return 0; } getchar() - Will create a pause because the function getchar is used to take onecharacter of input from the user so - the program will run then wait foryou to press a key then it will exit. system("pause"); while this function was designed for the purpose of pausing it isconsidering bad programming to use this because, you are borrowing afunction from the operating system meaning that if you were to use thissame program on another OS such as *nix then it would not run correctly,it would make your program, single-platform. #include int main() { char a[10]; // Good practice is to seperate your variables from the rest of your code printf("Hello, what is your name?\n"); scanf("%s", a); printf("You entered: %s", a); fflush(stdin); getchar(); return 0; } char a[10] - Wedeclare a char (character) array (which has the ability to contain 9characters, i know it says 10, i'll explain that part later) so thevariable can hold more than one character, enabling us to store a stringinside the variable instead of just one letter. C unfortunately doesnot have a "string" data type but char arrays fill the void pretty well:). /0 If and Else Statements: Pseudocode definition: Example If statement using PseudoCode: if (this condition is true) { execute this statement } so basically, the if statement will check if the condition providedis true and if it is it will do the action provided in the braces, if itis found that the condition is not true then the program will justcontinue, unless you add in an else statement then it obviously executewhatever is provided inside the else function. Now i'll show you aPseudoCode example of using If and Else: 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 youjust think of it in a logical sense. Now i'll show some real examples ofif and else working together. #include 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 programmer"); } 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 startat the line of the "if". We start our if statement by typing "if" thenwe open our parenthesis and place our condition inside, which is "age ==17" which in english translates to "age is equal to 17", then we closeour parenthesis. Next we open our braces on the line below then on thenext line we call the printf function to display a unique message to theuser if the user's input is equal to the number 17, we then close ourbraces and begin our else statement. >greater than5 > 4 is TRUE < 5 is TRUE >=greater than or equal4 >= 4 is TRUE <=less than or equal3 <= 4 is TRUE ==equal to5 == 5 is TRUE !=not equal to5 != 4 is TRUE Credits to Cprogramming.com for this little table! Arithmetic: + 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 ithink only some of you will know them meaning of the last two, so i'llgive an explanation. C gives us two operators: Increment(++) andDecrement(--). Now what increment will do is add 1 to it's operand anddecrement will decrease it's operand by 1, not too hard to understand.Here is an example using the Increment and Decrement operators: #include 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 usedin the code has been explained in previous sections so if your a bithazey about a part of the code just check the previous sections. #include int main() { int num1 = 2; int num2 = 2; printf("num1 + num2 = %d", num1 + num2); getchar(); return 0; } Subtraction: #include int main() { int num1 = 2; int num2 = 2; printf("num1 - num2 = %d", num1 - num2); getchar(); return 0; } Division: #include int main() { int num1 = 2; int num2 = 2; printf("num1 / num2 = %d", num1 / num2); getchar(); return 0; } Multiplication: #include int main() { int num1 = 2; int num2 = 2; printf("num1 * num2 = %d", num1 * num2); getchar(); return 0; } Modulus: #include 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 goodto practice everything a little bit at a time so you will absorb itmore and hopefully remember it for a long time, now we piece everythingtogether that i've taught in this section and make a simple calculator: #include int main() { int n1, n2, loop, high, low; 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 == '-') { if (n1 > n2) { high = n1; low = n2; } else { high = n2; low = n1; } printf("The result of: %d - %d is %d\n", high, low, high - low); } if (op == '/') { if (n1 > n2) { high = n1; low = n2; } else { high = n2; low = n1; } printf("The result of: %d / %d is %d\n", high, low, high / low); } 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'tuse two or more ifstatements in a row? don't forget that it's alrightto do it if youaren't planning on using an else statement.
while(loop != 1) { } This, in C is what we call a loop. Loops like their name indicateswill loop whatever is inside the braces if the condition gave in theparenthesis is true, since this section is not covering loops i willonly give a brief explanation and i will save the rest for the nextsection. while(loop is not equal to 1) { do this } One last thing: if (n1 > n2) { high = n1; low = n2; } else { high = n2; low = n1; } Incase anyone got confused about what the above does, basically youknow when you try to type into a calculator for example "1 - 3", it willgive you "-2", this is just basically an auto-correction of that. Itchecks which number is the lowest and which is the highest and placesthem into the appropriate variables, we then later use these variablesto subtract/divide correctly. well, that's all for this section, i hope i explained it well, if youdidn't quite get a certain part of this section or any section of thistutorial, don't hesitate to PM and i'll be glad to help as best i can. #include int main() { int input; int code = 1094; while (input != 1094) { ("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 loopbecause i've covered everything else in previous sections. The loop iused in this program is a simple while loop, it can be translated toenglish very easily: 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, theparenthesis contain the condition, braces contain the code to be looped.an Infinite loop can be achieved very easily as well: while(1) { // Insert Code Here } Some of you might be wondering why this induces an infinite loop,well remember earlier when i said a loop will continue until thecondition specified is true? Well when we make the condition to onlycontain 1, the program can see that 1 is a nonzero value so that itselfmakes the result ALWAYS true (0 = false , 1 = true) but when using thistype of infinite loop it is advised to add a sleep function just afterthe opening brace because this type of infinite loop hogs ALL computerusage, to do so: while(1) { sleep(10); } the sleep command does exactly what it's named, it makes the programsleep for the time specified in the parameter which in this case is"10", sleep on windows ratio: 1000 = 1 second, so the above examplemakes the program sleep for 10 milliseconds at the start of the loopevery time. We do this because it stops the cpu usage from being eatenup and also won't interfere with the program. To use the sleep functionwe must include the windows header file so: #include The next and quite uncommon loop is the "Do While" loop, which works like this: #include 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 thebraces, while condition is true. I think the only part i need to explainabout this loop is the semi-colon after the last round bracket whichcontains the condition. The semi-colon is basically need to tell theprogram whether the "While" that was performed is the beginning of anormal while loop or the end of a "Do-while" loop. Note:Remember when using the do while loop that, the body will always beexecuted at least once, because the DO comes before the while. Thelast loop to discuss is the "For" loop. The for loop is a little morecomplicated than the while loops i've shown. If you think about itlogically it's easier to make sense of it, in real life i doubt any ofyou 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: For (Initialization; Conditions; Increment/Decrement Value) { //CODE } So if i include the code portion it has 4 parts, Incrementing andDecrementing is simply increasing/decreasing the current value by 1, andcan be as simple as adding ++(incrementing) or --(decrementing) to theend 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: #include 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: #include 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: For(;;) { sleep(10); } just simply edit your For loop to have no initializer, condition orincrement/decrement value, also do not forget to add the sleep commandto stop cpu usage getting too high. Finally, to break out of a loop, wedo the following: while(1) { if (condition is true) { break; } } Strings & Arrays : I have showed examples of using char arrays in previous chapters, buti didn't really give an explanation so i thought i'd do a sort of minisection for arrays. Unfortunately, in C there is no STRING datatype likethere is in many programming languages nowadays, but we have a simplesolution to that problem, CHAR Arrays! You might be thinking, what is anarray? well to put it as simple as possible, an array is a group ofelements stored in a variable. Still don't get it? To put it even moresimply, remember i described variables being like storage boxes? Wellarrays are like a bigger box that a group of storage boxes are placedinto, ok well i'll show some examples of arrays being used vs normalvariables: #include 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: #include 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 muchmore space than the second example. New programmers to C or new toprogramming in general often forget that the index of the first elementin C is '0'. What this means is that just say we declare an CHAR arrayand store 3 values inside like so: #include 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? #include int main() { char test[3] = {'a', 'b', 'c'}; printf("%c", test[0]); getchar(); } Now you will probably know won't what i meant by saying the firstelement in the array index is 0, it means that the first value getsstored in the '0' element, then '1' and so on. I heard that C is whatmade the number '0' as the first element so popular, practically everyprogramming language developed after C used this method, although, VB6grants you the option of creating a "start from 1 index". 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: #include 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 tothe variable "a". This is possible because the getchar() returns an intvalue, so that's why we can pass getchar to the INT variable a. Anotherreason for passing the return value to an integer value is incasegetchar returns EOF. EOF means End Of File and signals to the programwhen there is no more input, i don't think any char variable can holdthe EOF value, so we use INT:
do { a = getchar(); if (a == ' ') { SPACECOUNT++; } }while (a != '9');
Ok, so what is happening here is our loop starts, and getchar iscalled then our if statement executes and checks wether or not thecharacter that was caught in the input was the same as a space, if itwas then increment the variable "SPACECOUNT" then continue to the whilepart which contains our condition, if '9' is caught in the input thenbreak from the loop and continue to the end of the program which tellsthe user how many spaces he/she entered by printing from the spacecountvariable. |