0% found this document useful (0 votes)
8 views

C Language Overview

Uploaded by

kalasingayvonne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

C Language Overview

Uploaded by

kalasingayvonne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

C Language Overview

Programmers write instructions in various programming languages, some directly


understandable by computers and others that require intermediate translation steps. These may
be divided into three general types:
1. Machine languages
2. Assembly languages
3. High-level languages
Machine language is the language understood by computers. It is defined by the hardware
design of that computer. Machine language consists of numbers (i.e. 1s and 0s) that instruct
computers to perform their most elementary operations one at a time. Machine languages are
machine dependent (i.e. a particular machine language can be used on only one type of
computer). Machine languages are cumbersome for humans, as can be seen by the following
section of a machine-language program that adds overtime pay to base pay and stores the result
in gross pay.
+1300042774
+1400593419
+1200274027

As computers became more popular, it became apparent that machine-language programming


was simply too slow and tedious for most programmers. Instead of using the strings of numbers
that computers could directly understand, programmers began using English-like abbreviations
to represent the elementary operations of computers. These English-like abbreviations formed
the basis of assembly languages. Translator programs called assemblers were developed to
convert assembly-language programs to machine language at computer speeds. The following
section of an assembly-language program also adds overtime pay to base pay and stores the
result in gross pay, but somewhat more clearly than its machine-language equivalent.
LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY

Although such code is clearer to humans, it is incomprehensible to computers until translated to


machine language.
Computer usage increased rapidly with the advent of assembly languages, but programming in
these still required many instructions to accomplish even the simplest tasks.
To speed the programming process, high-level languages were developed in which single
statements could be written to accomplish substantial tasks. The translator programs that
convert high-level language programs into machine language are called compilers. High level
languages allow programmers to write instructions that look almost like every day English and
contain commonly used mathematical notations. A payroll program written in a high-level
language might contain a statement such as
grossPay = basePay + overTimePay
Obviously, high-level languages are much more desirable from the programmer’s standpoint
than either machine languages or assembly languages. C, C++ and Java are among the most
powerful and most widely used high-level programming languages.
The process of compiling a high-level language program into machine language can take a
considerable amount of computer time. Interpreter programs were developed to execute high-
level language programs directly without the need for compiling those programs into machine
language. Although compiled programs execute much faster than interpreted programs,
interpreters are popular in program-development environments in which programs are
recompiled frequently as new features are added and errors are corrected. Once a program is
developed, a compiled version can be produced to run most efficiently.

History of C
C was originally designed for and implemented on the UNIX operating system. C is not tied to any
particular hardware or system, however, and it is easy to write programs that will run without
change on any machine that supports C.
C is a general-purpose programming language with features economy of expression, modern
flow control and data structures and a rich set of operators. C is not a ‘‘very high level’’ language,
nor a ‘‘big’’ one, and is not specialized to any particular area of application. But its absence of
restrictions and its generality make it more convenient and effective for many tasks than
supposedly more powerful languages.
But the computing world has undergone a revolution since the publication of The C
Programming Language in 1978. Big computers are much bigger, and personal computers have
capabilities that rival mainframes of a decade ago. During this time, C has changed too, although
only modestly, and it has spread far beyond its origins as the language of the UNIX operating
system.
C has widely been used for various reason. Below are some benefits of using C
 Easy to learn

 Structured language

 It produces efficient programs.

 It can handle low-level activities.

 It can be compiled on a variety of computer platforms.

Elements in Programming Languages


There are several elements which programming languages, and programs written in them,
typically contain. These elements are found in all languages, not just C.
1. Variables or objects are used to store the pieces of data that a program is working on.
Variables are the way we talk about memory locations (data), and are similar to the ``registers''
in our pocket calculator example.
There exist two types of variables:-
 Global -are accessible anywhere in a program
 Local – are private to certain parts of a program

2. Expressions are used to compute new values from old ones

