Вы находитесь на странице: 1из 14

Welcome to my basic C programing tutorial. You can download Turbo C 3.

0 using
the links below.

Turbo C 3.0
Host File
Doteasy tc3.zip tc3.exe
Geocities tc3.zip

Let's start the tutorial with a simple program.

For this tutorial you should to have TC 3.0 running and a browser so that you can
view the tutorial. You can switch between browser and TC 3.0 by pressing Alt-Tab.

#include <stdio.h>
#include <conio.h>

void main()
{
clrscr();
printf("Let's learn C programming.");
getch();
}

This litle progam outputs the the phrase "let's learn C programming" on the the screen.

Let's learn C programming.

Now let me tell you what each line means and does.

#include <stdio.h>
#include <conio.h>
These lines are called the preprocessors. Commands, like printf, are contained in these
prepreprocessor not the compiler itself. Just remember you need the stdio.h, or
standard input & output, to be able to use printf, scanf and such. Conio is needed for
the clrscr or clear screen.

main()
This where the actual program begin and end. Void means that it does not return a
value.
clrscr();
Clears the screen. Simple as that.

printf("Let's learn C programming.");


Prints whatever is inside the quotes inside the parenthesis. Another command similar
to printf is scanf which allows for the user's input.

getch();
This allows you to time to read the ouput on the screen. Without it the program would
just exit quickly and you wouldn't be able to see the output.

One thing you should notice are the semicolon(;) at the end of each statment except
for main(). These semicolon indicate where the statement ends. A statement is one
complete command just like printf("Let's learn C programming.");. A statement can
have many statement within itself and is contained in within the curly brace ({}) just
like main().

Try it out yourself, it's the only way you'll learn. Next we'll talk about variables, scanf
and math operators.

Welcome back. We are now going to talk about variables.

Variables, just like in Algebra are the letters representing a number. For the computer
variables are little storage place inside the memory. In C there are four types of
variables: integer, float point, double floating point and character.

The first one is the integer or counting numbers or numbers without decimals. The
second is floating point which are the fractional numbers or numbers with decimals.
Double is just like float except it can handle bigger numbers and has more precission,
it could hold more decimals places. The last one is characters, these are the letters and
numbers.

To be able to use the variables they must be first initialized. We must tell the program
that they exist, and create a location for them in the memory.

To initialize an integer we use int.


int x, y;
This initiates the integer variable x and y.

To initialize a floating point we use float.


float a, b;
This initiates the floating point variable a and b.
To initialize a double floating point we use double.
double c, d;
This initiates the double floating point variable c and d. You get the idea right?

To initialize a character we use char.


char s, t;
This initializes a character variable s and t.

To initialize a string we use character array.


char u[8], v[8];
This initializes a character variable array u and v of 7 characters. It's only seven
characters because the last one contains the terminating character. Just remember that
expected number of characters is always one less than the number specified.

Now we need to know specifiers. Specifiers are used when we want to input or output
value of variables using printf and scanf. It specifies what type of variable it it is, and
is always a percent sign (%) followed by a letter. For integers the specifier is %d, for
float and double %f for characters % and for strings %s.

Now, here's an example.

#include <stdio.h>
#include <conio.h>

char name[8];
int a,b,sum;

main()
{
clrscr();

printf("What is your name: ");


scanf("%s", &name);

printf("Please enter two numbers:");


scanf("%d %d", &a, &b);

sum=a+b;

printf("\nYour name is %s.\n", name);


printf("%d + %d = %d", a, b, sum);

getch();
return(0);
}

Here's the output.


What is your name: Anthony
Please enter two numbers: 1 2

Your name is Anthony.


1 + 2 = 3

printf("What is your name:");


scanf("%s", &name);
The first line ask the user their name and the scanf gets the input from the user. We
use the specifier %s because it is a string variable. There should be an ampersand
before the the varible where inputted data will be stored. C considers a space as a
terminating character only your first name can be saved. To be able to have spaces
you can replace the scanf with name=gets();.

printf("Please enter two numbers:");


scanf("%d %d", &a, &b);
Here, the user is asked to input two numbers and the numbers will be stored in
variable a and b. We used %d for integers and there should always be an ampersand in
front of the variable.

sum=a+b;
Adds the two numbers together and store the answer in the variable sum. The basic
mathematical operators are plus(+), minus(-), multiply(*), divide(/) and modulus(%).
What's modulus you ask, it returns the remainder. You should know what the rest of
them do. When performing division using integers the decimals are cut off.

printf("Your name is %s.\n", name);


printf("%d + %d = %d", a, b, sum);
When displaying variables, you have the comment inside the string and you replace
where you want the value of a variable to be with a specifier. The string is followed
by a comma and the variable. The order of the variable from left to right follows the
order of the specifier respectively.

That should do it for ya. Now time for your homework. Create a program that prompts
for your name and three numbers, compute for the sum and average and outputs your
name, the sum and average.

