You are on page 1of 31

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.

Programming language can be defined in different ways, amongst which include:


- Is a specific set of commands or instructions used to direct, instruct or communicate with
computers.
- Is a vocabulary and set of grammatical rules for instructing a computer or computing
device to perform specific tasks.
- Are the tools we use to write instructions for computers to follow. 
- Is made up of a series of symbols that serves as a bridge that allow humans to translate
our thoughts into instructions computers can understand.
- Are commands and instructions, together with other syntax that are used to create
software program.
- it is a formal language comprising a set of strings that produce various kinds of machine
code output.
- Are used in computer programming to implement algorithms.

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.

What is a Program? A program:


- Is a set of instructions that tells the computer what to do.
- It can be seen as set of instructions issued to the computer to perform a specific task
- They are detailed plan or procedure for solving a problem with a computer.

Computer programming (also called programming or coding), is the process of writing,


testing, debugging/troubleshooting and maintaining act of instructions for solving a problem
with the computer.
A source code (Program) is written in an acceptable computer programming language. The
code may be a modification of an existing source or something completely new.

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.

Reasons for learning C programming Language


Learning C language helps you build a strong foundation of programming. Some say that C is
the core of all programming languages. Learning C does not mean that you will only learn how
to code in C but you will also learn how that program or code gets executed on a computer.
Programming has many concepts that you need to be clear about like classes, objects,
polymorphism, and inheritance among others. Other advanced languages build upon these
concepts. C is the language where you can find the basis for these concepts.

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.

C is a block-structured language. It is a simple language that follows a structured


approach to programming, i.e., it divides a problem into smaller sub-problems and then solves
them. This means every code is written in separate block and is not connected with the code in
the next block. With this, you can make programming easier and you can minimize the
possibilities of unnecess-ary side effects.

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.

It is used in embedded programming


C is used in embedded programming, which is used to control micro-controllers. These micro-
controllers are used in robotics, computers, and automation. Learning C can help you here as
well. Also appliances such as T.V., Refrigerators, and Microwaves etc. are becoming an integral
part of our daily needs. They have a CPU with them which do need programming and the
software's written for them are known as embedded system programs. These programs have to be
fast in execution but also have a very little memory. C is ideally suited for embedded system
programming.

Integrated Development Environments (IDE)


The process of editing, compiling, running, and debugging programs is often managed by a
single integrated application known as an Integrated Development Environment, or IDE for
short. It is a software application that provides comprehensive facilities to computer
programmers for software development. It normally consists of at least a source code editor,
build automation tools and a debugger. Examples of IDEs include Netbeans, Eclipse, intellij
IDEA, Visual Studio and codeblocks(mostly for C and C++). This course uses Code::Blocks
(Kindly install it on your computer).

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.

Creating, Compiling and running of C program


The procedure for turning a C program into machine language involves straight forward steps
that needs to be repeated a number of times during development in order to improve the program
and eliminate errors.
The following are the four steps in this process
1) Writing and Editing the program: The software used to write programs is known as a text
editor. A text editor helps us enter, change and store character data e.g. include the
IDEs mentioned above. Code::blocks, Visual studio etc.
2) Compiling the program
3) Linking the program with the required modules:
The Linker assembles all functions, the program’s functions and system’s functions into
one executable program. E.g. linking the programs with the header files or other
functions.
1) Executing the program: To execute a program we use an operating system command,
such as run, to load the program into primary memory and execute it. Getting the
program into memory is the function of an operating system program known as the
loader. It locates the executable program and reads it into memory. When everything is
loaded the program takes control and it begins execution.

Structure of C Language program


Syntax and Structure of C++ program
Below is the structure of C program, it is means that C program can be written in this structure
only. Writing a C program in any other structure will not compile correctly (lead to
compilation Error.)

4
COM 121- Introduction to C.

Below is a simple and basic C HELLO program


First C++ program

/* a program that prints a message on the screen */


#include <stdio.h>
/*symbolic constants section*/
//Global declaration section comes in here
main()
{
printf(" Hello, welcome to the world of C!\n");
return 0;-
}
/* Subprogram section*/

5
COM 121- Introduction to C.

Let us now understand this program in detail.


