C Tutorial
C Tutorial Learn C with our popular C tutorial, which will take you from the very basics of C all the way through sophisticated topics like binary trees and data structures. By the way, if you’re on the fence about learning C or C++, I recommend going through the C++ tutorial instead as it is a more modern language.
Introduction and Basic C Features
- Introduce to C
- If statements
- Loops in C
- Functions and Program Organization
- Switch case
Pointers, Arrays and Strings
- Pointers
- Structures
- Arrays
- C-style Strings
File IO and command line arguments
- C File I/O
- Typecasting
- Command line arguments
Linked lists, binary trees, recursion
- Linked Lists
- Recursion
- Variable argument lists
- Binary Trees
Lesson 1:
Introduce to C
Every full C program begins inside a function called “main”. A function is simply a collection of commands that do “something”. The main function is always called when the program first executes. , you need to include a header with the #include directive.. Let’s look at a working program:
#include <stdio.h>
int main()
{
printf( “BISMILLAHIR-RAHMANIR RAHIMn” );
getchar();
return 0;
}
Let’s look at the elements of the program.
** The #include is a “preprocessor” directive that tells the compiler to put code from the header called stdio.h into our program before actually creating the executable.
** you can gain access to many different functions–both the printf and getchar functions are included in stdio.h.
**The semicolon is part of the syntax of C. It tells the compiler that you’re at the end of a command.
**The next important line is int main(). This line tells the compiler that there is a function named main
** The “curly braces” ({ and }) signal the beginning and end of functions and other code blocks
** The printf function is the standard C way of displaying output on the screen.
** The ‘n’ sequence is actually treated as a single character that stands for a newline. The actual effect of ‘n’ is to move the cursor on your screen to the next line. Again, notice the semicolon: it is added onto the end of all lines, such as function calls, in C.
** “getchar()” is another function call: it reads in a single character and waits for the user to hit enter before reading the character. This line is included because many compiler environments will open a new console window, run the program, and then close the window before you can see the output. This command keeps that window from closing because the program is not done yet because it waits for you to hit enter. Including that line gives you time to see the program run.
** Finally, at the end of the program, we return a value from main to the operating system by using the return statement. This return value is important as it can be used to tell the operating system whether our program succeeded or not. A return value of 0 means success.
The final brace closes off the function. You should try compiling this program and running it. You can cut and paste the code into a file, save it as a .c file, and then compile it. If you are using a command-line compiler, such as Borland C++ 5.5, you should read the compiler instructions for information on how to compile. Otherwise compiling and running should be as simple as clicking a button with your mouse (perhaps the “build” or “run” button).
You might start playing around with the printf function and get used to writing simple C programs.
Explaining your Code: Comments are critical for all but the most trivial programs and this tutorial will often use them to explain sections of code. When you tell the compiler a section of text is a comment, it will ignore it when running the code, allowing you to use any text you want to describe the real code. To create a comment in C, you surround the text with /* and then */ to block off everything between as a comment. Certain compiler environments or text editors will change the color of a commented area to make it easier to spot, but some will not. Be certain not to accidentally comment out code (that is, to tell the compiler part of your code is a comment) you need for the program.
When you are learning to program, it is also useful to comment out sections of code in order to see how the output is affected.
Using Variables: So far you should be able to write a simple program to display information typed in by you, the programmer and to describe your program with comments. That’s great, but what about interacting with your user? Fortunately, it is also possible for your program to accept input.
But first, before you try to receive input, you must have a place to store that input. In programming, input and data are stored in variables. There are several different types of variables; when you tell the compiler you are declaring a variable, you must include the data type along with the name of the variable. Several basic types include char, int, and float. Each type can store different types of data.
Variables type
Descriptions
Int
integers (numbers without decimal places) .example: int x , a, b, c, d(1,23,4,56 etc);
Char
a single character. example: char letter(rahim ,cat etc);
float
numbers with decimal places. example: float the float(3.22,2.1,etc);
Wrong
#include <stdio.h>
int main()
{
/* wrong! The variable declaration must appear first */
printf( “Declare x next” );
int x;
return 0;
}
Fixed
#include <stdio.h>
int main()
{
int x;
printf( “Declare x first” );
return 0;
}
Reading input: Using variables in C for input or output can be a bit of a hassle at first, but bear with it and it will make sense. We’ll be using the scanf function to read in a value and then printf to read it back out. Let’s look at the program and then pick apart exactly what’s going on. You can even compile this and run it if it helps you follow along.
#include <stdio.h>
int main()
{
int this_is_a_number;
printf( “Please enter a number: ” );
scanf( “%d”, &this_is_a_number );
printf( “You entered %d”, this_is_a_number );
getchar();
return 0;
}
So what does all of this mean? We’ve seen the #include and main function before; main must appear in every program you intend to run, and the #include gives us access to printf (as well as scanf). (As you might have guessed, the io in stdio.h stands for “input/output”; std just stands for “standard.”) The keyword int declares this _ is _a _number to be an integer.
This is where things start to get interesting: the scanf function works by taking a string and some variables modified with &. The string tells scanf what variables to look for: notice that we have a string containing only “%d” — this tells the scanf function to read in an integer. The second argument of scanf is the variable, sort of. We’ll learn more about what is going on
later, but the gist of it is that scanf needs to know where the variable is stored in order to change its value. Using & in front of a variable allows you to get its location and give that to scanf instead of the value of the variable. Think of it like giving someone directions to the soda aisle and letting them go get a coca-cola instead of fetching the coke for that person. The & gives the scanf function directions to the variable.
When the program runs, each call to scanf checks its own input string to see what kinds of input to expect, and then stores the value input into the variable.
So what does it mean to treat a number as an integer?
If the user attempts to type in a decimal number, it will be truncated (that is, the decimal component of the number will be ignored) when stored in the variable. Try typing in a sequence of characters or a decimal number when you run the example program; the response will vary from input to input, but in no case is it particularly pretty.
Several operators used with variables include the following: *, -, +, /, =, ==, >, <. The * multiplies, the / divides, the – subtracts, and the + adds. It is of course important to realize that to modify the value of a variable inside the program it is rather important to use the equal sign. In some languages, the equal sign compares the value of the left and right values, but in C == is used for that task. The equal sign is still extremely useful. It sets the value of the variable on the left side of the equals sign equal to the value on the right side of the equals sign. The operators that perform mathematical functions should be used on the right side of an equal sign in order to assign the result to a variable on the left side.
Here are a few examples:
a = 4 * 6; /* (Note use of comments and of semicolon) a is 24 */
a = a + 5; /* a equals the original value of a with five added to it */
a == 5 /* Does NOT assign five to a. Rather, it checks to see if a equals 5.*/
The other form of equal, ==, is not a way to assign a value to a variable. Rather, it checks to see if the variables are equal. It is extremely useful in many areas of C; for example, you will often use == in such constructions as conditional statements and loops. You can probably guess how < and > function. They are greater than and less than operators.
For example:
a < 5 /* Checks to see if a is less than five */
a > 5 /* Checks to see if a is greater than five */
a == 5 /* Checks to see if a equals five, for good measure */
Quiz: The basics of C 1. What is the correct value to return to the operating system upon the successful completion of a program?
A. -1
B. 1
C. 0
D. Programs do not return a value.
2. What is the only function all C programs must contain?
A. start()
B. system()
C. main()
D. program()
3. What punctuation is used to signal the beginning and end of code blocks?
A. { }
B. -> and <-
C. BEGIN and END
D. ( and )
4. What punctuation ends most lines of C code?
A. .
B. ;
C. :
D. ‘
5. Which of the following is a correct comment?
A. */ Comments */
B. ** Comment **
C. /* Comment */
D. { Comment }
6. Which of the following is not a correct variable type?
A. float
B. real
C. int
D. double
7. Which of the following is the correct operator to compare two variables?
A. :=
B. =
C. equal
D. ==
ANSWER: 1. c; 2. c; 3. a; 4. b; 5. c; 6. b; 7. d;
** Finally, at the end of the program, we return a value from main to the operating system by using the return statement. This return value is important as it can be used to tell the operating system whether our program succeeded or not. A return value of 0 means success.
}
A. -1
B. 1
C. 0
D. Programs do not return a value.