Click here to see what I did.

The output out put should look similar to this.


What is your name: Anthony
Please enter two numbers: 1 2 3

Your name is Anthony.


1 + 2 + 3 = 6
6 / 3 = 2

Did you actually do the homework? If not, go try it now. It's simple, you just change
and add a few to the example program I showed you. Next we will discus the
conditional statements when I get around to it.

If I did my homework, then I'd have a better grades. That statement would be
conditional statement. This lesson is all about conditional statements. In a conditional
statement we use, if you haven't guessed it yet, the "if" statement.

The syntax are:

if (condition) statement;

if (condition)
{
statement
statement
}

if (condition is true) execute this; else execute this instead;

That's all there is to it. If the condition is true then it runs the statement if not and else
is specified it runs that instead.

Here are the symbols used in a conditional statement:

> Greater than


< Less than
>= Greater than or equal to
<= Less than or equal to
== are equal

* Notice the condition "are equal" are two equal sign. If you use only one equal sign,
it assigns the value on the right to the variable on the left. For example x=1+2; the
value of x will become 3; and x==1+2, if x=3 then the condition is true.
Here's an example of a program that determines if a number inputed is positive or
negative.

#include
#include

int n;

void main() {
clrscr();
printf("Enter a number, positive or negative: ");
scanf("%d", &n);
if (n>=0) printf("%d is a positive number", n);
else printf("%d is a negative number", n);
getch();
}

That wasn't so hard wasn't?


Now here's your homework:

Write a program that ask user their age and outputs a comment based on the their
input. If the user enters 0 to 2 it outputs "Still a baby", 3 to 12 "Children", 13 to 17
"Teenager", 18 to 26 "Young Adult", 27 to 39 "Middle age", 40 to 79 "Grand
Parents", 80 and higher "Wow". That's all, have fun.

Click here to see what I did.

If the condition we want to determine is a constant, ie, the number 1 or letter a, then
we could use the case switch statement as an alternative to the if else statement. This
is usefull in instances like menus. Case Switch can not work with ranges like in our
last homework.

The syntax are:


switch (variable) {
case constant expresion: statement; break;
default: statement;
}

Oh fun! Now here is an example.

#include <stdio.h>
#include <conio.h>
char choice;

void main() {
clrscr();
printf("What flavor do you like?");
printf("\n\ta) Apple");
printf("\n\tb) Orange");
printf("\n\tc) Vanilla");
printf("\n\td) Mint\n: ");
choice=getche();
switch (choice) {
case 'a': printf("\nI like apple too."); break;
case 'b': printf("\nI like orange too."); break;
case 'c': printf("\nI like vanilla too."); break;
case 'd': printf("\nI like mint too."); break;
default: printf("Huh?");
}
getch();
}
That's it. On to for loops.

If you want to do the same things many time you can use a loop. In C, there are three
different kind of loops. They are the for loop, while loop, and the do while loop.
They come in handy in certain conditions. Right now we'll focus on the for loop.

The for loop is good for looping a definite amount of loops. That is you already know
how many times to loop. More importantly for loop can count. You can start from
any number, end in any number, and count in multiples for example, counting in odd
or even numbers.

The syntax is:

for (initialization; condition; incrementation) statement;

or for multiple statements:

for (initialization; condition; incrementation)


{
statement 1
statement 2
}

#include<stdio.h>
#include<conio.h>

int i;

void main() {
clrscr();
printf("Prints my name three times.\n");
for (i=0; i<3; i++) printf("Anthony Perlas\n");
printf("\nCounts from 1 to ten.\n");
for (i=1; i<=10; i++) printf("%d ", i);
printf("\n\nCounts down from 10 to 0.\n");
for (i=10; i>=0; i--) printf("%d ", i);
printf("\n\nCounts the odd numbers from 1 to 21.\n");
for (i=1; i<=21; i+=2) printf("%d ", i);
printf("\n\nMultiple statements.\n");
for (i=0; i<3; i++)
{
printf("%d ", i);
printf("Anthony Perlas\n");
}
getch();
}
Prints my name three times.
Anthony Perlas
Anthony Perlas
Anthony Perlas

Counts from 1 to ten.


1 2 3 4 5 6 7 8 9 10

Counts down from 10 to 0.


10 9 8 7 6 5 4 3 2 1 0

Counts the odd numbers from 1 to 21.


1 3 5 7 9 11 13 15 17 19 21

Multiple statements.
0 Anthony Perlas
1 Anthony Perlas
2 Anthony Perlas

What's i++? It's a short cut. It's much easier to type i++ than i=i+1. It also avoids
having to type the same variable twice. Here's a table of shortcuts in C.

The long Way i=i+1 i=i-1 i=i+2 i=i-2 i=i*2 i=i/2


The short cut i++ i-- i+=2 i-=2 i*=2 i/=2
Basically you take out the repeating variable and move the operator to the front of the
equal sign.

