Cprogramming Notes
Cprogramming Notes
C is a programming language which born at “AT & T‟s Bell Laboratories” of USA in 1972. It
was written by Dennis Ritchie. This language was created for a specific purpose: to design the
UNIX operating system (which is used on many computers). From the beginning, C was
intended to be useful--to allow busy programmers to get things done. Because C is such a
powerful, dominant and supple language, its use quickly spread beyond Bell Labs. In the late
70‟s C began to replace widespread well-known languages of that time like PL/I, ALGOL etc.
Programmers everywhere began using it to write all sorts of programs. Soon, however, different
organizations began applying their own versions of C with a subtle difference. This posed a
serious problem for system developers. To solve this problem, the American National Standards
Institute (ANSI) formed a committee in 1983 to establish a standard definition of C. This
committee approved a version of C in 1989 which is known as ANSI C. With few exceptions,
every modern C compiler has the ability to adhere to this standard. ANSI C was then approved
by the International Standards Organization (ISO) in 1990. Now, what about the name? Why it
was named C, why not something else. The C language is so named because its predecessor was
called B. The B language was developed by Ken Thompson of Bell Labs.
Why C?
In today's world of computer programming, there are many high-level languages to choose from,
such as Pascal, BASIC, and Java. But C stands apart from all these languages. This is due to its
many desirable qualities. It is a robust language whose rich set of built-in functions and operators
can be used to write any complex logic program. The C language compiler combines the
capabilities of a low level language with the features of a high level language. Therefore the
language is suitable for writing both system software as well as business packages & other
software. You will see many compilers available in the market written in C.
Features of C
• C is a powerful and flexible language which helps system developers to deliver various
complex tasks with ease. C is used for diverse projects as operating systems, word processors,
graphics, spreadsheets, and even compilers for other languages.
• C is highly portable language. This means that a C program written for one computer system
(an IBM PC, for example) can be run on another system (a DEC VAX system, perhaps) with
little or no modification. Portability is enhanced by the ANSI standard for C, the set of rules for
C compilers.
1
C Programming Basics
• C‟s another striking feature is its ability to extend itself. A C program is basically a collection
of various function supported by C library (also known as header files). We can also add our own
functions to the C library. These functions can be reused in other applications or programs by
passing pieces of information to the functions, you can create useful, reusable code. • Writing C
program with user-defined functions makes program more simple and easy to understand.
Breaking a problem in terms of functions makes program debugging, maintenance and testing
easier.
Communicating with a computer involves speaking the language the computer understands,
which immediately rules out English as the language of communication with computer.
However, there is a close analogy between learning English language and learning C language.
The classical method of learning English is to first learn the alphabets used in the language, then
learn to combine these alphabets to form words, which in turn are combined to form sentences
and sentences are combined to form paragraphs. Learning C is similar and easier. Instead of
straight-away learning how to write programs, we must first know what alphabets, numbers and
special symbols are used in C, then how using them constants, variables and keywords are
constructed, and finally how are these combined to form an instruction. A group of instructions
would be combined later on to form a program. This is illustrated in the Figure 1.
Figure 1
2
C Programming Basics
A character denotes any alphabet, digit or special symbol used to represent information. Figure 2
shows the valid alphabets, numbers and special symbols allowed in C.
Figure 2
The alphabets, numbers and special symbols when properly combined form constants, variables
and keywords. Let us see what are „constants‟ and „variables‟ in C. A constant is an entity that
doesn‟t change whereas a variable is an entity that may change.
In any program we typically do lots of calculations. The results of these calculations are stored in
computers memory. Like human memory the computer memory also consists of millions of
cells. The calculated values are stored in these memory cells. To make the retrieval and usage of
these values easy these memory cells (also called memory locations) are given names. Since the
value stored in each location may change the names given to these locations are called variable
names. Consider the following example.
Here 3 is stored in a memory location and a name x is given to it. Then we are assigning a new
value 5 to the same memory location x. This would overwrite the earlier value 3, since a memory
location can hold only one value at a time. This is shown in Figure 3.
3
C Programming Basics
Figure 3
Since the location whose name is x can hold different values at different times x is known as a
variable. As against this, 3 or 5 do not change, hence are known as constants.
Types of C Constants
Figure 4
4
C Programming Basics
At this stage we would restrict our discussion to only Primary Constants, namely, Integer, Real
and Character constants. Let us see the details of each of these constants. For constructing these
different types of constants certain rules have been laid down. These rules are as under:
Truly speaking the range of an Integer constant depends upon the compiler. For a 16-bit compiler
like Turbo C or Turbo C++ the range is –32768 to 32767. For a 32-bit compiler the range would
be even greater. Question like what exactly do you mean by a 16- bit or a 32-bit compiler, what
range of an Integer constant has to do with the type of compiler and such questions are discussed
in detail in Chapter 16. Till that time it would be assumed that we are working with a 16-bit
compiler. Example: 426, +782, -8000, -7605
Variable in C
Variable represent some segment of memory location in a computer. Different values placed in
the storage depend on the value type. Variable should be declared prior to storage of any values.
When declaring variable in C rules must be followed. Such as:
5
C Programming Basics
Figure 5
Create a variable called myNum of type int and assign the value 15 to it:
You can also declare a variable without assigning the value, and assign the value later:
// Declare a variable
int myNum;
Data type is some reserve words used to specify the values whether they are integral, real,
character, etc. Different storage space would be allocated depends on the data type.
Declaration is the process of reserving storage area in order to store different values temporary.
Whenever we use a value or variable, we will declare it and its data type. Variables must be
explicitly declared before they are used. Each declaration statement in C language must be end
with semicolon. There are various ways of declaring a variables, and following are some variable
declaration.
int GrossPay;
6
C Programming Basics
int NetPay = 0;
Writing a C Program
Stages of Compilation
1) Preprocessing
Performed by a program called the preprocessor
Modifies the source code (in RAM) according to preprocessor directives
(preprocessor commands) embedded in the source code
Strips comments and white space from the code
The source code as stored on disk is not modified.
2) Compilation
Performed by a program called the compiler
Translates the preprocessor-modified source code into object code (machine code)
Checks for syntax errors and warnings
Saves the object code to a disk file, if instructed to do so (we will not do this).
o If any compiler errors are received, no object code file will be generated
o An object code file will be generated if only warnings, not errors, are
received.
3) Linking
Combines the program object code with other object code to produce the
executable file.
The other object code can come from the Run-Time Library, other libraries, or
object files that you have created.
Saves the executable code to a disk file. On the Linux system, that file is called
a.out.
o If any linker errors are received, no executable file will be
generated.
7
C Programming Basics
Simple C Program
#include <stdio.h>
return 0 ;
Anatomy of C language
statement(s)
return 0 ;
A comment is descriptive text used to help a reader of the program understand its content
All comments must begin with the characters /* and end with the characters */
These are called comment delimiters
The program header comment always comes first
8
C Programming Basics
Stdio.h
When we write our programs, there are libraries of functions to help us so that we do
not have to write the same code over and over.
Some of the functions are very complex and long. Not having to write them ourselves
make it easier and faster to write programs.
Using the functions will also make it easier to learn to program!
Every program must have a function called main. This is where program execution
begins.
main() is placed in the source code file as the first function for readability. There must be
a function with this name or the program can not successful compile.
The reserved word “int” indicates that main() returns an integer value.
The parentheses following the reserved word “main” indicate that it is a function
The reserved word “void” means nothing is there.
A left brace (curly bracket) -- { -- begins the body of every function. A corresponding
right brace -- } -- ends the function body
The style is to place these braces on separate lines and to indent the entire function body.
return 0;
Because function main() returns an integer value, there must be a statement that indicates
what this value is.
The statement
return o;
indicates that main() returns a value of zero to the operating system.
A value of 0 indicates that the program successfully terminated execution.
Do not worry about this concept now. Just remember to use the statement.
9
C Programming Basics
Input
The input in C enables users to enter values for e.g. data entry. The function enables programmer
to prompt for data entry during program execution. Appropriate Conversion Codes should be
specified in order to display the required value. You have already learned that printf() is used
to output values in C. To get user input, you can use the scanf() function:
#include <stdio.h>
int main() {
// Create an integer variable that will store the number we get from the user
int myNum;
return 0;
}
The scanf() function takes two arguments: the format specifier of the variable (%d in the
example above) and the reference operator (&myNum), which stores the memory address of the
variable.
Multiple Inputs
The scanf() function also allow multiple inputs (an integer and a character in the following
example):
#include <stdio.h>
int main() {
int myNum;
char myChar;
10
C Programming Basics
// Get and save the number AND character the user types
return 0;
#include <stdio.h>
int main() {
// Create a string
char firstName[30];
scanf("%s", firstName);
return 0;
11
C Programming Basics
Note: When working with strings in scanf(), you must specify the size of the string/array (we
used a very high number, 30 in our example, but atleast then we are certain it will store enough
characters for the first name), and you don't have to use the reference operator (&).
However, the scanf() function has some limitations: it considers space (whitespace, tabs, etc) as a
terminating character, which means that it can only display a single word (even if you type many
words). For example:
char fullName[30];
scanf("%s", &fullName);
// Hello Usman
From the example above, you would expect the program to print "Usman Idris", but it only prints
"Usman".
That's why, when working with strings, we often use the fgets() function to read a line of text.
Note that you must include the follow arguments: the name of the string variable,
Use the scanf() function to get a single word as input, and use fgets() for multiple words.
Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
12
C Programming Basics
printf("%d", myNum);
return 0;
}
Although the + operator is often used to add together two values, like in the example above, it
can also be used to add together a variable and a value, or a variable and another variable:
#include <stdio.h>
int main() {
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
printf("%d\n", sum1);
printf("%d\n", sum2);
printf("%d\n", sum3);
return 0;
}
C Divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
13
C Programming Basics
Example:
#include <stdio.h>
int main() {
int x = 5;
int y = 3;
printf("%d", x + y);
return 0;
}
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
The addition assignment operator (+=) adds a value to a variable:
Example:
#include <stdio.h>
int main() {
int x = 10;
x += 5;
printf("%d", x);
return 0;
}
Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in
programming, because it helps us to find answers and make decisions.
The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values
are known as Boolean values, and you will learn more about them in
the Booleans and If..Else lectures
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:
#include <stdio.h>
int main() {
int x = 5;
14
C Programming Basics
int y = 3;
return 0;
}
A list of all comparison operators:
== Equal x==y
Logical Operators
You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values:
#include <stdio.h>
int main() {
int x = 5;
int y = 3;
15
C Programming Basics
return 0;
Example: Logical or
#include <stdio.h>
int main() {
int x = 5;
int y = 3;
// Returns 1 (true) because one of the conditions are true (5 is greater than 3, but 5 is not less
than 4)
return 0;
#include <stdio.h>
int main() {
int x = 5;
int y = 3;
return 0;
16
C Programming Basics
Booleans
Very often, in programming, you will need a data type that can only have one of two values, like:
YES / NO
ON / OFF
TRUE / FALSE
Booleans Variable:
In C, the bool type is not a built-in data type, like int or char.
It was introduced in C99, and you must import the following header file to use it:
#include <stdbool.h>
A boolean variable is declared with the bool keyword and can only take the values true or false:
Before trying to print the boolean variables, you should know that boolean values are returned as
integers:
0 represents false
Example:
#include <stdio.h>
int main() {
return 0;
17
C Programming Basics
The if Statement
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18. If the condition is
true, print some text:
Example:
#include <stdio.h>
int main() {
return 0;
Example:
#include <stdio.h>
int main() {
18
C Programming Basics
int x = 20;
int y = 18;
if (x > y) {
return 0;
Use the else statement to specify a block of code to be executed if the condition is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example:
#include <stdio.h>
int main() {
printf("Good day.");
else {
printf("Good evening.");
19
C Programming Basics
return 0;
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example:
#include <stdio.h>
int main() {
printf("Good morning.");
printf("Good day.");
} else {
printf("Good evening.");
return 0;
20
C Programming Basics
Switch Statement
Instead of writing many if..else statements, you can use the switch statement.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The example below uses the weekday number to calculate the weekday name:
Example:
#include <stdio.h>
int main() {
int day = 4;
switch (day) {
case 1:
printf("Monday");
break;
21
C Programming Basics
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
return 0;
22
C Programming Basics
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for more
testing.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the
code in the switch block.
#include <stdio.h>
int main() {
int day = 4;
switch (day) {
case 6:
printf("Today is Saturday");
break;
case 7:
printf("Today is Sunday");
break;
default:
return 0;
23
C Programming Basics
Note: The default keyword must be used as the last statement in the switch, and it does not need
a break.
s
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.
The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition) {
// code block to be executed
}
Example:
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
return 0;
}
Note: Do not forget to increase the variable used in the condition (i++), otherwise the loop will
never end!
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax
Do{
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once, even if
the condition is false, because the code block is executed before the condition is tested:
#include <stdio.h>
int main() {
int i = 0;
do {
24
C Programming Basics
printf("%d\n", i);
i++;
}
while (i < 5);
return 0;
}
For Loop
When you know exactly how many times you want to loop through a block of code, use the for
loop instead of a while loop:
Syntax:
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example:
#include <stdio.h>
int main() {
int i;
printf("%d\n", i);
}
return 0;
}
#include <stdio.h>
int main() {
int i;
for (i = 0; i <= 10; i = i + 2) {
printf("%d\n", i);
}
return 0;
}
26