3. Assignments store values (of expressions, or other variables) into variables.


In many languages, assignment is indicated by an equals sign (=)
E.g. b = 3 or c = d + e + 1
The first sets the variable b to 3; the second sets the variable c to the sum of the variables d plus
e plus 1.
In mathematics, an equal’s sign indicates equality. In programming, there's a time element, and
a notion of cause-and-effect: after the assignment, the thing on the left-hand side of the
assignment statement is equal to what the stuff on the right-hand side was before. To remind
yourself of this meaning, you might want to read the equals sign in an assignment as ``gets'' or
``receives'': a = 3 means ``a gets 3'' or ``a receives 3''.

Consider the line i = i + 1


In algebra, we'd subtract i from both sides and end up with 0 = 1 which doesn't make much
sense. In programming, however such lines are extremely common. The variable i receives (its
new value is) by what we get when we evaluate the expression on the right-hand side. The
expression says to fetch i's (old) value, and add 1 to it, and this new value is what will get stored
into i. So i = i + 1 adds 1 to i
This is called incrementing i (i.e. add 1 to i/ increases i by 1)

4. Conditionals are used to determine whether some condition is true


E.g. determine whether one number is greater than another.
Sometimes conditionals are actually expressions which compare two values and compute a
``true'' or ``false'' value.)

5. Variables and expressions may have types, indicating the nature of the expected values.
e.g. you might declare that one variable is expected to hold a number, and that another is
expected to hold a piece of text.
In many languages (including C), your declarations of variables you plan to use and what types
you expect them to hold must be clear.
Types of data types
 single characters
Declaration char a
E.g. char a;
a=’k’;
OR char a=’k’;

 integers – are whole numbers


Declaration int b
E.g. int b;
b=2;
OR int b=2;

 real (floating point) numbers - these are numbers that contain decimals
Declaration float c
E.g. float c;
c=1.05;
OR float c=1.05;

 text strings - strings of several characters


Declaration string d
E.g. string d;
d=’welcome’;
OR string d=’welcome’

 arrays - reference (point at) values of other types.


It can be an array of any type. Easily identified by [].
Syntax array-name []
E.g. int numbers [];
numbers[] =1,2,3,4;
OR int numbers[]=1,2,3,4;
Note: there are no spaces anywhere in the declaration.

6. Statements contain instructions describing what a program actually does.


Statements may compute expressions, perform assignments, or call functions (to be discussed
later).

7. Control flow constructs determine the order statements are performed in.
A certain statement might be performed only if a condition is true. A sequence of several
statements might be repeated over and over, until some condition is met; this is called a loop.

8. An entire set of statements, declarations, and control flow constructs can be lumped
together into a function (also called routine, subroutine, or procedure) which another piece of
code can then call as a unit. When you call a function, you transfer control to it and wait for it
to do its job, after which it returns to you; it may also return a value as a result of what it has
done. You may also pass values to the function on which it will operate or which otherwise
direct its work. Placing code into functions not only avoids repetition if the same sequence of
actions must be performed at several places within a program, but it also makes programs
easy to understand, because you can see that some function is being called, and performing
some (presumably) well-defined subtask, without always concerning yourself with the details
of how that function does its job. (If you've ever done any knitting, you know that knitting
instructions are often written with little sub-instructions or patterns which describe a
sequence of stitches which is to be performed multiple times during the course of the main
piece. These sub-instructions are very much like function calls in programming.)
9. A set of functions, global variables, and other elements makes up a program.
A source code for a program may be distributed among one or more source files.

C Program Structure
Let’s look into Hello World example using C Programming Language.
Before we study basic building blocks of the C programming language, let us look a bare
minimum C program structure so that we can take it as a reference in upcoming chapters.

A C program basically consists of the following parts:


 Preprocessor Commands
 Functions
 Variables
 Statements & Expressions
 Comments

