COM 121-Introduction To C
COM 121-Introduction To C
Computers cannot think nor can they understand what humans say! There is then a need for a
way to tell them what we want, so we can work together and get things done. Programming
language is how we can talk to computers. Unlike people, machines cannot guess our intent. We
have to be super meticulous and describe what we want in every little detail especially step by
step ways of doing things.
Most Languages that programmers use to write code are called "high-level languages." This code
can be compiled into a "low-level language," which is recognized directly by the computer
hardware using a translator (compiler or interpreter). Examples of high-level languages include
C, C++, Java, Perl, and PHP.
Each language has a unique set of keywords (words that it understands) and a special syntax for
organizing program instructions.
The description of a programming language is usually split into the two components
of syntax (form) and semantics (meaning).
There are tons of programming languages out there that allow you to do all sorts of things, from
building virtual reality experiences to creating video games and more.
1
COM 121- Introduction to C.
SYNTAX
- The syntax of a computer language is the set of rules that defines the
combinations of symbols that are considered to be correctly structured statements
or expressions in that language.
- Syntax is a set of rules for grammar and spelling
- The syntax of a language describes the possible combinations of symbols that
form a syntactically correct program.
- We refer to syntax in computer programming as the concept of giving
specific word sets in specific orders to computers so that they do what we
want them to do.
Introduction to C
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was
designed and written by a man named Dennis Ritchie. In the late seventies C began to replace the
more familiar languages of that time like PL/I, ALGOL, etc
It is a structured, procedural and general-purpose programming language, and is used for writing
programs in many different domains, such as operating systems, numerical computing, graphical
applications, etc. It is a small language, with 32 keywords. It provides “high-level” structured
programming constructs such as statement grouping, decision making, and looping, as well as
“low-level” capabilities such as the ability to manipulate bytes and addresses.
C Language is easy to learn and Apply: The syntax of the C programming language is easy to
learn and implement. Various resources of C programing language are available from different
sources( e.g. internet, text books). With the help of C, you can easily learn high-level
programming languages. You can learn C fast even if you have zero knowledge of programming.
Versatile: The C programming language is versatile. You can execute a C program code in any
operating system. It is platform-independent. It is considered that C is the boss of hardware
programming. With the help of C, you can code or program different types of hardware such as
robots and electronic appliances of the house.
It forms the basis for C++ and Java: Java and C++ are amongst the most widely used
programming languages today. They derive their syntax, and concepts from the C
programming language. Being acquainted with the C programming basics will thus make
learning C++ and Java easier.
2
COM 121- Introduction to C.
The use of Memory management: C Language is very flexible in the use of memory
management. Programmers have opportunities to control how, when, and where to allocate and
deallocate memory. Memory is allocated statically, automatically, or dynamically in C
programming with the help of malloc and calloc functions. C language enables you to work
closely with the hardware. This facilitates developing system software and makes it a top choice
for system level programming.
Less Execution Time: The C programming language is fast and efficient. it offers fast compilation
time to their users. In C, programs and codes get executed faster than any other programming
language. C does not include additional processing overheads like garbage collection or avoiding
leaking of memory. (When it comes to speed of execution, C is still unmatched.)
C is a middle level language.: C is a middle level language because it combines the best part of
high level language(make development of programs fast enough) with low level language
(execute programs faster). It is both user and machine oriented and provides infinite
possibilities.
3
COM 121- Introduction to C.
What is ANSI C?
Because of the many possible versions of C, a committee known as the American National
Standards Institute (ANSI) committee developed a set of rules (known as ANSI C) for all
versions of C. As long as you write and run programs using an ANSI C compiler, you can be
sure that you can compile your C programs on almost any computer that has an ANSI C
compiler.
4
COM 121- Introduction to C.
5
COM 121- Introduction to C.
3) Definition section: The definition section defines all symbolic constants using the
#define directive.
5) main()
The most important part of a C program is its main() function. The parenthesis “()”
attached to main shows that it is a function. Every C program contains the main function.
The program execution starts from here and its return type is int (integer) though it can
also return nothing (void).
6) Braces ({})
The opening and closing pair of braces after a function shows the starting and end of the
function. In-between these braces comes the statements to be executed in the function.
This pair of braces and the portion of the program between the braces is called a block.
For example the opening and closing braces in our example above shows the beginning
and ending of the function main. The printf statement comes in the braces and will be
executed.
7) printf ()
The printf() is a C built-in function used to print anything on the screen. To be able to
use the printf() function, it is necessary to use #include at the beginning of the program.
6
COM 121- Introduction to C.
C building Blocks
In the human world, before you speak any language, you must have learnt different words that
makes up a sentence, likewise in the computer world, before you can program in any language,
you must at least know the things that make up the language. Each and every smallest individual
unit in a C program is known as C tokens. C tokens are of different types. They are keywords,
special symbols, constants, variables and the operators that make up the language. Below are
some terms we need to know about C programming language.
C KEYWORDS (reserved)
C keywords are the words that convey a special meaning to the c compiler. The keywords
cannot be used as variable names as it has been assigned with fixed meaning. Keywords are
normally written in lowercase letters.
Some examples of keywords are int, short, signed, unsigned, default, volatile, float, long,
double, break, continue, typedef, static, do, for, union, return, while, do, extern, register,
enum, case, goto, struct, char, auto, const etc.
Identifiers
Identifiers are user defined words consisting of arbitrarily long sequence of letters and digits with
either a letter or the underscore(_) as the first character used to name entities like variables,
functions, arrays, structures etc. Rules for naming identifiers are:
1) Name should only consists of alphabets (both upper and lower case), digits and
underscore (_) sign.
2) First characters should be alphabet or underscore
3) Name should not be a keyword(reserved words)
4) Since C is case sensitive, the upper case and lower case are considered differently, for
example code, Code, CODE etc. are different identifiers.
5) Identifiers are generally given in some meaningful name such as value, net_salary,
age, data etc. An identifier name may be long, some implementation recognizes only
first eight characters, most recognize 31 characters. ANSI standard compiler
recognize 31 characters.
6) Some valid identifiers are grade, interest, total reg_no, etc.
7) Some invalid identifiers are 5cb, int, res#, avg no etc.
Data types
C is a typed language, meaning that each variable or identifier must be defined with name and a
specific type to determine the value it can hold or represent in a program. In C programming
language, the Basic data types are char (character) , int (integer) , and float (floating point or real
numbers). Each of these has several sub-types. Other data types in C language include
- Enum (enumeration),
7
COM 121- Introduction to C.
- derived data types (array, pointers, structure, union and functions) and
- void types (indicates that no value is available)
8
COM 121- Introduction to C.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h> /* integer specifications */
#include <float.h> /* floating-point specifications */
Variables
Variable is a data name which is used to store some data value or symbolic names for storing
program computations and results. During the execution, the variable's value can be changed.
The same rules apply to naming variables as they do to naming identifiers.
A variable must be defined and declared before it may be used in the program. Variable
declarations include their name, data types, and the range of values that variables can store,
which is determined by their data types.
Variable initialization
Initialization of variables occurs when we assign initial value to a variable during the declaration.
Garbage value is a term used to describe a variable that has been declared but has no defined
value.
The variable is initialized with the assignment operator such as
9
COM 121- Introduction to C.
Constants
Constant is any value that cannot be changed during program execution. These fixed values are
also called literals. We have different types of constants:
Integer constants
Integer constants are whole numbers without any fractional part. It must have at least one digit
and may contain either + or – sign. A number with no sign is assumed to be positive.
There are three types of integer constants:
Decimal constant: 0-------9(base 10)
Octal constant: 0-------7(base 8)
Hexa decimal constant: 0----9, A------F(base 16)
In decimal constant first digit should not be zero unlike octal constant first digit must be zero (as
076, 0127) and in hexadecimal constant first two digit should be 0x/ 0X (such as 0x24, 0x87A).
For example:
1234 is an integer constant of type int. A constant of type long int is suffixed by an L, 1234L;
(integer constants too big for int are implicitly taken as long). An unsigned int is suffixed by a U,
1234U, and UL specifies unsigned long.),
Real constants
It is also called floating point constant. Floating-point constants are specified by a decimal point
after a number.
-real constant must have at least one digit.
-It must have a decimal point.
-It could be either positive or negative.
-Default sign is positive.
-No commas or blanks are allowed within a real constant.
Ex.: +325.34, 426.0, -32.76
Floating point numbers can also be written using exponents (scientific notation), such as 1.65e-2
(which is equivalent to 0.0165). Constant expressions, such as 3+7+9.2, are evaluated at
compile-time and replaced by a single constant value, 19.2. Thus, constant expressions incur no
runtime overhead.
To express small/large real constant, exponent(scientific) form is used where number is written
in mantissa and exponent form separated by e/E. Exponent can be positive or negative integer
but mantissa can be real/integer type, for example 3.6*105=3.6e+5.
The size and range of the different data types on a 16 bit machine is given below:
Basic data type Data type with type Size Range
qualifier (byte)
Char char or signed char 1 -128 to 127
Unsigned char 1 0 to 255
10
COM 121- Introduction to C.
String constant
Set of characters are called string and when sequence of characters are enclosed within a double
quote (it may be combination of all kind of symbols) is a string constant. String constant has
zero, one or more than one character and at the end of the string null character(\0) is
automatically placed by compiler. Some examples are “sarathina” , “908”, “3”,” ”, “A” etc. In C
although same characters are enclosed within single and double quotes it represents different
meaning such as “A” and ‘A’ are different because first one is string attached with null character
at the end but second one is character constant with its corresponding ASCII value is 65.
Symbolic constants
Symbolic constants are names that represent numerical constants. These are specified by
#define (using The #define Preprocessor), and mean that we can avoid littering our code with
numbers. These constant are generally defined at the beginning of the program and normally
written in upper case.
Defining constants
Defined constants are good for naming values that might need to be changed between program
runs.
There are two simple ways in C to define constants −
Using #define preprocessor.
Using const keyword.
11
COM 121- Introduction to C.
#define LENGTH 55
#define WIDTH 4
#define NEWLINE '\n'
int main() {
int area;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Area is calculated as: 220
return 0;
}
12
COM 121- Introduction to C.
Escape characters
There are certain characters in C++ when they are preceded by a backslash (\) they will have
special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list
of some of such escape sequence codes:
Storage Classes
Storage class in c language is a specifier which tells the compiler where and how to store
variables, its initial value and scope of the variables in a program.
The kind of location in the computer, where value can be stored is either in the memory or in the
register. There are various storage classes which determine, in which of the two location value
would be stored.
There are four types of storage classes and all are keywords:-
1 ) Automatic (auto)
2 ) Register (register)
3) Static (static)
4 ) External (extern)
Examples:-
auto float x; or float x;
extern int x;
register char c;
static int y;
13
COM 121- Introduction to C.
Expressions
An expression is a combination of variables, constants, operators and function call.
It can be arithmetic, logical and relational for example:-
int y= k+ x// arithmetic expression
x>y //relational
a==b // logical
func(c, d) // function call
Operators
This is a symbol use to perform some operation on variables, operands or with the constant.
Some operator required 2 operands (binary) to perform operation while some require single
operand(unary).
C language offers many types of operators. They are,
1. Arithmetic operators
2. Assignment operators
3. Relational operators
14
COM 121- Introduction to C.
4. Logical operators
5. Conditional operators (ternary operators)
6. Increment/decrement operators
7. Special operators
8. Bit wise operators
Arithmetic Operators
These are used to perform mathematical calculations like addition, subtraction, multiplication,
division and modulus. The arithmetic operators are addition (+), subtraction (-), multiplication
(*), division (/), and modulo (%).
#include <stdio.h>
#include <stdlib.h>
int main() {
int area;
int a = 10, b = 4, c;
c = a + b; // 14
c = a - b; // 6
c = a * b; // 40
c = a / b; // 2, integer division
c = a % b; // 2, remainder
Assignment operator
A value can be stored in a variable with the use of assignment operator. The assignment
operator(=) is used in assignment statement and assignment expression. We have simple and
compound assignment operators. Example of the simple assignment operator:
Int a, d, c = 43, b, m;
m = 89;
b= a= d= 20; // multiple assignment
The compound variant comes in a bit different form (e.g. +=, -=, *=, /=, %=). In the example
below, a's value is increased by the value of c; that is, a is given the value 4.
15
COM 121- Introduction to C.
int a = 2, b = 4, c = 2;
b -= c; // 2, equivalent to b = b - c.
For most binary operators ‘op’ whose operands have the same type, the combination operator
“op = “ can be used as :
Variable op= expression // to perform the combined operations
Variable = Variable op expression
Compound assignment operators modify the current value of a variable by performing an
operation on it. They are equivalent to assigning the result of an operation to the first operand:
Expression equivalent to
y += x; y = y + x;
y *= 4; y = y * 4;
program extract
int a = 8, b=6;
a *= b ; // equivalent to a= a * b i.e. a = 8 * 6
a += b; // a = 48 + 6 = 54 at this point
a /=b; // a = 54/6 = 9 at this point
a%=b; // a = 9 % 6 = 3 at this point
printf(" \n %d" ,a); // final output is 3
Relational operator
These operators are used to compare the value of two variables. they produce a true or false
result. When you compare two data values, the data values either produce a true comparison or
they don’t. They include: greater than(>), Less than (<), greater than or equal to (>=), equal to
(==), Less than or equal to (<=) and not equal to (!=). For example, given the following values:
int i = 5, j = 10, k = 15, w = 5;
the following statements are true:
i == w;
j < k;
k > i;
j != w;
The following statements are not true, so they are false:
i > j;
k < j;
k == w
Every time C evaluates a relational operator, a value of 1 or 0 is produced. True always results in
1, and false always results in 0. The following statements assign a 1 to the variable a and a 0 to
the variable b:
a = (4 < 10); // (4 < 10) is true, so a 1 is put in a
b = (8 == 9); // (8 == 9) is false, so a 0 is put in b
Logical Operator
16
COM 121- Introduction to C.
The three logical operators are AND ( &&), OR (||) and NOT !. Where logical NOT is a unary
operator and other two are binary operator.
The && and || operators connect pairs of conditional expressions, with && being TRUE only if
both expressions are TRUE, and || being TRUE if either expression is TRUE. They can be
used to chain together multiple expressions, as in the following example where,
int a=1, b=2, c=3, d=3,
(a < b) && (b < c) && (c < d) /* FALSE */
(a < b) && (b < c) && (c <= d) /* TRUE */
The statement below can be represented with logical and relational operators
“If the age is at least 21 and no more than 65,...” can be represented as
if ((age >= 21) && (age <= 65)) {…
The ! (not) operator reverses a true or a false condition. True becomes false, and false becomes
true. So if the expression evaluates to true, then applying ! operator to it results into a false. Vice versa, if the expression
evaluates to false, then applying ! to it makes it.true. Here is an example showing use of ! operator.
int y = 5;
int a, b;
a = (y<10); // a results to true (i.e 1)
b = !(y<10); // b results to false (i.e 0)
printf(" the value of a = %d", a);
printf(" the value of b = %d", b);
In above example, if a is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.
Example
int a = 5, b = 7, big;
big = (a > b) ? a : b; // The maximal value of a and b
17
COM 121- Introduction to C.
If increment or decrement operators are placed before a variable (i.e., prefixed), they are referred to as the pre-
increment or pre-decrement operators, respectively. (++d or –d)
If increment or decrement operators are placed after a variable (i.e., postfixed), they are referred to as the post-
increment or post-decrement operators, respectively.
Syntax:
Increment operator: ++var_name ;( or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
Example1 of increment
int main()
{
int p=20, a, b,q,f, s;
a=++p;
b=p++;
printf(" p is incremented by 1. therefore, a = %d \n",a);
printf("b = %d \n", b);
printf("enter a value for s \n");
scanf("%d",&s);
printf("the value entered for s is %d \n",s);
q = s++;
f = ++s;
printf(" post incrementing s is %d. pre- incrementing s again is %d \n", q, f);
int k=20, w, j;
w=--k;
j=k--;
printf(" the decrement operator\n\n");
printf("post-decrementing k = %d\n",w);//
printf("pre-decrementing j = %d \n", j);
return 0;
}
18
COM 121- Introduction to C.
example 3
int i=1;
while(i<10)
{
printf(" i = %d ",i);
i++;
}
Bitwise Operators
They are used for manipulating the bits of integral operands. Read up Bitwise operators
19
COM 121- Introduction to C.
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right
where, data_type is any valid C data type, and expression may be constant, variable or expression.
The following rules have to be followed while converting the expression from one type to another
to avoid the loss of information:
Rules for converting from one data type to another (type casting)
All integer types to be converted to float.
All float types to be converted to double.
All character types to be converted to integer.
Program extract
int main()
{ int a, b, c;
float d, e, f;
20
COM 121- Introduction to C.
a= 2 ;
d= 4.6, f = 7.9;
b = a + (int)f;
e= (float)a + d;
printf("the value of b is %d \n", b);
printf("the value of e is %.2f", e);
return 0;
}
Printf()
C’s primary means of output is the printf() function. printf() produces output on your screen. The
function printf() is a general purpose print function that converts and formats its arguments to a
character string, and prints the result to standard output (typically the screen). The general interface for printf() is
In this syntax format is the format specification string. C does not automatically move the cursor
down to the next line when a printf() executes. You must insert an escape sequence (\n) in the
String if you want C to go to the next line after a printf().
Double quotation marks begin and end of a string, single quotation marks begin and end a
character, and a backslash signals the start of an escape sequence, so they have their own escape
sequences if you need to print them. \a rings your computer’s bell, \b moves the cursor back a
line, and \t causes the output to appear moved over a few spaces.
21
COM 121- Introduction to C.
return 0;
}
Conversion Characters
When you print numbers and characters, you must tell C exactly how to print them. You indicate
the format of numbers with conversion characters.
You can control how C prints floating-point values by placing a period (.) and a number between
the % and the f of the floating-point conversion character.
C rounds the floating-point numbers to the number of decimal places specified in the %.f
conversion character
scanf()
22
COM 121- Introduction to C.
The scanf() function gets data from the keyboard. You must have a way to get data from your
user. You can’t always assign data values using assignment statements. scanf() is a built-in C
function that comes with all C compilers. It reads characters from standard input and interprets
them according to the format string specification.
scanf() looks a lot like printf() because scanf() uses conversion codes such as %s and %d. scanf()
is the mirror-image function of printf(). Often you will write programs that ask the user for
values with a printf() and get those values with scanf().
Format of scanf():
scanf (format, num1, num2,……);
scanf() requires that you put the ampersand (&) before all variables, even though the ampersand
is not part of the variable name! Do it, and scanf() works; leave off the ampersand, and scanf()
won’t accept the user’s values into the variables.
/* This is a sample program that asks users for some basic data and
prints it on screen in order to show what was entered */
int main()
{
// Set up the variables that scanf will fill
printf(" my name is, ");
scanf("%s",&name);
char f_Initial;
char l_Initial;
int years;
int best_number;
printf("Enter the letter your first name starts with?\n");
scanf(" %c", &f_Initial);
printf("Enter the letter your last name starts with?\n");
scanf(" %c", &l_Initial);
printf("How old are you?\n");
scanf(" %d", &years);
printf("Which number do you love the most (integer only)?\n");
scanf(" %d", &best_number);
printf("\nYour intitials are %c.%c. and you are %d years old",
f_Initial, l_Initial, years);
printf("\nYour favorite number is %d.\n\n", best_number);
return 0;
}
23
COM 121- Introduction to C.
Control Structures
Normally, statements in a program are executed one after the other in the order in which they’re written. This
is called sequential execution. Various C statements we’ll soon discuss enable you to specify that the next
statement to be executed may be other than the next one in sequence. This is called transfer of control.
In C, all programs could be written in terms of only three control structures, namely
the sequence structure,
the selection (decision) structure and
the iteration structure.
Sequence structure
The sequence structure is simple—unless directed otherwise, the computer executes C statements one after the
other in the order in which they’re written. The syntax is
Statement_1
Statement _2
…
Statement_n
Selection Statements in C
C provides three types of selection structures in the form of statements.
The if selection statement: it either selects (performs) an action if a condition is true or skips the
action if the condition is false.
The if…else selection statement performs an action if a condition is true and performs a different
action if the condition is false.
The switch selection statement performs one of many different actions, depending on the value of an
expression.
The if statement is called a single-selection statement because it selects or ignores a single action.
The if…else statement is called a double-selection statement because it selects between two different actions.
The switch statement is called a multiple-selection statement because it selects among many different actions.
Explanation :
Expression is Boolean Expression
It may have true or false value
If Expression is True Then it executes the statement otherwise jumps to next_instruction
24
COM 121- Introduction to C.
Sample Code :
int main()
{
int a=7,b=6,c;
c=a+b;
if (c==13)
printf("Execute me 1");
printf("Execute me 2");
return 0;} // output will be Execute me 1 Execute me 2
if-else Statement :
We can use if-else statement in c programming so that we can check any condition and depending
on the outcome of the condition we can follow appropriate path. We have true path as well as false
path.
Syntax :
if(expression)
{ statement1;
statement2; }
else
{ statement3;
Statement4; }
next_statement;
If condition is True then Statement1 and Statement2 are executed Otherwise Statement3 and
Statement4 are executed.
25
COM 121- Introduction to C.
Syntax is :-
if (condition)
{ If (condition)
Statement1;
else
statement2;
}
Statement3;
Example code
int m; a =6, b =5;
if (a > b)
if (m != 0)
b = a;
else
a = m;
printf(" they enjoyed");
return 0;
}
26
COM 121- Introduction to C.
This chain is evaluated from the top and, if a particular if-condition is TRUE, then its statement is executed and the
chain is terminated.
Program example
What do you want to do?
1. Add New Contact
2. Edit Existing Contact
3. Call Contact
4. Text Contact
5. Delete Contact
6. Quit the Program
What is your choice?
It would take five if-else statements, nested inside one another, to handle all these conditions, as you can
see here:
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf(" \t What do you want to do? \n");
printf(" \t 1. Add New Contact \n");
printf(" \t 2. Edit Existing Contact \n ");
printf(" \t 3. Call Contact \n ");
printf(" \t 4. Text Contact \n");
printf(" \t 5. Delete Contact \n ");
printf(" \t 6. Quit the Program \n");
//printf(" \t What is your choice? \n");
int userAns;
printf(" what is your choice?");
scanf("%d", &userAns);
if (userAns == 1)
{
// Perform the Add Contact Routine
printf(" \n you can call this number 07033252466");
}
else if (userAns == 2)
{
//Perform the Edit Contact Routine
printf(" \n make changes to phone number" );
}
else if (userAns == 3)
{
//Perform the Call Contact Routine
printf(" \n give me a call on that number" );
}
else if (userAns == 4)
{
//Perform the Text Contact Routine
27
COM 121- Introduction to C.
28
COM 121- Introduction to C.
Program example
#include<stdio.h>
void main() {
int roll = 3 ;
switch ( roll )
{
case 1:
printf ( " I am Paul ");
break;
case 2:
printf ( " I am Nicole ");
break;
case 3:
printf ( " I am John ");
break;
default :
printf ( "No student found");
break; }
int userAns;
printf(" what is your choice?");
scanf("%d", &userAns);
switch(userAns)
{
case 1:
{// Perform the Add Contact Routine
printf(" \n you can call this number 07033252466");
}
break;
case 2:
{ //Perform the Edit Contact Routine
printf(" \n make changes to phone number" );
}
break;
29
COM 121- Introduction to C.
case 3:
{ //Perform the Call Contact Routine
printf(" \n give me a call on that number" );
}
break;
case 4:
{
//Perform the Text Contact Routine
printf(" \n send me a text message" );
}
break;
case 5 : {
//Perform the Delete Contact Routine
printf("\n Delete my numbers from your phone" );
}
break;
default:
{
//Perform the Quit Routine
printf("\n quitted selection" );
}
} return 0;
}
30
COM 121- Introduction to C.
for loop
For (initializer; condition; expression) statements;
31