Nested For Loops:


You can put a loop inside a loop. This is called a nested loop. You can nest as many
loop as you can but keep it to a minimum as it could get confusing especially when
trying to debug your program.

Here's an example:

#include<stdio.h>
#include<conio.h>
#define max 5

void main() {
clrscr();
printf("Prints the value of i and j as it goes through the loop.\n");
for (int i=0; i<max; i++) for (int j=0; j<max; j++) printf("(%d, %d)\n",i,j);

getch();
}
Prints the value of i and j as it goes through the loop.
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 0)
(1, 1)
(1, 2)
(1, 3)
(1, 4)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 0)
(3, 1)
(3, 2)
(3, 3)
(3, 4)
(4, 0)
(4, 1)
(4, 2)
(4, 3)
(4, 4)
Now for your assignment:

A. Create a program that uses a for loop that doubles the value of i starting from 1
to 1024. The output should be 1 2 4 8 16 32 64 ... 1024.
B. Create a program that allows the user to input a number and find its factorial.
Use float instead of int since you will be getting large number.
C. Create a program that uses a nested for loop to simulate counting in 4-bit
binary.
See what I did for A, B or C.

Click on A, B or C to see the code.

Hover over A, B or C to see the output.

Wasn't that easy and fun? Next we'll discuss the other loops.

For loop is great for loops that you know how many times to loop. The others are
good for if you don't know or don't need to know how many the program goes to the
loop for example when a user want to continue or to quit when they are prompted.
There is no need for a counter.
The syntax:
while (condion)
{
statement 1
statement 2
}

do
{
statement 1
statement 2
} while (condition)

Simple as that. Now here is an example for a while loop.

#include<stdio.h>
#include<conio.h>

char yorn;

void main()
{
clrscr();
printf("Do you want to go through the loop? (y or n):");
yorn=getch();
printf("%c", yorn);
while (yorn=='y')
{
printf("\nDo you still want to go through the loop? (y or n):");
yorn=getch();
}
getch();
}
And for a do while loop
#include<stdio.h>
#include<conio.h>

char yorn;

void main()
{
clrscr();
do {
printf("\nDo you want to go through the loop? (y or n):");
yorn=getch();
printf("%c", yorn);
} while (yorn=='y');
getch();
}

It's not that hard to figure out. Next is we move on to Arrays.

Arrays is like a numbered list. It has an address, which is a whole number, and data
that correspond with the address of the array. It is declared with variables.

Declarations:
int arr[size];
char arr[size][charlenght];

Basically you just put the size of the array in brackets after the name of the variable.

#include<stdio.h>
#include<conio.h>
#include<string.h>
#define max 5

char fruits[max][8];
void main()
{
clrscr();
strcpy(fruits[0], "Apple");
strcpy(fruits[1], "Orange");
strcpy(fruits[2], "Banana");
strcpy(fruits[3], "Grapes");
strcpy(fruits[4], "Mango");
for (int i=0; i<max; i++) printf("%s\n", fruits[i]);
getch();
}
Apple
Orange
Banana
Grapes
Mango
Fruits
Apple Orange Banana Grapes Mango
0 1 2 3 4

Arrays and for loop go together like a list and counting numbers. Array of words is a
bit complicated with C as you can see, since strings are treated like an array of
character, and array of words would be like a two-dimensional array of strings, but it
still works. Array of numbers are much easier.

Here's another example with arrays of numbers:

#include<stdio.h>
#include<conio.h>
#define max 5

int num[max], i, sum=0;

void main()
{
clrscr();
printf("Enter %d numbers: ", max);
for (i=0; i<max; i++) scanf("%d", &num[i]);
for (i=0; i<max; i++) sum+=num[i];
printf("%d\n", sum);
getch();
}
Now your turn. Edit the code above to include the average and the product of the
numbers inputed. What do you do if you want to change how many numbers can be
inputed, let say 10, instead of 5?

Click here to see what I did.

For the final lesson we'll discuss funcions. On other programming language they are
called procedures. There are some codes that might get used more than others.
Functions makes it easier to get to the code. Functions separate certain functions into
its own self contained mini-program. For example the Input Processing and Output
function of the program can be separated into different functions. This leaves the main
function smaller and less cluttered.

The syntax:
(No return value.)

void functionname()
{
statement 1;
statement 2;
}

(With return value.)

int functionname(int num)


{
statement1;
statement2;
return(num);
}

Now here's an example:


#include<stdio.h>
#include<conio.h>

int num1, num2;

void input() {
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);}

int sum(int x, int y) {return(x+y);}

void output() {printf("%d + %d = %d", num1, num2, sum(num1,num2));}


void main()
{
clrscr();
input();
output();
getch();
}

Notice how the main function is at the bottom and it calls the input and output
function above. The output function calls the sum function. We'll that's the end of my
tutorial, it's not comprehensive by all means but should help you get started.

Вам также может понравиться