Let us look at a simple code that would print the words "Hello World":
1. #include <stdio.h>
2. int main()
3. {
4. /* my first program in C */
5. printf("Hello, World! \n");
6. return 0;
7. }

Let us look various parts of the above program:

1. The first line of the program #include <stdio.h> is a preprocessor command which tells a C
compiler to include stdio.h file before going to actual compilation.
2. The next line int main() is the main function where program execution begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program.
4. The next line printf(...) is another function available in C which causes the message "Hello,
World!" to be displayed on the screen.
5. The next line return 0; terminates main()function and returns the value 0.
C Basic Syntax
Tokens in C

A C program consists of various tokens and a token is either a keyword, an identifier, a


constant, a string literal, or a symbol. For example, the following C statement consists of five
tokens:

printf("Hello, World! \n");

The individual tokens are:

printf
(
"Hello, World! \n"
)
;
Semicolons ;

In C program, the semicolon is a statement terminator. That is, each individual statement
must be ended with a semicolon. It indicates the end of one logical entity.

For example, following are two different statements:

printf("Hello, World! \n");


return 0;

Comments

Comments are like helping text in your C program and they are ignored by the compiler.
They start with /* and terminates with the characters */ as shown below:

/* my first program in C */

You can not have comments with in comments and they do not occur within a string or
character literals.

Identifiers

A C identifier is a name used to identify a variable, function, or any other user-defined


item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or
more letters, underscores, and digits (0 to 9).

C does not allow punctuation characters such as @, $, and % within identifiers. C is a case
sensitive programming language. Thus Manpower and manpower are two different
identifiers in C. Here are some examples of acceptable identifiers:
mohd zara abc move_name a_123

myname5 _temp j a23b9 retVal


0 Keywords

The following list shows the reserved words in C. These reserved words may not be used as
constant or variable or any other identifier names.

auto else long switch


break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _packed
double

Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line, and a
C compiler totally ignores it.

Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.
Whitespace separates one part of a statement from another and enables the compiler to
identify where one element in a statement, such as int, ends and the next element begins.
Therefore, in the following statement:

int age;

There must be at least one whitespace character (usually a space) between int and age for the
compiler to be able to distinguish them. On the other hand, in the following statement

fruit = apples + oranges; // get the total fruit

No whitespace characters are necessary between fruit and =, or between = and apples,
although you are free to include some if you wish for readability purpose.
C Data Types
Data types refers to an extensive system used for declaring variables or functions of different
types. The type of a variable determines how much space it occupies in storage and how the bit
pattern stored is interpreted.
The types in C can be classified as follows:

S.N Types and Description


. Basic Types:
1 They are arithmetic types and consists of the two types: (a) integer types
and (b) floating- point types.
Enumerated types:
2 They are again arithmetic types and they are used to define variables
that can only be assigned certain discrete integer values throughout
the program.

3 The type void:


The type specifier void indicates that no value is available.

Derived types:
4
They include (a) Pointer types, (b) Array types, (c) Structure types, (d)
Union types and
(e) Function
The array types andtypes.
structure types are referred to collectively as the aggregate types. The type
of a function specifies the type of the function's return value. We will see basic types in the
following section where as other types will be covered in the upcoming chapters.

Integer Types
Following table gives you detail about standard integer types with its storage sizes and
value ranges:

Type Storage size Value range

char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to


2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767


unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647

unsigned long 4 bytes 0 to 4,294,967,295

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. Following is an example to get the size of int type on any machine:

#include <stdio.h>
#include <limits.h>

int main()
{
printf("Storage size for int : %d \n", sizeof(int));

return 0;
}

When you compile and execute the above program it produces following result on Linux:

Storage size for int : 4

Floating-Point Types

Following table gives you detail about standard float-point types with storage sizes and
value ranges and their precision:

Type Storage size Value range Precision

float 4 byte 1.2E-38 to 3.4E+38 6 decimal places


