C Programming Tutorial: Introduction To C Programming (For Novices & First-Time Programmers)
C Programming Tutorial: Introduction To C Programming (For Novices & First-Time Programmers)
C Programming Tutorial: Introduction To C Programming (For Novices & First-Time Programmers)
| HOME
TABLE OF CONTENTS (HIDE)
1. Getting Started - Write your First Hello-world C Program
2. C Terminology and Syntax
3. The Process of Writing a C Program
4. C Program Template
5. Let's Write a Program to Add a Few Numbers
5.1 Example: Adding Two Integers
5.2 Example: Prompting User for Inputs
6. What is a Program?
7. What is a Variable?
8. Basic Arithmetic Operations
9. What If Your Need To Add a Thousand Numbers? Use a Loop!
10. Conditional (or Decision)
11. Type double & Floating-Point Numbers
12. Mixing int and double, and Type Casting
13. Summary
C programming Tutorial
Introduction to C Programming
(for Novices & First-Time
Programmers)
1. Getting Started - Write your First Hello-world C
Program
Let's begin by writing our first C program that prints the message "Hello, world!" on the display
console:
Hello, world!
Step 1: Write the Source Code: Enter the following source codes using a programming text
editor (such as NotePad++ for Windows or gEdit for UNIX/Linux/Mac) or an Interactive Development
Environment (IDE) (such as CodeBlocks, Eclipse, NetBeans or MS Visual Studio - Read the respective
"How-To" article on how to install and get started with these IDEs).
Do not enter the line numbers (on the left panel), which were added to help in the explanation. Save
the source file as "Hello.c". A C source file should be saved with a file extension of " .c". You should
choose a filename which reflects the purpose of the program.
1/*
2 * First C program that says Hello (Hello.c)
3 */
4#include <stdio.h> // Needed to perform IO operations
5
6int main() { // Program entry point
7 printf("Hello, world!\n"); // Says Hello
8 return 0; // Terminate main()
9} // End of main()
Step 2: Build the Executable Code: Compile and Link (aka Build) the source code "Hello.c"
into executable code ("Hello.exe" in Windows or "Hello" in UNIX/Linux/Mac).
On IDE (such as CodeBlocks), push the "Build" button.
On Text editor with the GNU GCC compiler, start a CMD Shell (Windows) or Terminal (Mac, Linux)
and issue these commands:
// UNIX/Linux/Mac (Bash shell) - Run "Hello" (./ denotes the current directory)
$ ./Hello
Hello, world!
integer1 = 55;
integer2 = 66;
sum = integer1 + integer2;
We assign values to variables integer1 and integer2; compute their sum and store in variable sum.
printf("The sum of %d and %d is %d.\n", integer1, integer2, sum);
We use the printf() function to print the result. The first argument in printf() is known as
the formatting string, which consists of normal texts and so-called conversion specifiers. Normal texts
will be printed as they are. A conversion specifier begins with a percent sign (%), followed by a code to
indicate the data type, such as d for decimal integer. You can treat the %d as placeholders, which will
be replaced by the value of variables given after the formatting string in sequential order. That is, the
first %d will be replaced by the value of integer1, second %d by integer2, and third %d by sum.
The \n denotes a newline character. Printing a \n bring the cursor to the beginning of the next line.
5.2 Example: Prompting User for Inputs
In the previous example, we assigned fixed values into variables integer1 and integer2. Instead of
using fixed values, we shall prompt the user to enter two integers.
PromptAdd2Integers.c
1/*
2 * Prompt user for two integers and print their sum (PromptAdd2Integers.c)
3 */
4#include <stdio.h>
5
6int main() {
7 int integer1, integer2, sum; // Declare 3 integer variables
8
9 printf("Enter first integer: "); // Display a prompting message
10 scanf("%d", &integer1); // Read input from keyboard into integer1
11 printf("Enter second integer: "); // Display a prompting message
12 scanf("%d", &integer2); // Read input into integer2
13
14 sum = integer1 + integer2; // Compute the sum
15
16 // Print the result
17 printf("The sum of %d and %d is %d.\n", integer1, integer2, sum);
18
19 return 0;
20}
2. * * * * * * * * * * * * * * *
3. * * * * * * * * *
4. * * * * * * * * *
5. * * * * * * * * *
6. * * * * * * * * * * *
Example (Sequential): The following program (CircleComputation.c) prompts user for the
radius of a circle, and prints its area and circumference. Take note that the programming statements
are executed sequentially - one after another in the order that they are written.
1/*
2 * Prompt user for the radius of a circle and compute its area and circumference
3 * (CircleComputation.c)
4 */
5#include <stdio.h>
6
7int main() {
8 double radius, circumference, area; // Declare 3 floating-point variables
9 double pi = 3.14159265; // Declare and define PI
10
11 printf("Enter the radius: "); // Prompting message
12 scanf("%lf", &radius); // Read input into variable radius
13
14 // Compute area and circumference
15 area = radius * radius * pi;
16 circumference = 2.0 * radius * pi;
17
18 // Print the results
19 printf("The radius is %lf.\n", radius);
20 printf("The area is %lf.\n", area);
21 printf("The circumference is %lf.\n", circumference);
22
23 return 0;
24}
Take note that the programming statements inside the main() are executed one after another,
sequentially.
Exercises
1. Follow the above example, write a program to print the area and perimeter of a rectangle. Your
program shall prompt the user for the length and width of the rectangle, in doubles.
2. Follow the above example, write a program to print the surface area and volume of a cylinder.
Your program shall prompt the user for the radius and height of the cylinder, in doubles.
7. What is a Variable?
Computer programs manipulate (or process) data. A variable is used to store a piece of data for
processing. It is called variablebecause you can change the value stored.
More precisely, a variable is a named storage location, that stores a value of a particular data type. In
other words, a variable has a name, a type and stores a value of that type.
A variable has a name (or identifier), e.g., radius, area, age, height. The name is needed to
uniquely identify and reference a variable, so as to assign a value to the variable (e.g., radius=1.2),
and retrieve the value stored (e.g., area = radius*radius*pi).
A variable has a type. Examples of type are:
o int: for integers (whole numbers) such as 123 and -456;
o double: for floating-point or real numbers, such as 3.1416, -55.66, 7.8e9, 1.2e3, -4.5e-
6 having a decimal point and fractional part, in fixed or scientific notations.
A variable can store a value of the declared type. It is important to take note that a variable is
associated with a type, and can only store value of that particular type. For example, a int variable
can store an integer value such as 123, but NOT real number such as 12.34, nor texts such
as "Hello". The concept of type was introduced into the early programming languages to simplify
interpretation of data.
The above diagram illustrates 2 types of variables: int and double. An int variable stores an integer
(whole number). A double variable stores a real number.
To use a variable, you need to first declare its name and type, in one of the following syntaxes:
var-type var-name; // Declare a variable of a type
var-type var-name-1, var-name-2,...; // Declare multiple variables of the same type
var-type var-name = initial-value; // Declare a variable of a type, and assign an
initial value
var-type var-name-1 = initial-value-1, var-name-2 = initial-value-2,... ; // Declare
variables with initial values
For example,
int sum; // Declare a variable named "sum" of the type "int" for storing
an integer.
// Terminate the statement with a semi-colon.
int number1, number2; // Declare two "int" variables named "number1" and "number2",
// separated by a comma.
double average; // Declare a variable named "average" of the type "double" for
storing a real number.
int height = 20; // Declare an int variable, and assign an initial value.
Once a variable is declared, you can assign and re-assign a value to a variable, via the assignment
operator "=". For example,
int number; // Declare a variable named "number" of the type "int" (integer)
number = 99; // Assign an integer value of 99 to the variable "number"
number = 88; // Re-assign a value of 88 to "number"
number = number + 1; // Evaluate "number + 1", and assign the result back to "number"
int sum = 0; // Declare an int variable named sum and assign an initial value
of 0
sum = sum + number; // Evaluate "sum + number", and assign the result back to "sum",
i.e. add number into sum
int num1 = 5, num2 = 6; // Declare and initialize two int variables in one statement,
separated by a comma
double radius = 1.5; // Declare a variable name radius, and initialize to 1.5
int number; // ERROR: A variable named "number" has already been declared
sum = 55.66; // WARNING: The variable "sum" is an int. It shall not be assigned
a floating-point number
sum = "Hello"; // ERROR: The variable "sum" is an int. It cannot be assigned a
text string
For examples:
Exercises
1. Write a program to sum all the integers between 1 and 1000, that are divisible by 13, 15 or 17,
but not by 30.
2. Write a program to print all the leap years between AD1 and AD2010, and also print the number
of leap years. (Hints: use a variable called count, which is initialized to zero. Increment
the countwhenever a leap year is found.)
11. Type double & Floating-Point Numbers
Recall that a variable in C has a name and a type, and can hold a value of only that particular type. We
have so far used a type called int. A int variable holds only integers (whole numbers), such
as 123 and -456.
In programming, real numbers such as 3.1416 and -55.66 are called floating-point numbers, and
belong to a type called double. You can express floating-point numbers in fixed notation (e.g., 1.23, -
4.5) or scientific notation (e.g., 1.2e3, -4E5.6) where e or E denote the exponent of base 10.
Example
1/*
2 * Convert temperature between Celsius and Fahrenheit
3 * (ConvertTemperature.c)
4 */
5#include <stdio.h>
6
7int main() {
8 double celsius, fahrenheit;
9
10 printf("Enter the temperature in celsius: ");
11 scanf("%lf", &celsius); // Use %lf to read an double
12 fahrenheit = celsius * 9.0 / 5.0 + 32.0;
13 printf("%.2lf degree C is %.2lf degree F.\n\n", celsius, fahrenheit);
14 // %.2lf prints a double with 2 decimal places
15
16 printf("Enter the temperature in fahrenheit: ");
17 scanf("%lf", &fahrenheit);
18 celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
19 printf("%.2lf degree F is %.2lf degree C.\n\n", fahrenheit, celsius);
20
21 return 0;
22}
int i = 3;
double d;
d = i; // 3 3.0, d = 3.0
d = 88; // 88 88.0, d = 88.0
double nought = 0; // 0 0.0; there is a subtle difference between int of 0 and
double of 0.0
However, if you assign a double value to an int variable, the fractional part will be lost. For example,
double d = 55.66;
int i;
i = d; // i = 55 (truncated)
Some C compilers signal a warning for truncation, while others do not. You should study the "warning
messages" (if any) carefully - which signals a potential problem in your program, and rewrite the
program if necessary. C allows you to ignore the warning and run the program. But, the fractional part
will be lost during the execution.
Type Casting Operators
If you are certain that you wish to carry out the type conversion, you could use the so-called type
cast operator. The type cast operation returns an equivalent value in the new-type specified.
(new-type)expression;
For example,
double d = 5.5;
int i;
i = (int)d; // (int)d -> (int)5.5 -> 5
i = (int)3.1416; // 3
Similarly, you can explicitly convert an int value to double by invoking type-casting operation too.
Example
Try the following program and explain the outputs produced:
1/*
2 * Testing type cast (TestCastingAverage.c)
3 */
4#include <stdio.h>
5
6int main() {
7 int sum = 0; // Sum in "int"
8 double average; // average in "double"
9
10 // Compute the sum from 1 to 100 (in "int")
11 int number = 1;
12 while (number <= 100) {
13 sum = sum + number;
14 ++number;
15 }
16 printf("The sum is %d.\n", sum);
17
18 // Compute the average (in "double")
19 average = sum / 100;
20 printf("Average 1 is %lf.\n", average);
21 average = (double)sum / 100;
22 printf("Average 2 is %lf.\n", average);
23 average = sum / 100.0;
24 printf("Average 3 is %lf.\n", average);
25 average = (double)(sum / 100);
26 printf("Average 4 is %lf.\n", average);
27
28 return 0;
29}
}
22. Write a program called GeometricSeriesSum to compute the sum of a geometric series 1 + 1/2
+ 1/4 + 1/8 + .... + 1/n. You program shall prompt for the value of n. (Hints: Use post-
processing statement of denominator = denominator * 2 .)
13. Summary
I have presented the basics for you to get start in programming. To learn programming, you need to
understand the syntaxes and features involved in the programming language that you chosen, and
you have to practice, practice and practice, on as many problems as you could.