rogue poser
06-25-2009, 05:53 PM
Intro to the C/C++ programming Language!
[Hopefully this gets stickied]
I noticed that the c section was missing a basic tut, so i took the liberty of wasting an hour of my life to write this.
this guide is meant for people who have a general knowledge of programming, im sure people with scar knowledge will have no problems
TABLE OF CONTENTS
1.The Basics
2.Comments
3.Data Types
4.User Input
5.Constants
6.Operators and Logic
7.If statements and loops
8.Arrays
9.Character Array VS Strings
more to come soon! (functions, pointers, dynamic memory, classes, structures)
1.The Basics
every C program has at least three main sections. Following is an example of a basic C program.
#include <iostream>
using namespace std;
int main()
{
cout << "My first C program!\n" << endl;
return 0;
}
compile this.
CONGRATS! your very first C program.
**(if you are using dev c++, i think you may need to add "system("pause");" right after the cout, or it will flash very quickly)
first you have the includes. This is a defintion of what files we will be using, outside of our file.
After that you will notice the namespace section. A namespace is, as it says, a place for names. this a structure that stores variables and what not. a basic example of a namespace is
namespace this
{
int variable;
}
if you had an include with this declared in the include, you could access variable either by calling "this::variable"or declaring this as a namespace and then using variable. (if you dont get namespaces thats okay, you can learn about them later, just know that you need them to call functions)
Then we have out main function. int main() defining that we will be returning an integer value, thus returning 0 after were finished with whatever were doing to close the program.
As you can see we call the "cout" function to display some information to the screen. in this case "My first C program!"
the "\n" within an output means that there is to be a line break. As you can see "endl" will also end the line
Got it?
2.Comments
This is a very short section, just to tell you a bit about comments. comments are very important because some time when c programming you will get a 400 line nightmare of code and it will make sense... then a week later you have no idea what the hell you did. you can add comments to you previous program in 2 ways, examine the following code
#include <iostream>
using namespace std;
int main()
{
cout << "My first C program!"; // this is a comment for a single line
/*this is also a
comment, only it
continues until
its terminated*/
return 0;
}
3.Data Types
Now were going to start to get into the meat of C, and were going to talk about different variables.
The most common variables that you will be using are probably going to be integers, floats, booleans and characters. When these are declared outside of main or a function, they are considered global, because they can be used by any function. this is generally frowned upon because it tends to lead to user errors with calculations
integers are whole numbers, floats are numbers with possible decimal points, booleans are true or false, and characters are, well characters.
#include <iostream>
using namespace std;
int global_variable = 12;
int main()
{
cout << global_variable;
return 0;
}
This is an example of a variable that is local
#include <iostream>
using namespace std;
int main()
{
int local_variable = 12;
cout << local_variable;
return 0;
}
Now the variables are quite easy to declare, you have already seen how integers are declared, here are the others
float float_example;
char character_example;
bool bool_example;
to declare more than one variable, simply seperate them by commas.
int this,that;
when you give a variable a number it is known as initializing it. the most convenient way to do this is
int x = 10;
but it can also be accomplished like this
int x (10);
^^^ (that is called casting, and is pretty convenient when used to transform data types)
So now you have a basic idea of variables
4. User Input
User input in the command line is pretty straight forward. what you need to do is allocate memory for a variable, and then prompt the user for the input
#include <iostream>
using namespace std;
int main()
{
int user_input;
cout << "please enter a number\n:";
cin >> user_input;
cout << "the number was " << user_input << endl;
return 0;
}
obviously entering characters or floats will skrew it up, i may cover error handling later
5.Constants
this is going to be very short, constants are easy, and sometimes necessary (although variables that you never change are just as convenient)
lets say i have a program that is trying to find the area of a circle
#include <iostream>
#define PI 3.1415
using namespace std;
int main()
{
float radius;
cout << "please enter the radius of the circle\n:";
cin >> radius;
cout << "the area is was " << radius * radius * PI <<" sq units" << endl;
return 0;
}
as you can see we defined PI to equal 3.1415, and used basic mathematical operators to output the area of the circle. you can define more with constants than you can with variables, perhaps we will delve deeper into this later
using those operators we will now cover the basic math operators that do not need extra includes
6.Operators and Logic
+,-,*,/,%
examples
a = a + 12;
b = b - 5;
c = c * c;
d = d / 2;
e = e % 3;
All of these but the last one are self explanatory except for the last one. im not sure what its called, but what it does is it takes the remainder and that is what it will be defined as
for example
int e = 10;
e = e % 3;
e will equal 1, because it will divide 10 by 3, and the answer is 3 remainder 1. that operator outputs the remainder of the division.
in addition to that, if you want to increment, or decrement an integer you can do it easily with these operators
a++;
a--;
the final will be one added to a, or one subtracted from a respectively;
that was easy eh?
now for the logic portion of this bit.
there are a few logical operators ever c programmer will need to use on a regular basis. They are
== equal
!= not equal
>= greater than or equal to
<= less than or equal to
> greater than
< less than
These operators are very heavile used in if statements. they can be used kinda of like booleans. here is an example
#include <iostream>
using namespace std;
int main()
{
int a, b;
a = 3;
b = 4;
if(a < b)
cout << "a is less than b\n";
if(b > a)
cout << "b is greater than a\n";
if(b == a)
cout << "b and a are equivelant\n";
return 0;
}
as you can see, the first and second if statements evaluate to true, so their coresponding "cout" statements are output, while the last one evaluates to sale so its informations is not output
7.If statements and loops
as seen in the last example and if statement was used, we will now expand on that knowlede. notice how online the first line after the if was executed if it evaluated to true? C has a very convenient feature built in for the cases when you only need to execute one thing after an if. that is, unless otherwise defined and if statements following line will be executed. heres an example of the alternative
#include <iostream>
using namespace std;
int main()
{
int a, b;
a = 3;
b = 4;
if(a == b)
{
cout << "a is equal to b\n";
cout << "a + b = " << a + b << endl;
}
return 0;
}
notice how nothing will be output because both statements are within the brackets. now lets try it without the brackets
#include <iostream>
using namespace std;
int main()
{
int a, b;
a = 3;
b = 4;
if(a == b)
cout << "a is equal to b\n";
cout << "a + b = " << a + b << endl;
return 0;
}
notice how it outputs a+b? C ignores spaces, they mean nothing to the compiler. the only reason they are there is so that you, the user have an idea of what the frick is going on
in addition to the if statments there is the "else if" and the "else" statements. as is readily apparent the else if will check its operator if the if function returns false, and the else function will do whatever you tell it, if the "if" or "else if" are both false
#include <iostream>
using namespace std;
int main()
{
int a, b;
a = 3;
b = 4;
if(a == b)
{
cout << "a is equal to b\n";
}
else if(a > b)
{
cout << "a is greater than b\n";
}
else
{
cout << "a is neither equal or greater than b\n";
}
return 0;
}
if youre still unsure, play with the numbers and watch what happens
now lets talk a bit about loops. We have for, while, and do while loops, as well as switch statements
for(i=0; i<10;i++)
{
cout << i << endl;
}
this is a basic for loop. what it does is, it starts out iterator i at 0, then it adds one (i++) while it is less than 10. simple enough?
bool repeat = true;
int i = 0;
while(repeat)
{
if(i>5)
repeat = false;
i++;
}
this is an example of a while loop. since repeat is true, it will evaluate until repeat is false. repeat will be false when i = 5. notice that this loop will not evaluate if repeat is false. that is different then the do while loop
bool repeat = true;
int i = 0;
do
{
if(i>5)
repeat = false;
i++;
} while (true);
the do while loop with execute at least one time even if the evaluation is false.
Another very useful statement is the switch, case statment. this statment will keep you from making a giant if festival out of your code
switch(i)
{
case 1: cout << "i = 1 \n";
break;
case 2: cout << "i = 2 \n";
break;
default: cout << "i is something else";
}
8.Arrays
an array is a group of information stored in an east to access location. for example
int array_example[5];
that will allocate enough memory to store 5 inegers at slots 0-4 of the array. remember that the arrays always start at slot 0, so if you define an array of 10, 9 will be the highest number you can access. forgetting this tib bit will cause for headaches, as you will be returning some weird values and you will have no idea where they are coming from, so log that somehwere in your noggin.
if i wanted to store the value 46 in the 3 slot of the array i could simply do this
array_example[2] = 46;
in addition to the normal array, multidimensional arrays are else very handy. imagine an excel spreadsheet that is 5 by 5. if i were to make a virtual data structure to hold that information a 2 dimensional array would do the trick
int excel_example[5][5];
now when i want to store information in this array i must identify where in both arrays i want the information.
excel_example[0][0] = 34;
this would store the number 34 in the element located at the position 0,0 of the array.
9.Character Array VS Strings
Alright, some time you will probably have to deal with comparing different sets of information that happen to be words. Character arrays are defined like this
char array_example[] = "example";
or
char array_example[8] = "example";
both strings have memory allocated for 8 places even though there are 7 letters in the word. at the end of a character array there is a null terminator "/0" that signifies the end of the array. remember to leave room for the terminator.
in C, there is a class made to deal specifically with character arrays called the string class. this class is within the namespace std, and was made to make your life of dealing with character arrays much easier.
#include <iostream>
int main()
{
std::string my_string = "holy crap\n";
cout << my_string;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
string my_string = "holy crap\n";
cout << my_string;
return 0;
}
To find out just how much easier it is to deal with string than character arrays, take for example a simple comparison of the array.
char first_string[] = "wow", second_string[] = "something";
first_string = second_string;
this will not work because in c you cannot compare entire arrays to eachother. in order to set the first character array equal to the second one you must do something like this
#include <iostream>
using namespace std;
int main()
{
int i;
char first_string[] = "wow", second_string[] = "something";
for(i=0; i<sizeof(second_string); i++)
first_string[i] = second_string[i];
cout << first_string;
return 0;
}
now running a for loop everytime you want to set a character array equal to another is quite cumbersome. thats where the string class comes in. lets try another tidbit of code shall we
#include <iostream>
using namespace std;
int main()
{
string first_string = "wow", second_string = "something";
first_string = second_string;
cout << first_string;
return 0;
}
much easier, wouldnt you say? strings are your friends, remember them, they will be nice to you
[Hopefully this gets stickied]
I noticed that the c section was missing a basic tut, so i took the liberty of wasting an hour of my life to write this.
this guide is meant for people who have a general knowledge of programming, im sure people with scar knowledge will have no problems
TABLE OF CONTENTS
1.The Basics
2.Comments
3.Data Types
4.User Input
5.Constants
6.Operators and Logic
7.If statements and loops
8.Arrays
9.Character Array VS Strings
more to come soon! (functions, pointers, dynamic memory, classes, structures)
1.The Basics
every C program has at least three main sections. Following is an example of a basic C program.
#include <iostream>
using namespace std;
int main()
{
cout << "My first C program!\n" << endl;
return 0;
}
compile this.
CONGRATS! your very first C program.
**(if you are using dev c++, i think you may need to add "system("pause");" right after the cout, or it will flash very quickly)
first you have the includes. This is a defintion of what files we will be using, outside of our file.
After that you will notice the namespace section. A namespace is, as it says, a place for names. this a structure that stores variables and what not. a basic example of a namespace is
namespace this
{
int variable;
}
if you had an include with this declared in the include, you could access variable either by calling "this::variable"or declaring this as a namespace and then using variable. (if you dont get namespaces thats okay, you can learn about them later, just know that you need them to call functions)
Then we have out main function. int main() defining that we will be returning an integer value, thus returning 0 after were finished with whatever were doing to close the program.
As you can see we call the "cout" function to display some information to the screen. in this case "My first C program!"
the "\n" within an output means that there is to be a line break. As you can see "endl" will also end the line
Got it?
2.Comments
This is a very short section, just to tell you a bit about comments. comments are very important because some time when c programming you will get a 400 line nightmare of code and it will make sense... then a week later you have no idea what the hell you did. you can add comments to you previous program in 2 ways, examine the following code
#include <iostream>
using namespace std;
int main()
{
cout << "My first C program!"; // this is a comment for a single line
/*this is also a
comment, only it
continues until
its terminated*/
return 0;
}
3.Data Types
Now were going to start to get into the meat of C, and were going to talk about different variables.
The most common variables that you will be using are probably going to be integers, floats, booleans and characters. When these are declared outside of main or a function, they are considered global, because they can be used by any function. this is generally frowned upon because it tends to lead to user errors with calculations
integers are whole numbers, floats are numbers with possible decimal points, booleans are true or false, and characters are, well characters.
#include <iostream>
using namespace std;
int global_variable = 12;
int main()
{
cout << global_variable;
return 0;
}
This is an example of a variable that is local
#include <iostream>
using namespace std;
int main()
{
int local_variable = 12;
cout << local_variable;
return 0;
}
Now the variables are quite easy to declare, you have already seen how integers are declared, here are the others
float float_example;
char character_example;
bool bool_example;
to declare more than one variable, simply seperate them by commas.
int this,that;
when you give a variable a number it is known as initializing it. the most convenient way to do this is
int x = 10;
but it can also be accomplished like this
int x (10);
^^^ (that is called casting, and is pretty convenient when used to transform data types)
So now you have a basic idea of variables
4. User Input
User input in the command line is pretty straight forward. what you need to do is allocate memory for a variable, and then prompt the user for the input
#include <iostream>
using namespace std;
int main()
{
int user_input;
cout << "please enter a number\n:";
cin >> user_input;
cout << "the number was " << user_input << endl;
return 0;
}
obviously entering characters or floats will skrew it up, i may cover error handling later
5.Constants
this is going to be very short, constants are easy, and sometimes necessary (although variables that you never change are just as convenient)
lets say i have a program that is trying to find the area of a circle
#include <iostream>
#define PI 3.1415
using namespace std;
int main()
{
float radius;
cout << "please enter the radius of the circle\n:";
cin >> radius;
cout << "the area is was " << radius * radius * PI <<" sq units" << endl;
return 0;
}
as you can see we defined PI to equal 3.1415, and used basic mathematical operators to output the area of the circle. you can define more with constants than you can with variables, perhaps we will delve deeper into this later
using those operators we will now cover the basic math operators that do not need extra includes
6.Operators and Logic
+,-,*,/,%
examples
a = a + 12;
b = b - 5;
c = c * c;
d = d / 2;
e = e % 3;
All of these but the last one are self explanatory except for the last one. im not sure what its called, but what it does is it takes the remainder and that is what it will be defined as
for example
int e = 10;
e = e % 3;
e will equal 1, because it will divide 10 by 3, and the answer is 3 remainder 1. that operator outputs the remainder of the division.
in addition to that, if you want to increment, or decrement an integer you can do it easily with these operators
a++;
a--;
the final will be one added to a, or one subtracted from a respectively;
that was easy eh?
now for the logic portion of this bit.
there are a few logical operators ever c programmer will need to use on a regular basis. They are
== equal
!= not equal
>= greater than or equal to
<= less than or equal to
> greater than
< less than
These operators are very heavile used in if statements. they can be used kinda of like booleans. here is an example
#include <iostream>
using namespace std;
int main()
{
int a, b;
a = 3;
b = 4;
if(a < b)
cout << "a is less than b\n";
if(b > a)
cout << "b is greater than a\n";
if(b == a)
cout << "b and a are equivelant\n";
return 0;
}
as you can see, the first and second if statements evaluate to true, so their coresponding "cout" statements are output, while the last one evaluates to sale so its informations is not output
7.If statements and loops
as seen in the last example and if statement was used, we will now expand on that knowlede. notice how online the first line after the if was executed if it evaluated to true? C has a very convenient feature built in for the cases when you only need to execute one thing after an if. that is, unless otherwise defined and if statements following line will be executed. heres an example of the alternative
#include <iostream>
using namespace std;
int main()
{
int a, b;
a = 3;
b = 4;
if(a == b)
{
cout << "a is equal to b\n";
cout << "a + b = " << a + b << endl;
}
return 0;
}
notice how nothing will be output because both statements are within the brackets. now lets try it without the brackets
#include <iostream>
using namespace std;
int main()
{
int a, b;
a = 3;
b = 4;
if(a == b)
cout << "a is equal to b\n";
cout << "a + b = " << a + b << endl;
return 0;
}
notice how it outputs a+b? C ignores spaces, they mean nothing to the compiler. the only reason they are there is so that you, the user have an idea of what the frick is going on
in addition to the if statments there is the "else if" and the "else" statements. as is readily apparent the else if will check its operator if the if function returns false, and the else function will do whatever you tell it, if the "if" or "else if" are both false
#include <iostream>
using namespace std;
int main()
{
int a, b;
a = 3;
b = 4;
if(a == b)
{
cout << "a is equal to b\n";
}
else if(a > b)
{
cout << "a is greater than b\n";
}
else
{
cout << "a is neither equal or greater than b\n";
}
return 0;
}
if youre still unsure, play with the numbers and watch what happens
now lets talk a bit about loops. We have for, while, and do while loops, as well as switch statements
for(i=0; i<10;i++)
{
cout << i << endl;
}
this is a basic for loop. what it does is, it starts out iterator i at 0, then it adds one (i++) while it is less than 10. simple enough?
bool repeat = true;
int i = 0;
while(repeat)
{
if(i>5)
repeat = false;
i++;
}
this is an example of a while loop. since repeat is true, it will evaluate until repeat is false. repeat will be false when i = 5. notice that this loop will not evaluate if repeat is false. that is different then the do while loop
bool repeat = true;
int i = 0;
do
{
if(i>5)
repeat = false;
i++;
} while (true);
the do while loop with execute at least one time even if the evaluation is false.
Another very useful statement is the switch, case statment. this statment will keep you from making a giant if festival out of your code
switch(i)
{
case 1: cout << "i = 1 \n";
break;
case 2: cout << "i = 2 \n";
break;
default: cout << "i is something else";
}
8.Arrays
an array is a group of information stored in an east to access location. for example
int array_example[5];
that will allocate enough memory to store 5 inegers at slots 0-4 of the array. remember that the arrays always start at slot 0, so if you define an array of 10, 9 will be the highest number you can access. forgetting this tib bit will cause for headaches, as you will be returning some weird values and you will have no idea where they are coming from, so log that somehwere in your noggin.
if i wanted to store the value 46 in the 3 slot of the array i could simply do this
array_example[2] = 46;
in addition to the normal array, multidimensional arrays are else very handy. imagine an excel spreadsheet that is 5 by 5. if i were to make a virtual data structure to hold that information a 2 dimensional array would do the trick
int excel_example[5][5];
now when i want to store information in this array i must identify where in both arrays i want the information.
excel_example[0][0] = 34;
this would store the number 34 in the element located at the position 0,0 of the array.
9.Character Array VS Strings
Alright, some time you will probably have to deal with comparing different sets of information that happen to be words. Character arrays are defined like this
char array_example[] = "example";
or
char array_example[8] = "example";
both strings have memory allocated for 8 places even though there are 7 letters in the word. at the end of a character array there is a null terminator "/0" that signifies the end of the array. remember to leave room for the terminator.
in C, there is a class made to deal specifically with character arrays called the string class. this class is within the namespace std, and was made to make your life of dealing with character arrays much easier.
#include <iostream>
int main()
{
std::string my_string = "holy crap\n";
cout << my_string;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
string my_string = "holy crap\n";
cout << my_string;
return 0;
}
To find out just how much easier it is to deal with string than character arrays, take for example a simple comparison of the array.
char first_string[] = "wow", second_string[] = "something";
first_string = second_string;
this will not work because in c you cannot compare entire arrays to eachother. in order to set the first character array equal to the second one you must do something like this
#include <iostream>
using namespace std;
int main()
{
int i;
char first_string[] = "wow", second_string[] = "something";
for(i=0; i<sizeof(second_string); i++)
first_string[i] = second_string[i];
cout << first_string;
return 0;
}
now running a for loop everytime you want to set a character array equal to another is quite cumbersome. thats where the string class comes in. lets try another tidbit of code shall we
#include <iostream>
using namespace std;
int main()
{
string first_string = "wow", second_string = "something";
first_string = second_string;
cout << first_string;
return 0;
}
much easier, wouldnt you say? strings are your friends, remember them, they will be nice to you