double 8 byte 2.3E-308 to 1.7E+308 15 decimal
long double 10 byte 3.4E-4932 to 1.1E+4932 places
19 decimal
places
The header file float.h defines macros that allow you to use these values and other details
about the binary representation of real numbers in your programs. Following example will print
storage space taken by a float type and its range values:

#include <stdio.h>
#include <float.h>

int main()
{
printf("Storage size for float : %d \n", sizeof(float)); printf("Minimum float
positive value: %E\n", FLT_MIN ); printf("Maximum float positive value: %E\n",
FLT_MAX ); printf("Precision value: %d\n", FLT_DIG );

return 0;
}

When you compile and execute the above program it produces following result on Linux:

Storage size for float : 4


Minimum float positive value: 1.175494E-38
Maximum float positive value: 3.402823E+38
Precision value: 6

The void Type


The void type specifies that no value is available. It is used in three kinds of situations:

S.N Types and Description


. Function returns as void
1 There are various functions in C who do not return value or you can say they return void. A
function with no return value has the return type as void. For example void exit (int status);

Function arguments as void


2 There are various functions in C who do not accept any parameter. A function with no
parameter can accept as a void. For example int rand(void);

Pointers to void
3
A pointer of type void * represents the address of an object, but not its type. For example a
memory allocation function void *malloc( size_t size ); returns a pointer to void which can be
casted to any data type.

The void type may not be understood to you at this point, so let us proceed and we will
cover these concepts in upcoming chapters.
C Variables
A variables is a name given to a storage area that programs can manipulate.
Each variable in C has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of operations
that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore character. It
must begin with either a letter or an underscore. Upper and lowercase letters are distinct
because C is case-sensitive. Based on the basic types explained in previous chapter, there will
be following basic variable types:

Type Description

char Typically a single octet(one byte). This is an integer type.

int The most natural size of integer for the machine.

float A single-precision floating point value.

double A double-precision floating point value.

void Represents the absence of type.

C programming language also allows to define various other type of variables which we will
cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union etc. For
this chapter, let us study only basic variable types.

Variable Declaration in C
All variables must be declared before we use them in C program, although certain declarations
can be made implicitly by content. A declaration specifies a type, and contains a list of one or
more variables of that type as follows:

type variable_list;

Here, type must be a valid C data type including char, int, float, double, or any user
defined data type etc., and variable_list may consist of one or more identifier names
separated by commas. Some valid variable declarations are shown here:

int i, j, k; char c, ch;

A variable declaration does not allocate any memory space for the variable but a variable
definition allocate required memory space for that variable. A variable declaration with an
initial value as shown below will become variable definition and required memory is
allocated for the variable.

int i = 100;

An extern declaration is not a definition and does not allocate storage. In effect, it claims that
a definition of the variable exists somewhere else in the program. A variable can be declared
multiple times in a program, but it must be defined only once. Following is the declaration of a
variable with extern keyword:

extern int i;

Variable Initialization in C

Variables are initialized (assigned an value) with an equal sign followed by a constant
expression. The general form of initialization is:

variable_name = value;

Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows:

type variable_name = value;

Some examples are:

int d = 3, f = 5; /* initializing d and f. */


byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */

It is a good programming practice to initialize variables properly otherwise, sometime program


would produce unexpected result. Try following example which makes use of various types of
variables:

#include <stdio.h>

int main ()
{
/* variable declaration: */
int a, b; int c; float f;
/* actual initialization */
a = 10;
b = 20;

c = a + b;
printf("value of c : %d \n", c);

f = 70.0/3.0;
printf("value of f : %f \n", f);

return 0;
}

When the above code is compiled and executed, it produces following result:

value of c : 30
value of f : 23.333334

Character constants
Character literals are enclosed in single quotes e.g., 'x' and can be stored in a simple
variable of char type.

A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a
universal character (e.g., '\u02C0').

There are certain characters in C when they are proceeded by a back slash 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 Meaning
sequence