1) The comment line- (documentation section)
Comments are used for documentations in programming. They are not executable but
increases readability! It is used to explain what a line or section of the program does. It is
very useful in case you visit the program after a long period of time to remind you what a
particular line of code does. In C programs, comments are represented with /*…….*/. It
can be used for either a line of statement or multiple lines of statements but it cannot be
nested. It can be used anywhere in the program. ANSI C also permits the use of “//” for
one line comments e.g. //my name is Dorathy or /* my name is Dorathy*/

2) #include <stdio.h> (link section)


The link section provides instructions to the compiler to link functions from the system
library such as using the #include directive.
The “#include is a C preprocessor directive. A preprocessor directive always begins with
a pound sign (#). Preprocessor directives don’t cause anything to happen at runtime
(when you run your program). Instead, they work during the compiling of your program.
#include<stdio.h> tells the compiler to include information about the standard
input/output header file from the library into the program. The <stdio.h> contains some
built-in functions in C, such as printf()- that is used to display on the screen and scanf() –
that is used to accept input from keyboard.

3) Definition section: The definition section defines all symbolic constants using the
#define directive.

4) Global declaration section


These are some variables that are used in more than one function. Such variables are
called global variables and are declared in the global declaration section that is outside of
all the functions. This section also declares all the user-defined functions.

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.

8) Subprogram section: If the program is a multi-function program then the subprogram


section contains all the user-defined functions that are called in the main () function.
User-defined functions are generally placed immediately after the main () function,
although they may appear in any order.

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)

Basic data types


 Integer data Types:
An integer is a number without a decimal point. They are whole numbers. All of the
following are integers: 20, 45, 0, –112, –86, 257
Integers— long, short, signed, unsigned. C offers two variations of the integer data
type— short and long .
Though their sizes vary across compilers, following rules apply:
(a) short is at least 2 bytes big
(b) long is at least 4 bytes big
(c) short is never bigger than int
(d) int is never bigger than long

 Floating point data type


Numbers with decimal points are called floating-point numbers. All of the following are
floating point numbers:
547.43, 0.0, 0.44384, 9.1923, –168.4, 70 .22

 Character data type


