Jump to content


Photo
- - - - -

[C] Beginner Examples


  • Please log in to reply
5 replies to this topic

#1 Encrypt

Encrypt

    Young Padawan

  • Members
  • Pip
  • 9 posts
  • Gender:Male
  • Location:Northern Ireland

Posted 17 February 2008 - 04:01 AM

Beginner C Examples
By Shoxin
http://www.pixel2life.com


Hello, i've created this tutorial for the purpose of introducing beginner programmers into the world of C.

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. Strings & Arrays
11. Ending Notes


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.

http://www.bloodshed...dev/devcpp.html


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.

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

#include <stdio.h>
   
   int main()
   {
	   printf("hey, this source is indented");
	   return 0;
   }

Not Indented Source:

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

#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

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

Note: Integer Values can be stored in char variables alongside characters, e.g. for storing an IP Address

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:

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

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

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

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

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

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

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

\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...cs307vocab.html


Example If statement using PseudoCode:

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:

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.

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

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

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

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

#include <stdio.h>
   
   int main()
   {
	   int num1 = 2;
	   int num2 = 2;
	   
	   printf("num1 + num2 = %d", num1 + num2);
	   getchar();
	   return 0;
   }

Subtraction:

#include <stdio.h>
   
   int main()
   {
	   int num1 = 2;
	   int num2 = 2;
	   
	   printf("num1 - num2 = %d", num1 - num2);
	   getchar();
	   return 0;
   }

Division:

#include <stdio.h>
   
   int main()
   {
	   int num1 = 2;
	   int num2 = 2;
	   
	   printf("num1 / num2 = %d", num1 / num2);
	   getchar();
	   return 0;
   }

Multiplication:

#include <stdio.h>
   
   int main()
   {
	   int num1 = 2;
	   int num2 = 2;
	   
	   printf("num1 * num2 = %d", num1 * num2);
	   getchar();
	   return 0;
   }

Modulus:

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

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

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 =

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

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:

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

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 round brackets contain the condition, braces contain the code to be looped. an Infinite loop can be achieved very easily as well:

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:

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:

#include <windows.h>

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

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

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:

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

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

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:

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:

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

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

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

#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, apart from Visual Basic, which i THINK kept the first element as '1' (i don't know for sure as i've never programmed in VB).

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:

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

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

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.

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.

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



#2 Indigo

Indigo

    Official Alien

  • Members
  • PipPipPip
  • 617 posts
  • Gender:Male
  • Location:Trondheim, Norway
  • Interests:Computing in general, especially design and programming of all kinds.

Posted 27 February 2008 - 04:46 PM

Didn't read the entire tutorial, since I know most of this already. Looked over your code-examples though, and this looks really good! I'd advice this to people just starting with C, it seems to be a really good tutorial. :D

#3 Leibrockoli

Leibrockoli

    Young Padawan

  • Members
  • Pip
  • 27 posts

Posted 27 February 2008 - 05:51 PM

There were some parts where the text of the tutorial were hard to read due to the light blue text and white background. :D

Otherwise I'd say it makes for a good tutorial start. I overlooked some of the basic things and I saw I knew most of it from C++, but every programming language starts from C.

#4 vvtopkar

vvtopkar

    P2L Jedi

  • Members
  • PipPipPip
  • 532 posts
  • Gender:Male
  • Location:3rd Planet from the Sun

Posted 27 February 2008 - 06:20 PM

Just skimmed it, but it looks like a really nice in-depth tut on C, with I had this when I was learning it! :D

#5 Encrypt

Encrypt

    Young Padawan

  • Members
  • Pip
  • 9 posts
  • Gender:Male
  • Location:Northern Ireland

Posted 29 February 2008 - 04:29 PM

Didn't read the entire tutorial, since I know most of this already. Looked over your code-examples though, and this looks really good! I'd advice this to people just starting with C, it seems to be a really good tutorial. :o


Thanks :)

There were some parts where the text of the tutorial were hard to read due to the light blue text and white background. :o

Otherwise I'd say it makes for a good tutorial start. I overlooked some of the basic things and I saw I knew most of it from C++, but every programming language starts from C.


Yeah, i need to change this when i get time, this is because originally the forum i decided to post this on a long while ago, used dark layouts, so the royalblue color was the best choice.

Just skimmed it, but it looks like a really nice in-depth tut on C, with I had this when I was learning it! :D


Thanks :o

I'll add more to it as i get time, but recently i've found myself very busy.

#6 WilliamHey

WilliamHey

    Young Padawan

  • Members
  • Pip
  • 1 posts

Posted 07 March 2008 - 09:17 AM

ITs a really nice tool this bro, you are awesome, you ROCK!!!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users