\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\ooo Octal number of one to three digits
\xhh . . . Hexadecimal number of one or more digits
Following is the example to show few escape sequence characters:
#include <stdio.h>

int main()
{
printf("Hello\tWorld\n\n");

return 0;
}

When the above code is compiled and executed, it produces following result:

Hello World

String literals

String literals or constants are enclosed in double quotes "". A string contains characters
that are similar to character literals: plain characters, escape sequences, and universal
characters.

You can break a long lines into multiple lines using string literals and separating them using
whitespaces.

Here are some examples of string literals. All the three forms are identical strings.

"hello, dear"
"hello, \
dear"

"hello, " "d" "ear"


Defining Constants

There are two simple ways in C to define constants:

1. Using #define preprocessor.


2. Using const keyword.

The #define Preprocessor

Following is the form to use #define preprocessor to define a constant:

#define identifier value

Following example explains it in detail:

#include <stdio.h>

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

int main()
{
int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
printf("%c", NEWLINE);

return 0;
}

When the above code is compiled and executed, it produces following result:

value of area : 50

The const Keyword

You can use const prefix to declare constants with a specific type as follows:

const type variable = value;

Following example explains it in detail:

#include <stdio.h>

int main()
{
const int LENGTH = 10; const int WIDTH =
5; const char NEWLINE = '\n'; int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
printf("%c", NEWLINE);

return 0;
}

When the above code is compiled and executed, it produces following result:
value of area : 50

Note that it is a good programming practice to define constants in CAPITALS.


C Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C language is rich in built-in operators and provides the following types of
operators

 Arithmetic Operators

 Relational Operators

 Logical Operators

 Bitwise Operators

 Assignment Operators

 Misc Operators

Arithmetic Operators

Assume variable A holds 10 and variable B holds 20 then:

Operat Description Example


or
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after an B % A will give 0
++ integer division
Increment operator increases integer value by A++ will give 11
one
-- Decrement operator decreases integer value by A-- will give 9
one
Try following example to understand all the arithmetic operators available in C
programming language:

#include <stdio.h>

main()
{
int a = 21; int b = 10; int c ;

c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}

When you compile and execute the above program it produces following result:

Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22

Relational Operators

Following table shows all the relational operators supported by C language. Assume
variable A holds 10 and variable B holds 20 then:

Operator Description Example

== Checks if the value of two operands is equal or (A==B) is true


not, if yes then the condition becomes true
!= Checks if the value of two operands is equal or (A != B) is true.
not, if values are not equal then condition
becomes true.
> Checks if the value of left operand is greater than (A > B) is not true.
the value of right operand, if yes then condition
becomes true.
< Checks if the value of left operand is less than the (A < B) is true.
value of right operand, if yes then condition
becomes true
>= Checks if the value of left operand is greater than (A >= B) is not true.
or equal to the value of right operand, if yes then
condition becomes true.
<= Checks if the value of left operand is less than or (A <= B) is true.
equal to the value of right operand, if yes then
condition becomes true.

The following example shows how relational operators are used in C programming language:

#include <stdio.h>

main()
{
int a = 21; int b = 10; int c ;

if( a == b )
{
printf("Line 1 - a is equal to b\n" );
}
else
{
printf("Line 1 - a is not equal to b\n" );
}
if ( a < b )
{
printf("Line 2 - a is less than b\n" );
}
else
{
printf("Line 2 - a is not less than b\n" );
}
if ( a > b )
{
printf("Line 3 - a is greater than b\n" );
}
else
{
printf("Line 3 - a is not greater than b\n" );
}
/* Lets change value of a and b */
a = 5;
b = 20;
if ( a <= b )
{
printf("Line 4 - a is either less than or equal to b\n" );
}

if ( b >= a )
{
printf("Line 5 - b is either greater than or equal to b\n" );
}
}
When you compile and execute the above program it produces following result:

Line 1 - a is not equal to b Line 2 - a is not less