Any single character that your computer can represent is referred to as a C character. It
could be a single digit, a letter or a single special symbol enclosed within single inverted
commas. A 4 may appear to be a number, which it is, but it is also a character. You
can't do math with a 4 that has been designated as a character. You can conduct math
with another 4 if you declare that it will be a number. The special symbols are the same
way. Although the plus sign (+) is a character, it also conducts addition. Apostrophes (')
surround all of C's character data. For example, in a C program, all of the following are
character data:
'A' 'a' '4' '%' ' ' '-'
None of the following can be character data because they have no apostrophes around
them: A a 4 % -

There are two types of type qualifier in c


Size qualifier: short, long
Sign qualifier: signed, unsigned
When the qualifier unsigned is used the number is always positive, and when signed is used
number may be positive or negative. If the sign qualifier is not mentioned, then by default sign
qualifier is assumed. The range of values for signed data types is less than that of unsigned data
type.
To get the exact size of a type or a variable on a particular platform, you can use
the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in
bytes. The sizeof operator is a keyword in c language.

8
COM 121- Introduction to C.

#include <stdio.h>
#include <stdlib.h>
#include <limits.h> /* integer specifications */
#include <float.h> /* floating-point specifications */

/* Look at range limits of certain types */


int main (void)
{
printf("Integer range:\t%d\t%d\n", INT MIN, INT MAX);
printf("Long range:\t%ld\t%ld\n", LONG MIN, LONG MAX);
printf("Float range:\t%e\t%e\n", FLT MIN, FLT MAX);
printf("Double range:\t%e\t%e\n", DBL MIN, DBL MAX);
printf("Long double range:\t%e\t%e\n", LDBL MIN, LDBL MAX);
printf("Float-Double epsilon:\t%e\t%e\n", FLT EPSILON, DBL EPSILON);
printf("%e",sizeof(int));
printf("%d\n",sizeof(int));
printf("%e\n",sizeof(float));
printf("%e\n",sizeof(double));
return 0;
}

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.

Syntax: Data_type variable_name;


int b;
char p;
float z;

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

Example: Data_type variable_name = constant;


int a=20; or
int a;
a=20;

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.

Int int or signed int 2 -32768 to 32767


unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
1 0 to 255
unsigned short int
4 -2147483648 to 2147483647
long int or signed long int
4 0 to 4294967295
unsigned long int
Float Float 4 -3.4E-38 to 3.4E+38
double Double 8 1.7E-308 to 1.7E+308
Long double 10 3.4E-4932 to 1.1E+4932

Character constants (e.g. ‘A’)


Character constants such as ’a’, ’\n’, ’7’, are specified by single quotes. These can be single
digit, single special symbol or white spaces such as ‘9’,’c’,’$’, ‘ ’ etc. Only single characters, not
multiple characters, can go inside apostrophes. It should be noted that character constants have
numerical values known as ASCII (American standard code for information interchange) values,
for example, the value of ’A’ = is 65 which is its ASCII value.
Some numeric value associated with each upper and lower case alphabets and decimal integers
are as:
A------------ Z ASCII value (65-90)
a-------------z ASCII value (97-122)
0-------------9 ASCII value (48-59)

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.

The #define Preprocessor


Given below is the form to use #define preprocessor to define a constant −

#define identifier value


The following example explains it in detail −
#include <stdio.h>
#include <stdlib.h>

#define LENGTH 55
#define WIDTH 4
#define NEWLINE '\n'

int main() {
int area;

area = LENGTH * WIDTH;


printf("Area is calculated as : %d", area);
printf("%c", NEWLINE);

return 0;
}

When the above code is compiled and executed, it produces the following result −
Area is calculated as: 220

The const Keyword


You can use const prefix to declare constants with a specific type as follows −
const type variable = value;

The following example explains it in detail –


#include <stdio.h>
#include <stdlib.h>
int main() {
const int LENGTH = 55;
const int WIDTH = 4;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("Area is calculated as: %d", area);
printf("%c", NEWLINE);

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:

Escape sequence Meaning


\\ \ character
\' ' character (Single quotation mark is printed)
\" " character (Double quotation mark is printed)
\? ? character
\a Alert or bell
\b Backspace (Cursor moves one space to the left)
\f Form feed
\n Newline (Cursor moves to the beginning of the
next line)
\r Carriage return (Cursor moves to the beginning
of the current line (not the next line))
\t Horizontal tab (Cursor moves to the next tab
stop)
\v Vertical tab

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.

Syntax of declaring storage classes is:-


storageclass datatype variable name;

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.

Compiler assume different storage class based on:-


1 ) Storage class:- tells us about storage place(where variable would be stored).
2) Initial value :-what would be the initial value of the variable. If initial value not assigned,
then what value taken by uninitialized variable.
3) Scope of the variable:- ; i.e. in which functions the value of the variable would be available.
4) Life time :- It is the time between the creation and distribution of a variable or how long
would variable exists. how long would the variable exist. Some variables exist briefly, some are
repeatedly created and destroyed, and others exist for the program’s entire execution.

Storage classes and their features


Storage Keyword storage Default initial scope Life time
class value
1 Automatic Auto Memory predictable value Local to the Till control remains in
location or Garbage value block or the block where
function variable is defined
2 Register Register CPU Garbage value Local to the Till control remains in
Register block or the block where
function variable is defined
3 Static Static Memory Zero Local to Value of the variable
location block or fn persist or remain
in which it between different call.
is defined
4 External Extern Memory Zero Global As long as program
area execution remains its
retains

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

printf(" \n a = 10, b = 4 ");


printf(" \n a %% b =%d", a%b); // 2
printf(" \n a + b = %d ", a + b); // 14
printf(" \n a/b =%d", a/b); // 2
printf(" \n a * b = %d", a * b); // 40
printf(" \n a - b =%d", a - b); //4
return 0;
}

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);

CONDITIONAL (TERNARY OPERATORS) IN C


Conditional operators return one value if condition is true and returns another value if condition is
false. This operator is also called ternary operator.
Syntax :
(Condition? true_value: false_value);
(Condition? result1: result2);
Example :
int a= 3, c;
c = (a > 100 ? 0 : 1);
printf(" \n the value of c = %d", c);

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

Increment and Decrement Operators


Increment operators are used to increase the value of the variable by one and decrement operators
are used to decrease the value of the variable by one in C programs.

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

C OPERATOR PRECEDENCE AND ASSOCIATIVITY


