Publishing System Settings Logout Login Register
[C] Beginner Examples Tutorial
TutorialCommentsThe AuthorReport Tutorial
Tutorial Avatar
Rating
Add to Favorites
Posted on February 28th, 2008
20668 views
C++ General

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:


C was invented by a man named Dennis Ritchie. C is the predecessor tothe language B (invented by Ken Thompson) and the language B wasinfluenced by the language BCPL(invented by Martin Richards). C "tookthe 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 itvery quickly spread to multiple platforms. When Invented, C was mainlyused for creating programs that would control hardware but not so longafter, it became common to see C applications being programmed forregular 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 Csource code into a lower level language, such as ASM(Assembly) orMachine 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 theseperate programs needed for compiling bunched into one (sometimesgraphical) interface.

For Windows, i find the mostuser-friendly and easy to navigate(also good because it's free) IDE isDev-CPP (My personal opinion), which is originally a C++ compiler butgives 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 wheninstalled you just have to know the correct syntax for compilation andwhich compiler you are using (all this information should be availablein the documentation).

nowthat you know a little bit about the history of C and have got acompiler (hopefully), i think we can get started on some simpleapplications so let's get started!

The Hello World Application:


Well, nearly every first tutorial for any programming languageyou will come across will start with this traditional example, thestandard "Hello World" program, so i may as well follow the tradition

#include 

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

Now, lets break the program down.

#include-

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".


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 yourprogram. 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 whateveris inside the double quotes to the console, in this case it is "HelloWorld". note that
the whole function is in lowercase, all standardfunctions must be typed in lowercase else the compiler will not knowwhich 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 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; -

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

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

Indentation & Whitespace:

so by reading the title of this mini section you will probably not knowwhat indentation means, and you will probably will know what whitespaceis, 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 indentationis i'll show you by a quick example.

Indented Source:

#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).

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 makes it easier for them to navigate too.

Comments:

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

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

Now comments are done like the following:

#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.

Variables:

Before we go any further i think i should explain what variables areand how they are used. Variables are like storage boxes, whenever theyare made they are made for a specific purpose, in C variables are madewith a specific DATA TYPE such as INT and CHAR. Once Created andassigned a data type, the variable will only accept values within thatdata 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 ableto store a value such as "a" into it. Why? because we specified whendeclaring the variable that we only want to store INT (integer) valuessuch as "1","2" and "3" into the variable named "tutorial".

Just like storage boxes we can put things into variables and use themwhen 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:

#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.

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

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.

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:

#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:).

scanf("%s", a); - we use the function scanf to tell the program that we wish to wait foruser input and we want that user input to be a string (%s = string) andthat 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 iexplained before) so that we can see the input and output.

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

/0

If and Else Statements:

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

Pseudocode definition:
a way of writingprogram descriptions that is similar to programminglanguages but mayinclude English descriptions and does not have aprecise syntax.

Source:
http://www.cs.utexas.edu/users/novak/cs307vocab.html

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.

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

You will notice that there is aampersand(&) before the variable "age" when we call scanf beforethe if statement. This is needed because the variable parameter of scanfin this case "age" needs to be a pointer when dealing with decimalvalues, not the contents of a variable. Simply put - A pointer is areference to a memory address, it POINTS to a memory address and thefunction scanf will only take the parameter as a pointer so what we dois throw a "&" infront of the variable to give the function apointer to the variable we wish to print, i hope i explained thatalright haha pointers are one of the hardest subjects for programmers inmy opinion! I'll speak more about pointers later.

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

>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:

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

+ 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.

Ok, so you can see once we call scanf to grab the user input, we use anif statement and a else if statement (we can't use two if statements ina row or else when it comes to creating the else statement the programwill get confused and print what it's not supposed to) to determine whatwill happen depending on the option if the user entered 1, the programwill increment the starting number by one, this simply done by namingthe variable and placing the increment operator at the end(startingnumber++;) and end the statement with a semi-colon. Thedecrementing process is pretty much the same apart from the fact thatthe 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 theyenter anything apart from the options granted, flush the standardinput, 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 touse them seperately then i'll show you how to make a basic calculator:

Addition:

#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.


i'd advise you to read over the code a couple of times and maybetype it out at least twice just to soak it into your head, since i gavea pretty good explanation about operators and how to use them so far inthis 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 buti'll explain it now:

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.

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

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.

Loops:

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

Let'ssay we have programmed a password protection program, and all theprogram does is prompt the user for a user name and password, once thecorrect account details are received the password protection programtransfers control to the main program. For this program, we don't wantthe program to exit immediately after a user has a failed attempt(unless you were implementing a sort of lock out feature after X amountof 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 loginmany times without having to re-execute the program every time, here'ssome example source:

#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:

Prints from 0-1000 in console:

#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:

Normal Variables:

#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".

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

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.

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 gettime. If you find any mistakes in this tutorial please feel free toinform me as i just finished typing this all in one go and i'm tired! :)

Dig this tutorial?
Thank the author by sending him a few P2L credits!

Send
Encrypt

Hello, my name is Daniel. I live in the UK (Northern Ireland) and have done for my whole life. On the computer i enjoy programming, reverse engineering and playing games every now and again.
View Full Profile Add as Friend Send PM
Pixel2Life Home Advanced Search Search Tutorial Index Publish Tutorials Community Forums Web Hosting P2L On Facebook P2L On Twitter P2L Feeds Tutorial Index Publish Tutorials Community Forums Web Hosting P2L On Facebook P2L On Twitter P2L Feeds Pixel2life Homepage Submit a Tutorial Publish a Tutorial Join our Forums P2L Marketplace Advertise on P2L P2L Website Hosting Help and FAQ Topsites Link Exchange P2L RSS Feeds P2L Sitemap Contact Us Privacy Statement Legal P2L Facebook Fanpage Follow us on Twitter P2L Studios Portal P2L Website Hosting Back to Top