than b Line 3 - a is greater than b


Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b

Logical Operators

Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0 then:

Operator Description Example


&& Called Logical AND operator. If both the operands (A && B) is
are non zero then condition becomes true. false.
|| Called Logical OR Operator. If any of the two (A || B) is true.
operands is non zero then condition becomes
true.
Called Logical NOT Operator. Use to reverses the
! !(A && B) is
logical state of its operand. If a condition is true true.
then Logical NOT operator will make false.
Try following example to understand all the logical operators available in C programming
language:
#include <stdio.h>

main()
{
int a = 5; int b = 20; int c ;

if ( a && b )
{
printf("Line 1 - Condition is true\n" );
}
if ( a || b )
{
printf("Line 2 - Condition is true\n" );
}
/* lets change the value of a and b */

a = 0;
b = 10;
if ( a && b )
{
printf("Line 3 - Condition is true\n" );
}
else
{
printf("Line 3 - Condition is not true\n" );
}
if ( !(a && b) )
{
printf("Line 4 - Condition is true\n" );
}
}
When you compile and execute the above program it produces following result:
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true

Bitwise Operators

Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |,
and ^ are as follows:

p q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Assume if A = 60; and B = 13; Now in binary format they will be as follows: A =
0011 1100
B = 0000 1101
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

The Bitwise operators supported by C language are listed in the following table. Assume
variable A holds 60 and variable B holds 13 then:

Operat Description Example


or Binary AND Operator copies a bit to
& the result if it exists in both operands. (A & B) will give 12 which is
0000 1100

| Binary OR Operator copies a bit if (A | B) will give 61 which is


it exists in either operand. 0011 1101

^ Binary XOR Operator copies the bit if (A ^ B) will give 49 which is


0011 0001
it is set in one operand but not both.

~ Binary Ones Complement Operator is (~A ) will give -60 which is 1100
unary and has the effect of 'flipping' 0011
bits.

Binary Left Shift Operator. The left


<< operands value is moved left by A << 2 will give 240 which is
1111 0000
the number of bits specified by
the right operand.

Binary Right Shift Operator. The


>> left operands value is moved right A >> 2 will give 15 which is
by the number of bits specified by 0000 1111
the right operand.

Try following example to understand all the bitwise operators available in C programming
language:

#include <stdio.h>
main()
{

unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b =


13; /* 13 = 0000 1101 */ int c = 0;

c = a & b; /* 12 = 0000 1100 */


printf("Line 1 - Value of c is %d\n", c );

c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );

c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );

c = ~a; /*-61 = 1100 0011 */


printf("Line 4 - Value of c is %d\n", c );

c = a << 2; /* 240 = 1111 0000 */


printf("Line 5 - Value of c is %d\n", c );

c = a >> 2; /* 15 = 0000 1111 */


printf("Line 6 - Value of c is %d\n", c );
}
When you compile and execute the above program it produces following result:

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

Assignment Operators

There are following assignment operators supported by C language:

Operator Description Example

= Simple assignment operator, C = A + B will assign value


Assigns values from right side of A + B into C
operands to left side operand

Add AND assignment operator, It


+= C += A is equivalent to C = C +
adds right operand to the left A
operand and assign the result to
left operand

Subtract AND assignment


-= operator, It subtracts right C -= A is equivalent to C = C -
operand from the left operand A
and assign the result to left
operand

Multiply AND assignment


*= C *= A is equivalent to C = C *
operator, It multiplies right A
operand with the left operand
and assign the result to left
operand
Divide AND assignment
/= operator, It divides left operand C /= A is equivalent to C = C /
with the right operand and A
assign the result to left operand

Modulus AND assignment


%= C %= A is equivalent to C = C
operator, It takes modulus %A
using two operands and assign
the result to left operand
<<= Left shift AND assignment C <<= 2 is same as C = C << 2
operator
>>= Right shift AND assignment C >>= 2 is same as C = C >> 2
operator
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

