1 Introduction
1 Introduction
1 Introduction
PROGRAMMING
• C is a general-purpose programming language created by Dennis Ritchie at the
Bell Laboratories in 1972.
• It is a very popular language, despite being old. The main reason for its popularity
is because it is a fundamental language in the field of computer science.
• C is strongly associated with UNIX, as it was developed to write the UNIX
operating system.
Why Learn C?
• It is one of the most popular programming languages in the world
• If you know C, you will have no problem learning other popular programming
languages such as Java, Python, C++, C#, etc, as the syntax is similar
• C is very fast, compared to other programming languages, like Java and Python
• C is very versatile; it can be used in both applications and technologies
Difference between C and C++
• C++ was developed as an extension of C, and both languages have almost the
same syntax
• The main difference between C and C++ is that C++ support classes and objects,
while C does not
To start using C, you need two things:
• A text editor, like Notepad, to write C code
• A compiler, like GCC, to translate the C code into a language that the computer
will understand
• There are many text editors and compilers to choose from.
C Install IDE
• An IDE (Integrated Development Environment) is used to edit AND compile the
code.
• Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free,
and they can be used to both edit and debug C code.
Characteristics of C
• A high level programming language.
• Small size. C has only 32 keywords. This makes it relatively easy to learn.
• Makes extensive use of function calls.
• C is well suited for structured programming.
• Stable and Quick language.
• Facilitates low level (bitwise) programming.
• Supports pointers to refer computer memory, array, structures and functions.
• C is a core language.
• C is a portable language.
• C is an extensible language.
Structure of C Program: Example
Example explained
• Line 1: #include <stdio.h> is a header file library that lets us work with input and output
functions, such as printf() (used in line 4). Header files add functionality to C programs
• Line 2: A blank line. C ignores white space. But we use it to make the code more readable.
• Line 3: Another thing that always appear in a C program is main(). This is called a function.
Any code inside its curly brackets {} will be executed.
• Line 4: printf() is a function used to output/print text to the screen. In our example, it will
output "Hello World!".
Note that: Every C statement ends with a semicolon ;
Note: The body of int main() could also been written as:
int main(){printf("Hello World!");return 0;}
• Remember: The compiler ignores white spaces. However, multiple lines makes the code
more readable.
• Line 5: return 0 ends the main() function.
• Line 6: Do not forget to add the closing curly bracket } to actually end the main function.
Statements
• A computer program is a list of "instructions" to be "executed" by a computer.
• In a programming language, these programming instructions are called statements.
• The following statement "instructs" the compiler to print the text "Hello World" to
the screen:
#include<stdio.h>
int main()
{
printf("\n Welcome to the world of C ");
return 0; // return value 0 to the operating system
}
14
Compiling and Executing C Program
Files used in a C Program
Files in a C
program
16
Files used in a C Program
Source code file
• The source code file contains the source code of the program.
• The file extension of any C source code file is “.c”.
• This file contains C source code that defines the main function and maybe other
functions.
• The main() is the starting point of execution when you successfully compile and
run the program.
17
Header Files
• Conventionally, header files names ends with a “.h” extension and its name can use
only letters, digits, dashes, and underscores.
• While some standard header files are available in C, but the programmer may also
create his own user defined header files.
• When working with large projects, it is often desirable to make sub-routines and
store them in a different file known as header file. The advantage of header files can
be realized when
a) The programmer wants to use the same subroutines in different programs.
b) The programmer wants to change, or add, subroutines, and have those changes
be reflected in all other programs.
18
Standard Header Files
19
Object Files
• generated by the compiler as a result of processing the source code file.
• Object files contain compact binary code of the function definitions.
• Object files have a “.o” extension, although some operating systems including
Windows and MS-DOS have a “.obj” extension for the object file.
20
Compiling and Executing C Program
Source File Pre- Compiler Object
process Files
Library Files
21
The compilation and execution process of C can be divided in to multiple steps:
23
C Tokens
C Tokens
• Tokens are building blocks in C language
• Smallest unit of C program
• Program is constructed using combination of tokens
• Six main types of tokens
1) Keywords
2) Variables
3) Constants
4) Strings
5) Special Character
6) Operators
26
Keywords
• C has a set of 32 reserved words often known as keywords.
• All keywords are basically a sequence of characters that have a fixed meaning.
• By convention all keywords must be written in lowercase (small) letters.
auto for while do break goto else if
27
Identifiers
• Identifiers are names given to program elements such as variables, arrays and
functions.
Rules for forming identifier name
it cannot include any special characters or punctuation marks (like #, $, ^, ?, ., etc)
except the underscore"_".
There cannot be two successive underscores.
Keywords cannot be used as identifiers.
The names are case sensitive. So, example, “FIRST” is different from “first” and “First”.
It must begin with an alphabet or an underscore.
It can be of any reasonable length. Though it should not contain more than 31
characters.
Example: roll_number, marks, name, emp_number, basic_pay, HRA, DA, dept_code
28
Variables in C
• A variable is defined as a meaningful name given to the data storage location in
computer memory.
• When using a variable, we actually refer to address of the memory where the data is
stored. C language supports two basic kinds of variables.
• Numeric variables can be used to store either integer values or floating point values.
• While an integer value is a whole numbers without a fraction part or decimal point, a
floating point number, can have a decimal point in them.
• Numeric values may also be associated with modifiers like short, long, signed and
unsigned. By default, C automatically takes a numeric variable signed.
• Character variables can include any letter from the alphabet or from the ASCII chart
and numbers 0 – 9 that are put between single quotes.
29
Variables in C
• To declare a variable specify data type of the variable followed by its name.
• Variable names should always be meaningful and must reflect the purpose of their
usage in the program.
• Variable declaration always ends with a semicolon. Example,
int emp_num;
Variables
float salary;
char grade;
double balance_amount;
unsigned short int acc_no;
Numeric Variable Character Variables
30
Data Types in C
31
Data Types in C
• In the table mentioned above, we have assumed a 16-bit compiler. It means that
the code generation of the compiler will be for a 16-bit target processor.
• The integer is, normally, the natural size for any processor or machine. In the
table mentioned above, the integer is 16-bit or 2 bytes wide. Thus, the compiler
is also 16-bit or 2 bytes wide.
• If the compiler was 32-bit wide, the int type size would have been about 32-bits
or 4 bytes. However, this might not be the case every single time. It is also
possible that the integer size is 32-bits or 4 bytes for a 64-bits processor.
• It entirely depends on the type of compiler.
32
Constants
• Constants are identifiers whose value does not change.
• Constants are used to define fixed values like PI or the charge on an electron so
that their value does not get changed in the program even by mistake.
• To declare a constant, precede the normal variable declaration with const
keyword and assign it a value. For example,
const float pi = 3.14;
• Another way to designate a constant is to use the pre-processor command
define.
#define PI 3.14159
When the preprocessor reformats the program to be compiled by the compiler,
it replaces each defined name with its corresponding value wherever it is found
in the source program. Hence, it just works like the Find and Replace command
available in a text editor.
33
Constants
Rules that needs to be applied to a #define statement which defines a constant.
34
Strings
• Strings are nothing but an array of characters ended with a null character (‘\0’).
• This null character indicates the end of the string. Strings are always enclosed in
double quotes.
• Whereas, a character is enclosed in single quotes in C and C++.
Examples of String
char string[10] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};
char string[10] = “hello”;
char string [] = “hello”;
Special Symbols
• The following special symbols are used in C having some special meaning and thus, cannot be used
for some other purpose. Some of these are listed below:
• Brackets[]: Opening and closing brackets are used as array element references. These indicate single
and multidimensional subscripts.
• Parentheses(): These special symbols are used to indicate function calls and function parameters.
• Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
• Comma (, ): It is used to separate more than one statement like for separating parameters in function
calls.
• Colon(:): It is an operator that essentially invokes something called an initialization list.
• Semicolon(;): It is known as a statement terminator. It indicates the end of one logical entity. That’s
why each individual statement must be ended with a semicolon.
• Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
• Assignment operator(=): It is used to assign values and for logical operation validation.
• Pre-processor (#): The preprocessor is a macro processor that is used automatically by the compiler
to transform your program before actual compilation.
• Period (.): Used to access members of a structure or union.
• Tilde(~): Used as a destructor to free some space from memory.
Operators
Operators
• Operators are symbols that trigger an action when applied to C variables and other
objects. The data items on which operators act are called operands.
Depending on the number of operands that an operator can act upon, operators
can be classified as follows:
• Unary Operators: Those operators that require only a single operand to act upon
are known as unary operators. For Example increment and decrement operators
• Binary Operators: Those operators that require two operands to act upon are called
binary operators. Binary operators can further are classified into:
Arithmetic operators
Relational Operators
Logical Operators
Assignment Operators
Bitwise Operator
• Ternary Operator: The operator that requires three operands to act upon is called
the ternary operator. Conditional Operator(?) is also called the ternary operator.
Arithmetic Operators
OPERATION OPERATOR SYNTAX COMMENT RESULT
Multiply * a*b result = a * b 27
Divide / a/b result = a / b 3
40
Logical Operators
• C language supports three logical operators. They are- Logical AND (&&),
Logical OR (||) and Logical NOT (!).
• As in case of arithmetic expressions, the logical expressions are evaluated
from left to right.
A B A &&B A B A || B A !A
0 0 0 0 0 0
0 1
0 1 0 0 1 1
1 0 0 1 0 1 1 0
1 1 1 1 1 1
Assignment Operators
• The assignment operator is responsible for assigning values to the variables. While the
equal sign (=) is the fundamental assignment operator, C also supports other assignment
operators that provide shorthand ways to represent common variable assignments. They
OPERATOR SYNTAX EQUIVALENT TO
are shown in the /=table. variable /= expression variable = variable / expression
\= variable \= expression variable = variable \ expression
*= variable *= expression variable = variable * expression
+= variable += expression variable = variable + expression
-= variable -= expression variable = variable - expression
&= variable &= expression variable = variable & expression
^= variable ^= expression variable = variable ^ expression
<<= variable <<= amount variable = variable << amount
>>= variable >>= amount variable = variable >> amount
42
Bitwise Operators
• Bitwise operators perform operations at bit level. These operators include: bitwise
AND, bitwise OR, bitwise XOR and shift operators.
• The bitwise AND operator (&) is a small version of the boolean AND (&&) as it
performs operation on bits instead of bytes, chars, integers, etc.
• The bitwise OR operator (|) is a small version of the boolean OR (||) as it performs
operation on bits instead of bytes, chars, integers, etc.
• The bitwise NOT (~), or complement, is a unary operation that performs logical
negation on each bit of the operand. By performing negation of each bit, it actually
produces the ones' complement of the given binary value.
• The bitwise XOR operator (^) performs operation on individual bits of the operands.
The result of XOR operation is shown in the table.
A B A^B
0 0 0
0 1 1
1 0 1
1 1 430
Equality Operators
• C language supports two kinds of equality operators to compare their
operands for strict equality or inequality. They are equal to (==) and not
equal to (!=) operator.
• The equality operators have lower precedence than the relational
operators.
OPERATOR MEANING
44
Unary Operators
• Unary operators act on single operands. C language supports three unary operators.
They are unary minus, increment and decrement operators.
• When an operand is preceded by a minus sign, the unary operator negates its value. The increment operator
is a unary operator that increases the value of its operand
by 1.
• Similarly, the decrement operator decreases the value of its operand by 1. For
example,
y = x++;
is equivalent to writing
y = x;
x = x + 1;
45
Conditional Operator
• The conditional operator (?:) is just like an if .. else statement that can be written within
expressions.
• The syntax of the conditional operator is
exp1 ? exp2 : exp3
Here, exp1 is evaluated first. If it is true then exp2 is evaluated and becomes the result of the
expression, otherwise exp3 is evaluated and becomes the result of the expression. For example,
large = ( a > b) ? a : b
• Conditional operator is also known as ternary operator as it is neither a unary nor a binary
operator; it takes three operands.
46
Bitwise Shift Operators
• In bitwise shift operations, the digits are moved, or shifted, to the left or right. The CPU registers
have a fixed number of available bits for storing numerals, so when we perform shift
operations; some bits will be "shifted out" of the register at one end, while the same number of
bits are "shifted in" from the other end.
• In a left arithmetic shift, zeros are shifted in on the right. For example;
unsigned int x = 11000101;
Then x << 2 = 00010100
47
Comma Operator
• The comma operator in C takes two operands. It works by evaluating the first and
discarding its value, and then evaluates the second and returns the value as the result
of the expression.
• Comma separated operands when chained together are evaluated in left-to-right
sequence with the right-most value yielding the result of the expression.
• Among all the operators, the comma operator has the lowest precedence. For
example,
int a=2, b=3, x=0;
x = (++a, b+=a);
Now, the value of x = 6.
48
Sizeof Operator
• sizeof is a unary operator used to calculate the sizes of data types.
• It can be applied to all data types.
• The operator returns the size of the variable, data type or expression in bytes.
• 'sizeof' operator is used to determine the amount of memory space that the
variable/expression/data type will take. For example,
• sizeof(char) returns 1, that is the size of a character data type. If we have,
int a = 10;
unsigned int result;
result = sizeof(a);
then result = 2,
49