C operators in order of precedence (highest to lowest). Their associativity indicates in what order
operators of equal precedence in an expression are applied.
From greatest to smallest priority, C++ operators are evaluated in the following order:
Operator Description Associativity
() Parentheses (function call) Brackets left-to-right
[] array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement

++ -- Prefix increment/decrement right-to-left


+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left

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

Type casting operation


When variables and constants of different types are combined in an expression then they are
converted to same data type. The process of converting one predefined type into another is called
type conversion.

Type conversion in C can be classified into the following two types:


 Implicit Type Conversion
 Explicit Type Conversion

Implicit Type Conversion


When the type conversion is performed automatically by the compiler without programmer‘s
intervention, such type of conversion is known as implicit type conversion or type promotion. The
compiler converts all operands into the data type of the largest operand.

Explicit Type Conversion


The type conversion performed by the programmer by posing the data type of the expression of
specific type is known as explicit type conversion. The explicit type conversion is also known as
type casting. Type casting in C is done in the following form:
(data_type)expression;

where, data_type is any valid C data type, and expression may be constant, variable or expression.

For example, x=(int)a+b*d;

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;
}

FORMATTED INPUT AND OUTPUT


C provides standard functions scanf() and printf(), for performing formatted input and output.
These functions accept, as parameters, a format specification string and a list of variables. The
format specification string is a character string that specifies the data type of each variable to be
input or output and the size or width of the input and output.

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

Syntax for printf()


printf (format, data1, data2,……..);

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.

program extract of printf()/escape sequence


main()
{
/* These three lines show you how to use the most popular Escape
Sequences */
printf("Column A\tColumn B\tColumn C");
printf("\nMy Computer\'s Beep Sounds Like This: \a!\n");
printf("\"Letz\bs fix that typo and then show the backslash ");
printf("character \\\" she said\n");

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.

C’s most-used conversion characters.


Conversion character Description
%d integer
%c character
%f float
%s String
%e float with exponentials
When you want to print a value inside a string, insert the appropriate conversion characters in the
String. Then to the right of the String, list the value you want to be printed.

Example of the use of conversion characters


printf("%s %d %f %c\n", "Sam", 14, -8.76, 'X');

// the out put is Sam 14 -8.760000 X

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.

printf("%f %.3f %.2f %.1f", 4.5678, 4.5678, 4.5678, 4.5678);


//output = 4.567800 4.568 4.57 4.6

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.

Program example of printf() and scanf()


#include <stdio.h>
#include <stdlib.h>

/* 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.

The if selection statement


If statement:
Syntax :
if(condition) statement1;

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.

Sample Program on if-else Statement :


#include <stdio.h>
void main()
{ int score=50;
if(score>=40) {
printf("Student is Pass");
}
else
{printf("Student is Fail");
} //output is student passed
}

25
COM 121- Introduction to C.

Nested if...else Statements


Nested if…else statements test for multiple cases by placing if…else statements inside
if…else statements.

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;
}

It is also possible to chain if-else statements in the following form


if (expression)
statement;
else if (expression)
statement;
else if (expression)
statement;
else
statement;

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.

printf(" \n send me a text message" );


}
else if (userAns == 5)
{
//Perform the Delete Contact Routine
printf("\n Delete my numbers from your phone" );
}
else
{
//Perform the Quit Routine
printf("\n quit selection" );
}
return 0;
}

The switch statement


The switch statement is a multi-way (multiple) decision that tests whether an expression matches one of a number of
constant integer values, and branches accordingly.

The general form of the switch statement is as follows.


switch(expression)
{ case value1 :
body1 (statements)
break;
case value2 :
body2
break;
case value3 :
body3
break;
. ..
default :
default-body
break;
}
next-statement;

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; }

Rewriting example above using switch-case


#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("using switch - case construct \n");
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);
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;
}

The iteration structure (Loop).


It is a block of statement that performs set of instructions. In loops, Repeating particular portion
of the program either a specified number of time or until a particular no of condition is being
satisfied.
There are three types of loops in c
1.While loop
2.do while loop
3.for loop

While Loop Syntax:


initialization;
while(condition)
{
Statements;
}

30
COM 121- Introduction to C.

Do-While Loop Syntax :


initialization;
do
{
statements;
}
while(condition);

for loop
For (initializer; condition; expression) statements;

31

You might also like