^= bitwise exclusive OR and C ^= 2 is same as C = C ^ 2


assignment operator

|= bitwise inclusive OR and C |= 2 is same as C = C | 2


assignment operator

Try following example to understand all the assignment operators available in C


programming language:

#include <stdio.h>

main()
{
int a = 21;
int c ;

c = a;
printf("Line 1 - = Operator Example, Value of c = %d\n", c );

c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c );

c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c );

c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n", c );

c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c );

c = 200;
c %= a;
printf("Line 6 - %= Operator Example, Value of c = %d\n", c );

c <<= 2;
printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );

c >>= 2;
printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );

c &= 2;
printf("Line 9 - &= Operator Example, Value of c = %d\n", c );

c ^= 2;
printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );
c |= 2;
printf("Line 11 - |= Operator Example, Value of c = %d\n", c );
}

When you compile and execute the above program it produces following result:

Line 1 - = Operator Example, Value of c = 21

Line 2 - += Operator Example, Value of c = 42

Line 3 - -= Operator Example, Value of c = 21

Line 4 - *= Operator Example, Value of c = 441

Line 5 - /= Operator Example, Value of c = 21

Line 6 - %= Operator Example, Value of c = 11

Line 7 - <<= Operator Example, Value of c = 44

Line 8 - >>= Operator Example, Value of c = 11

Line 9 - &= Operator Example, Value of c = 2

Line 10 - ^= Operator Example, Value of c = 0

Line 11 - |= Operator Example, Value of c = 2

Misc Operators ↦sizeof & ternary

Operator Description Example

sizeof(a), where a is
sizeof() Returns the size of an variable. integer, will return 4.

&a; will give actual


& Returns the address of an variable. address of the variable.

* Pointer to a variable. *a; will pointer to a


variable.

If Condition is true ?
?: Conditional Expression
Then value X :
Otherwise value Y
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator:

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.

Here operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Category Operator Associativity


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
Use the below example to understand the operator precedence available in C
programming language:

#include <stdio.h>

main()
{
int a = 20; int b = 10;
int c = 15; int d = 5; int
e;

e = (a + b) * c / d; // ( 30 * 15 ) / 5 printf("Value of (a + b) * c /
d is : %d\n", e );

e = ((a + b) * c) / d; // (30 * 15 ) / 5 printf("Value of ((a + b) * c) / d is


: %d\n" , e );

e = (a + b) * (c / d); // (30) * (15/5)


printf("Value of (a + b) * (c / d) is : %d\n", e );

e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );

return 0;
}

When you compile and execute the above program it produces following result:

Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50

Decision Making in C
Decision making structures require that the programmer specify one or more conditions to
be evaluated or tested by the program, along with a statement or statements
to be executed if the condition is determined to be true, and optionally, other statements
to be executed if the condition is determined to be false.

Following is the general from of a typical decision making structure found in most of the
programming languages:
C programming language assumes any non-zero and non-null values as true and if it is
either zero or null then it is assumed as false value. C programming language provides
following types of decision making statements.

if statement

An if statement consists of a boolean expression followed by one or more statements.

Syntax

The syntax of an if statement in C programming language is:

if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}

If the boolean expression evaluates to true then the block of code inside the if statement
will be executed. If boolean expression evaluates to false then the first set of code after
the end of the if statement(after the closing curly brace) will be executed.

C programming language assumes any non-zero and non-null values as true and if it is
either zero or null then it is assumed as false value.

Flow Diagram
Example
#include <stdio.h>

int main ()
{
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);

return 0;
}

When the above code is compiled and executed, it produces following result:

a is less than 20;


value of a is : 10

if...else statement

An if statement can be followed by an optional else statement, which executes when the
boolean expression is false.

Syntax

The syntax of an if...else statement in C programming language is:

if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}

If the boolean expression evaluates to true then the if block of code will be executed
otherwise else block of code will be executed.

C programming language assumes any non-zero and non-null values as true and if it is
either zero or null then it is assumed as false value.

Flow Diagram

Example
#include <stdio.h>

int main ()
{
/* local variable definition */
int a = 100;

/* check the boolean condition */


if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
else
{
/* if condition is false then print the following */
printf("a is not less than 20\n" );
}
printf("value of a is : %d\n", a);

return 0;
}

When the above code is compiled and executed, it produces following result:

a is not less than 20;


value of a is : 100

The if...else if...else Statement

An if statement can be followed by an optional else if...else statement, which is very


useful to test various conditions using single if...else if statement.

When using if , else if , else statements there are few points to keep in mind. An if can have
zero or one else's and it must come after any else if's.

An if can have zero to many else if's and they must come before the else.

Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax

The syntax of an if...else if...else statement in C programming language is:

if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}

Example
#include <stdio.h>

int main ()
{
/* local variable definition */
int a = 100;

/* check the boolean condition */


if( a == 10 )
{
/* if condition is true then print the following */
printf("Value of a is 10\n" );
}
else if( a == 20 )
{
/* if else if condition is true */
printf("Value of a is 20\n" );
}
else if( a == 30 )
{
/* if else if condition is true */
printf("Value of a is 30\n" );
}
else
{
/* if none of the conditions is true */
printf("None of the values is matching\n" );
}
printf("Exact value of a is: %d\n", a );

return 0;
}

When the above code is compiled and executed, it produces following result:

None of the values is matching


Exact value of a is: 100

Nested if statements

It is always legal in C programming to nest if-else statements, which means you can use
one if or else if statement inside another if or else if statement(s).

Syntax

The syntax for a nested if statement is as follows:

if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}

You can nest else if...else in the similar way as you have nested if statement.

Example
#include <stdio.h>

int main ()
{
/* local variable definition */
int a = 100;
int b = 200;

/* check the boolean condition */

if( a == 100 )
{
/* if condition is true then check the following */
if( b == 200 )
{
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );

return 0;
}

When the above code is compiled and executed, it produces following result:

Value of a is 100 and b is 200


Exact value of a is : 100
Exact value of b is : 200

switch statement

A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each switch case.

Syntax

The syntax for a switch statement in C programming language is as follows:

switch(expression){
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}

The following rules apply to a switch statement:

 The expression used in a switch statement must have an integral or enumerated


type, or be of a class type in which the class has a single conversion function to an
integral or enumerated type.
 You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
 The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following
that case will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will
fall through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end
of the switch. The default case can be used for performing a task when none of the
cases is true. No break is needed in the default case.

Flow Diagram

Example
#include <stdio.h>

int main ()
{
/* local variable definition */
char grade = 'B';

switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break; case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );

return 0;
}

When the above code is compiled and executed, it produces following result:

Well done
Your grade is B

Nested switch statements

It is possible to have a switch as part of the statement sequence of an outer switch.


Even if the case constants of the inner and outer switch contain common values, no
conflicts will arise.

Syntax

The syntax for a nested switch statement is as follows:

switch(ch1) {
case 'A':
printf("This A is part of outer switch" );
switch(ch2) {
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* case code */
}
break;
case 'B': /* case code */
}
Example
#include <stdio.h>

int main ()
{
/* local variable definition */
int a = 100;
int b = 200;

switch(a) {
case 100:
printf("This is part of outer switch\n", a );
switch(b) {
case 200:
printf("This is part of inner switch\n", a );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );

return 0;
}
When the above code is compiled and executed, it produces following result:

This is part of outer switch This is part of

inner switch Exact value of a is : 100

Exact value of b is : 200

The ? : Operator

We have covered conditional operator ? : in previous chapter which can be used to


replace if...else statements. It has the following general form:

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then
Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then
Exp3 is evaluated and its value becomes the value of the expression.

You might also like