Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: c languange
Description: this is a c language

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


About The Tutorial
C is a general-purpose, procedural, imperative computer programming language
developed in 1972 by Dennis M
...

C is the most widely used computer language
...


Audience
This tutorial is designed for software programmers with a need to understand
the C programming language starting from scratch
...


Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of
Computer Programming terminologies
...


Copyright & Disclaimer
 Copyright 2014 by Tutorials Point (I) Pvt
...

All the content and graphics published in this e-book are the property of
Tutorials Point (I) Pvt
...
The user of this e-book is prohibited to reuse, retain,
copy, distribute or republish any contents or a part of contents of this e-book in
any manner without written consent of the publisher
...

Tutorials Point (I) Pvt
...
provides no guarantee regarding the accuracy,
timeliness or completeness of our website or its contents including this tutorial
...
com

i

Table of Contents
About The Tutorial
...
i
Prerequisites
...
i
Table of Contents
...
OVERVIEW
...
1
Why Use C?
...
2

2
...
3
Try it Option Online
...
3
Text Editor
...
4
Installation on UNIX/Linux
...
5
Installation on Windows
...
PROGRAM STRUCTURE
...
6
Compile and Execute C Program
...
BASIC SYNTAX
...
8
Semicolons
...
8
Identifiers
...
9
Whitespace in C
...
DATA TYPES
...
11
Floating-Point Types
...
14

6
...
15
Variable Definition in C
...
16
Lvalues and Rvalues in C
...
CONSTANTS AND LITERALS
...
19
Floating-point Literals
...
20
String Literals
...
22
The #define Preprocessor
...
23

8
...
24
The auto Storage Class
...
24
The static Storage Class
...
26

9
...
28
Arithmetic Operators
...
30

iii

Logical Operators
...
34
Assignment Operators
...
40
Operators Precedence in C
...
DECISION MAKING
...
46
if…else Statement
...
else if
...
49
Nested if Statements
...
53
Nested switch Statements
...
57

11
...
58
while Loop
...
61
do…while Loop
...
65
Loop Control Statements
...
68
continue Statement
...
72
The Infinite Loop
...
FUNCTIONS
...
76
Function Declarations
...
78
Function Arguments
...
80
Call by Reference
...
SCOPE RULES
...
84
Global Variables
...
86
Initializing Local and Global Variables
...
ARRAYS
...
89
Initializing Arrays
...
90
Arrays in Detail
...
92
Two-dimensional Arrays
...
93
Accessing Two-Dimensional Array Elements
...
94
Return Array from a Function
...
99

15
...
101
What are Pointers?
...
102
NULL Pointers
...
104
Pointer Arithmetic
...
105

v

Decrementing a Pointer
...
107
Array of Pointers
...
111
Passing Pointers to Functions
...
114

16
...
117
17
...
120
Defining a Structure
...
121
Structures as Function Arguments
...
124
Bit Fields
...
UNIONS
...
128
Accessing Union Members
...
BIT FIELDS
...
133

20
...
136
typedef vs #define
...
INPUT AND OUTPUT
...
139
The getchar() and putchar() Functions
...
140
The scanf() and printf() Functions
...
FILE I/O
...
143
Closing a File
...
144
Reading a File
...
146

23
...
147
Preprocessors Examples
...
148
Preprocessor Operators
...
150
The Stringize (#) Operator
...
150
The Defined() Operator
...
152

24
...
153
Include Syntax
...
153
Once-Only Headers
...
155

25
...
156
Integer Promotion
...
157

26
...
160
errno, perror(), and strerror()
...
161
Program Exit Status
...
RECURSION
...
164
Fibonacci Series
...
VARIABLE ARGUMENTS
...
MEMORY MANAGEMENT
...
170
Resizing and Releasing Memory
...
COMMAND LINE ARGUMENTS
...
OVERVIEW

C Programming

C is a general-purpose, high-level language that was originally developed by
Dennis M
...
C was
originally first implemented on the DEC PDP-11 computer in 1972
...

The UNIX operating system, the C compiler, and essentially all UNIX application
programs have been written in C
...




C is a successor of B language which was introduced around the early
1970s
...




The UNIX OS was totally written in C
...




Most of the state-of-the-art software have been implemented using C
...


Why Use C?
C was initially used for system development work, particularly the programs that
make-up the operating system
...
Some examples of the use of C might be:


Operating Systems
1

C Programming


Language Compilers



Assemblers



Text Editors



Print Spoolers



Network Drivers



Modern Programs



Databases



Language Interpreters



Utilities

C Programs
A C program can vary from 3 lines to millions of lines and it should be written
into one or more text files with extension "
...
c
...

This tutorial assumes that you know how to edit a text file and how to write
source code inside a program file
...
ENVIORNMENT SETUP

Try it Option Online
You really do not need to set up your own environment to start learning C
programming language
...
This gives you confidence in what you are reading and to check the result
with different options
...

Try following example using
http://www
...
com/
...
h>

int main()
{
/* my first program in C */
printf("Hello, World! \n");

return 0;
}
For most of the examples given in this tutorial, you will find the Try it option in
our website code sections at the top right corner that will take you to the online
compiler
...


Local Environment Setup
If you want to set up your environment for C programming language, you need
the following two software tools available on your computer, (a) Text Editor and
(b) The C Compiler
...
Examples of a few editors include
Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi
...

For example, Notepad will be used on Windows, and vim or vi can be used on
Windows as well as on Linux or UNIX
...
The source files for C programs are typically named
with the extension "
...

Before starting your programming, make sure you have one text editor in place
and you have enough experience to write a computer program, save it in a file,
compile it and finally execute it
...
It needs to be "compiled" into machine language so that your CPU can
actually execute the program as per the instructions given
...
The
most frequently used and free available compiler is the GNU C/C++ compiler,
otherwise you can have compilers either from HP or Solaris if you have the
respective operating systems
...

m We keep mentioning C/C++ together because GNU gcc compiler works for
both C and C++ programming languages
...

Target: i386-redhat-linux
Configured with:
...

Thread model: posix
gcc version 4
...
2 20080704 (Red Hat 4
...
2-46)
If GCC is not installed, then you will have to install it yourself using the detailed
instructions available at http://gcc
...
org/install/
...


4

C Programming

Installation on Mac OS
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode
development environment from Apple's web site and follow the simple
installation instructions
...

Xcode is currently available at developer
...
com/technologies/tools/
...
To install MinGW, go to
the MinGW homepage, www
...
org, and follow the link to the MinGW
download page
...
exe
...

Add the bin subdirectory of your MinGW installation to your PATH environment
variable, so that you can specify these tools on the command line by their simple
names
...


5

C Programming

3
...


Hello World Example
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":
#include ...
The first line of the program #include ...
h file before going to
actual compilation
...
The next line int main() is the main function where the program execution
begins
...
The next line /*
...
So such lines are called
comments in the program
...
The next line printf(
...

5
...


Compile and Execute C Program
Let us see how to save the source code in a file, and how to compile and run it
...
Open a text editor and add the above-mentioned code
...
Save the file as hello
...
Open a command prompt and go to the directory where you have saved
the file
...
Type gcc hello
...

5
...
out executable file
...
Now, type a
...

7
...

$ gcc hello
...
/a
...
c
...
BASIC SYNTAX

C Programming

You have seen the basic structure of a C program, so it will be easy to
understand other basic building blocks of the C programming language
...
For example, the following C
statement consists of five tokens:
printf("Hello, World! \n");
The individual tokens are:
printf
(
"Hello, World! \n"
)
;

Semicolons
In a C program, the semicolon is a statement terminator
...
It indicates the end of one logical
entity
...
They start with /* and terminate with the characters */ as shown
below:
/* my first program in C */

8

C Programming
You cannot have comments within comments and they do not occur within a
string or character literals
...
An identifier starts with a letter A to Z, a to z, or an underscore ‘_’
followed by zero or more letters, underscores, and digits (0 to 9)
...

C is a case-sensitive programming language
...
Here are some examples of acceptable
identifiers:
mohd

zara

abc

move_name

a_123

myname50

_temp

j

a23b9

retVal

Keywords
The following list shows the reserved words in C
...

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

9

C Programming

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 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
...
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 to increase readability
...
DATA TYPES

C Programming

Data types in C refer to an extensive system used for declaring variables or
functions of different types
...

The types in C can be classified as follows:
S
...


Types and Description

1

Basic Types:
They are arithmetic types and are further classified into: (a) integer
types and (b) floating-point types
...


3

The type void:
The type specifier void indicates that no value is available
...


The array types and structure types are referred collectively as the aggregate
types
...
We
will see the basic types in the following section, whereas other types will be
covered in the upcoming chapters
...
The expressions sizeof(type) yields the storage size of
the object or type in bytes
...
h>
#include ...
2E-38 to 3
...
3E-308 to 1
...
4E-4932 to 1
...
h defines macros that allow you to use these values and
other details about the binary representation of real numbers in your programs
...
h>
#include ...
175494E-38
Maximum float positive value: 3
...
It is used in three kinds of
situations:
S
...


Types and Description

1

Function returns as void
There are various functions in C which do not return any value or you
can say they return void
...
For example, void exit (int status);

2

Function arguments as void
There are various functions in C which do not accept any parameter
...
For example, int
rand(void);

3

Pointers to void
A pointer of type void * represents the address of an object, but not its
type
...


14

6
...
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
...
It must begin with either a letter or an underscore
...
Based on the basic
types explained in the previous chapter, there will be the following basic variable
types:
Type

Description

char

Typically a single octet (one byte)
...


int

The most natural size of integer for the machine
...


double

A double-precision floating point value
...


C programming language also allows to define various other types of variables,
which we will cover in subsequent chapters like Enumeration, Pointer, Array,
Structure, Union, etc
...


Variable Definition in C
A variable definition tells the compiler where and how much storage to create for
the variable
...
Some valid declarations are shown here:
int

i, j, k;

char

c, ch;

float

f, salary;

double d;
The line int i, j, k; declares and defines the variables i, j and k; which instruct
the compiler to create variables named i, j, and k of type int
...
The
initializer consists of an equal sign followed by a constant expression as follows:
type variable_name = value;
Some examples are:
extern int d = 3, f = 5;

// declaration of d and f
...


byte z = 22;

// definition and initializes z
...


For definition without an initializer: variables with static storage duration are
implicitly initialized with NULL (all bytes have the value 0); the initial value of all
other variables are undefined
...
A
variable declaration has its meaning at the time of compilation only, the
compiler needs actual variable declaration at the time of linking the program
...
You will use the keyword extern to declare a variable at any place
...


Example
Try the following example, where variables have been declared at the top, but
they have been defined and initialized inside the main function:

16

C Programming

#include ...
0/3
...
333334
The same concept applies on function declaration where you provide a function
name at the time of its declaration and its actual definition can be given
anywhere else
...
An lvalue may appear as either the left-hand or right-hand
side of an assignment
...
An rvalue is an expression that cannot have a value
assigned to it which means an rvalue may appear on the right-hand side
but not on the left-hand side of an assignment
...
Numeric literals are rvalues and so they may not be assigned and
cannot appear on the left-hand side
...
CONSTANTS AND LITERALS

Constants refer to fixed values that the program may not alter during its
execution
...

Constants can be of any of the basic data types like an integer constant, a
floating constant, a character constant, or a string literal
...

Constants are treated just like regular variables except that their values cannot
be modified after their definition
...
A prefix
specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for
decimal
...
The suffix can be uppercase or lowercase and
can be in any order
...
You can represent floating point literals either in decimal form
or exponential form
...
The signed exponent is introduced
by e or E
...
14159

/* Legal */

314159E-5L

/* Legal */

510E

/* Illegal: incomplete exponent */

210f

/* Illegal: no decimal or exponent */


...
g
...

A character literal can be a plain character (e
...
, 'x'), an escape sequence (e
...
,
'\t'), or a universal character (e
...
, '\u02C0')
...
Here, you have a list of
such escape sequence codes:
Escape
sequence

Meaning

\\

\ character

\'

' character

\"

" character

\?

? character

\a

Alert or bell
20

C Programming

\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
...
h>

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

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

World

String Literals
String literals or constants are enclosed in double quotes ""
...

21

C Programming
You can break a long line into multiple lines using string literals and separating
them using whitespaces
...
All the three forms are identical
strings
...
h>

#define LENGTH 10
#define WIDTH

5

#define NEWLINE '\n'

int main()
{

int area;

area = LENGTH * WIDTH;
22

C Programming

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

return 0;
}
When the above code is compiled and executed, it produces the 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;
The following example explains it in detail:
#include ...


23

C Programming

8
...
They precede the type that they modify
...

{
int mount;
auto int month;
}
The example above defines two variables within the same storage class
...
e
...


The register Storage Class
The register storage class is used to define local variables that should be stored
in a register instead of RAM
...

{
register int

miles;

}
The register should only be used for variables that require quick access such as
counters
...
It means that it MIGHT be stored in a
register depending on hardware and implementation restrictions
...
Therefore, making local
variables static allows them to maintain their values between function calls
...
When this is done, it
causes that variable's scope to be restricted to the file in which it is declared
...

#include ...
When you use 'extern', the variable cannot be
initialized, however, it points the variable name at a storage location that has
been previously defined
...
Just for understanding, extern is
used to declare a global variable or function in another file
...


First File: main
...
h>

int count;
extern void write_extern();

main()
{
count = 5;
write_extern();
}

Second File: support
...
h>

extern int count;

void write_extern(void)
{
26

C Programming

printf("count is %d\n", count);
}
Here, extern is being used to declare count in the second file, whereas it has its
definition in the first file, main
...
Now, compile these two files as follows:
$gcc main
...
c
It will produce the executable program a
...
When this program is executed, it
produces the following result:
5

27

9
...
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

We will, in this chapter, look into the way each operator works
...
Assume variable A holds 10 and variable B holds 20, then:
Operator

Description

Example

+

Adds two operands
...


A - B = -10

*

Multiplies both operands
...


B/A=2

%

Modulus Operator and remainder of after an
integer division
...


A++ = 11

28

C Programming

--

Decrement operator
value by one
...
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 the following
result:
Line 1 - Value of c is 31
29

C Programming

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
The following table shows all the relational operators supported by C
...
If yes, then the condition becomes
true
...


!=

Checks if the values of two operands are equal
or not
...


(A != B) is true
...
If yes, then
the condition becomes true
...


<

Checks if the value of left operand is less than
the value of right operand
...


(A < B) is true
...
If
yes, then the condition becomes true
...


<=

Checks if the value of left operand is less than
or equal to the value of right operand
...


(A <= B) is true
...
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
31

C Programming

{
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 the 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
Line 5 - b is either greater than

b

or equal to b

Logical Operators
Following table shows all the logical operators supported by C language
...
If both the
operands are non-zero, then the condition
becomes true
...


||

Called Logical OR Operator
...


B)

is

32

C Programming

operands is non-zero,
becomes true
...
It is used to
reverse the logical state of its operand
...


!(A &&
true
...
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" );
}
33

C Programming

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 the 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 operators work on bits and perform bit-by-bit operation
...
Assume variable
‘A’ holds 60 and variable ‘B’ holds 13, then:
Operator

Description

Example

&

Binary AND Operator copies a bit to the result
if it exists in both operands
...
e
...


(A | B) = 61, i
...
,
0011 1101

^

Binary XOR Operator copies the bit if it is set
in one operand but not both
...
e
...


(~A ) = -61, i
...
,
1100 0011 in 2's
complement form
...
The left operands
value is moved left by the number of bits
specified by the right operand
...
e
...
The left operands
value is moved right by the number of bits
specified by the right operand
...
e
...
h>

main()
35

C Programming

{

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 the 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

36

C Programming

Assignment Operators
The following tables lists the assignment operators supported by the C language:
Operator

Description

Example

=

Simple assignment operator
...


C = A + B will assign
the value of A + B to
C

+=

Add AND assignment operator
...


C += A is equivalent
to C = C + A

-=

Subtract AND assignment operator
...


C -= A is equivalent
to C = C - A

*=

Multiply AND assignment operator
...


C *= A is equivalent
to C = C * A

/=

Divide AND assignment operator
...


C /= A is equivalent
to C = C / A

%=

Modulus AND assignment operator
...


C %= A is equivalent
to C = C % A

<<=

Left shift AND assignment operator
...


C >>= 2 is same as C
= C >> 2

&=

Bitwise AND assignment operator
...


OR

and

assignment

C ^= 2 is same as C
=C^2

|=

Bitwise inclusive
operator
...
h>

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

c =

a;

printf("Line 1 - =

c +=

Operator Example, Value of c = %d\n", 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 );

38

C Programming

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 the 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
39

C Programming

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
Besides the operators discussed above, there are a few other important
operators including sizeof and ? : supported by the C Language
...


sizeof(a), where a is
integer, will return 4
...


&a; returns the actual
address
of
the
variable
...


*a;

?:

Conditional Expression
...
h>

main()
{
int a = 4;
short b;
double c;
int* ptr;

/* example of sizeof operator */
40

C Programming

printf("Line 1 - Size of variable a = %d\n", sizeof(a) );
printf("Line 2 - Size of variable b = %d\n", sizeof(b) );
printf("Line 3 - Size of variable c= %d\n", sizeof(c) );

/* example of & and * operators */
ptr = &a;

/* 'ptr' now contains the address of 'a'*/

printf("value of a is

%d\n", a);

printf("*ptr is %d
...

Value of b is 30
Value of b is 20

Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and
decides how an expression is evaluated
...

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator *
has a higher precedence than +, so it first gets multiplied with 3*2 and then
adds into 7
...
Within an expression, higher
precedence operators will be evaluated first
...
++ - -

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

Example
42

C Programming
Try the following example to understand operator precedence in C:
#include ...
DECISION MAKING

Decision-making structures require that the programmer specifies 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
...

C programming language provides the following types of decision-making
statements
...


if
...

nested if statements

You can use one if or else if statement inside
another if or else if statement(s)
...


nested switch statements

You can use one switch statement inside another
switch statement(s)
...


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

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
...
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 the following result:
a is less than 20;
47

C Programming

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
...
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 will be executed,
otherwise, the else block will be executed
...


Flow Diagram

48

C Programming

Example
#include ...
else if
...
else statement, which is
very useful to test various conditions using single if
...

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

49

C Programming


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

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

/* check the boolean condition */
if( a == 10 )
{
/* if condition is true then print the following */
50

C Programming

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 the 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)
...
else in the similar way as you have nested if statements
...
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 the following result:
52

C Programming

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


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
...
Each case is
followed by the value to be compared to and a colon
...




When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached
...

53

C Programming


Not every case needs to contain a break
...




A switch statement can have an optional default case, which must
appear at the end of the switch
...
No break is needed in
the default case
...
h>

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

switch(grade)
{
case 'A' :
54

C Programming

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 the following result:
Well done
Your grade is B

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


Syntax
The syntax for a nested switch statement is as follows:
switch(ch1) {
case 'A':
printf("This A is part of outer switch" );

55

C Programming

switch(ch2) {
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* case code */
}
break;
case 'B': /* case code */
}

Example
#include ...
else statements
...
Notice the use and placement of
the colon
...
Exp1 is evaluated
...

2
...


57

11
...
In general, statements are executed sequentially: The
first statement in a function is executed first, followed by the second, and so on
...

A loop statement allows us to execute a statement or group of statements
multiple times
...

Loop Type

Description

while loop

Repeats a statement or group of statements while a
given condition is true
...


for loop

Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable
...
while loop

It is more like a while statement, except that it tests
the condition at the end of the loop body
...
while loop
...


Syntax
The syntax of a while loop in C programming language is:
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements
...
The loop
iterates while the condition is true
...


Flow Diagram

59

C Programming

Here, the key point to note is that a while loop might not execute at all
...


Example
#include ...


Syntax
The syntax of a for loop in C programming language is:
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a ‘for’ loop:
1
...
This step allows you to
declare and initialize any loop control variables
...

2
...
If it is true, the body of the loop is
executed
...

3
...
This statement allows you to update any
loop control variables
...

61

C Programming
4
...
If it is true, the loop executes and
the process repeats itself (body of loop, then increment step, and then
again condition)
...


Flow Diagram

Example
#include ...
while loop in C programming checks its condition at the bottom of the
loop
...
while loop is similar to a while loop, except the fact that it is guaranteed
to execute at least one time
...
while loop in C programming language is:
do
{
statement(s);

}while( condition );
Notice that the conditional expression appears at the end of the loop, so the
statement(s) in the loop executes once before the condition is tested
...
This process repeats until the given
condition becomes false
...
h>

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

/* do loop execution */
do
{
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );

return 0;

64

C Programming

}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Nested Loops
C programming allows to use one loop inside another loop
...


Syntax
The syntax for a nested for loop statement in C is as follows:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C programming language is as
follows:
while(condition)
{
while(condition)
{
65

C Programming

statement(s);
}
statement(s);
}
The syntax for a nested do
...
For example, a ‘for’ loop can be inside a ‘while’ loop or vice versa
...
h>

int main ()
{
/* local variable definition */
int i, j;

for(i=2; i<100; i++) {
for(j=2; j <= (i/j); j++)
if(!(i%j)) break;

// if factor found, not prime

if(j > (i/j)) printf("%d is prime\n", i);
}

66

C Programming

return 0;
}
When the above code is compiled and executed, it produces the following result:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime

Loop Control Statements
Loop control statements change execution from its normal sequence
...

67

C Programming
C supports the following control statements
...


continue statement

Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating
...


break Statement
The break statement in C programming has the following two usages:


When a break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop
...


If you are using nested loops, the break statement will stop the execution of the
innermost loop and start executing the next line of code after the block
...
h>

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

/* while loop execution */
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
/* terminate the loop using break statement */
break;
}
}

69

C Programming

return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

continue Statement
The continue statement in C programming works somewhat like the break
statement
...

For the for loop, continue statement causes the conditional test and increment
portions of the loop to execute
...
while loops, continue
statement causes the program control to pass to the conditional tests
...
h>

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

/* do loop execution */
do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;

71

C Programming

}while( a < 20 );

return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

goto Statement
A goto statement in C programming provides an unconditional jump from the
‘goto’ to a labeled statement in the same function
...
Any program that
uses a goto can be rewritten to avoid them
...


...


72

C Programming

Flow Diagram

Example
#include ...
The for loop
is traditionally used for this purpose
...

#include ...
\n");
}

return 0;
}

74

C Programming
When the conditional expression is absent, it is assumed to be true
...

NOTE: You can terminate an infinite loop by pressing Ctrl + C keys
...
FUNCTIONS

C Programming

A function is a group of statements that together perform a task
...

You can divide up your code into separate functions
...

A function declaration tells the compiler about a function's name, return type,
and parameters
...

The C standard library provides numerous built-in functions that your program
can call
...

A function can also be referred as a method or a sub-routine or a procedure, etc
...
Here are all the parts of a function:


Return Type: A function may return a value
...
Some functions perform the
desired operations without returning a value
...




Function Name: This is the actual name of the function
...




Parameters: A parameter is like a placeholder
...
This value is referred to as
actual parameter or argument
...
Parameters are
optional; that is, a function may contain no parameters
...


Example
Given below is the source code for a function called max()
...
The actual body of the function can be defined separately
...
In such case, you should declare the
function at the top of the file calling the function
...

To use a function, you will have to call that function to perform the defined task
...
A called function performs a defined task and when its return
statement is executed or when its function-ending closing brace is reached, it
returns the program control back to the main program
...
For example:
#include ...
While
running the final executable, it would produce the following result:
Max value is : 200

Function Arguments
If a function is to use arguments, it must declare variables that accept the
values of the arguments
...

Formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit
...
In this case,
changes made to the parameter inside the function
have no effect on the argument
...
Inside the function, the address
is used to access the actual argument used in the call
...


79

C Programming

Call by Value
The call by value method of passing arguments to a function copies the actual
value of an argument into the formal parameter of the function
...

By default, C programming uses call by value to pass arguments
...
Consider the function swap() definition as follows
...
h>

/* function declaration */
void swap(int x, int y);

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

printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
80

C Programming

/* calling a function to swap the values */
swap(a, b);

printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );

return 0;
}
Let us put the above code in a single C file, compile and execute it, it will
produce the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there are no changes in the values, though they had been changed
inside the function
...
Inside the function, the
address is used to access the actual argument used in the call
...

To pass a value by reference, argument pointers are passed to the functions just
like any other value
...

/* function definition to swap the values */
void swap(int *x, int *y)
{
int temp;
temp = *x;

/* save the value at address x */

*x = *y;

/* put y into x */
81

C Programming

*y = temp;

/* put temp into y */

return;
}
Let us now call the function swap() by passing values by reference as in the
following example:
#include ...

* &a indicates pointer to a i
...
address of variable a and
* &b indicates pointer to b i
...
address of variable b
...

By default, C uses call by value to pass arguments
...


83

13
...
There are
three places where variables can be declared in C programming language:


Inside a function or a block which is called local variables,



Outside of all functions which is called global variables
...


Let us understand what are local and global variables, and formal parameters
...

They can be used only by statements that are inside that function or block of
code
...
The following
example shows how local variables are used
...

#include ...

Global variables hold their values throughout the lifetime of your program and
they can be accessed inside any of the functions defined for the program
...
That is, a global variable is
available for use throughout your entire program after its declaration
...

#include ...
Here is an example:
#include ...
Following is an example:
#include ...
Global variables are initialized automatically by the system
when you define them, as follows:
Data Type

Initial Default Value

int

0

char

'\0'

float

0

double

0

87

C Programming

pointer

NULL

It is a good programming practice to initialize variables properly, otherwise your
program may produce unexpected results, because uninitialized variables will
take some garbage value already available at their memory location
...
ARRAYS

C Programming

Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type
...

Instead of declaring individual variables, such as number0, number1,
...
, numbers[99] to represent individual variables
...

All arrays consist of contiguous memory locations
...


Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and
the number of elements required by an array as follows:
type arrayName [ arraySize ];
This is called a single-dimensional array
...
For example,
to declare a 10-element array called balance of type double, use this statement:
double balance[10];
Here, balance is a variable array which is sufficient to hold up to 10 double
numbers
...
0, 2
...
4, 7
...
0};

89

C Programming
The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ]
...
Therefore, if you write:
double balance[] = {1000
...
0, 3
...
0, 50
...

Following is an example to assign a single element of the array:
balance[4] = 50
...
0
...

Shown below is the pictorial representation of the array we discussed above:

Accessing Array Elements
An element is accessed by indexing the array name
...
For
example:
double salary = balance[9];
The above statement will take the 10th element from the array and assign the
value to salary variable
...
declaration, assignment, and accessing arrays:
#include ...
The following
important concepts related to array should be clear to a C programmer:
Concept

Description

Multidimensional arrays

C supports multidimensional arrays
...


Passing arrays to functions

You can pass to the function a pointer to an
91

C Programming

array by specifying the array's name without an
index
...


Pointer to an array

You can generate a pointer to the first element
of an array by simply specifying the array
name, without any index
...
Here is the general
form of a multidimensional array declaration:
type name[size1][size2]
...
A
two-dimensional array is, in essence, a list of one-dimensional arrays
...
A two-dimensional array can be considered as a table which will have
x number of rows and y number of columns
...

92

C Programming

Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for
each row
...

int a[3][4] = {
{0, 1, 2, 3} ,

/*

initializers for row indexed by 0 */

{4, 5, 6, 7} ,

/*

initializers for row indexed by 1 */

{8, 9, 10, 11}

/*

initializers for row indexed by 2 */

};
The nested braces, which indicate the intended row, are optional
...
e
...
For example:
int val = a[2][3];
The above statement will take the 4th element from the 3rd row of the array
...
Let us check the following program where
we have used a nested loop to handle a two-dimensional array:
#include ...


Passing Arrays to Functions
If you want to pass a single-dimension array as an argument in a function, you
would have to declare a formal parameter in one of following three ways and all
three declaration methods produce similar results because each tells the
compiler that an integer pointer is going to be received
...


Way-1
Formal parameters as a pointer:
void myFunction(int *param)
{

...


...


...

}

Way-3
Formal parameters as an unsized array:
void myFunction(int param[])
{

...


...
h>

/* function declaration */
double getAverage(int arr[], int size);

int main ()
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;

/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;

/* output the returned value */
printf( "Average value is: %f ", avg );

return 0;
}
When the above code is compiled together and executed, it produces the
following result:
Average value is: 214
...


Return Array from a Function
C programming does not allow to return an entire array as an argument to a
function
...

96

C Programming
If you want to return a single-dimension array from a function, you would have
to declare a function returning a pointer as in the following example:
int * myFunction()
{

...


...

Now, consider the following function which will generate 10 random numbers
and return them using an array and call this function as follows:
#include ...

Assuming you have some understanding of pointers in C, let us start: An array
name is a constant pointer to the first element of the array
...
Thus, the following program fragment assigns p as the
address of the first element of balance:
double *p;
double balance[10];

p = balance;
It is legal to use array names as constant pointers, and vice versa
...

Once you store the address of the first element in ‘p’, you can access the array
elements using *p, *(p+1), *(p+2), and so on
...
h>

int main ()
{
/* an array with 5 elements */
double balance[5] = {1000
...
0, 3
...
0, 50
...
000000
*(p + 1) : 2
...
400000
*(p + 3) : 17
...
000000
Array values using balance as address
*(balance + 0) : 1000
...
000000
*(balance + 2) : 3
...
000000
*(balance + 4) : 50
...
Once we have the address in p, *p will give
us the value available at the address stored in p, as we have shown in the above
example
...
POINTERS

C Programming

Pointers in C are easy and fun to learn
...
So it becomes necessary
to learn pointers to become a perfect C programmer
...

As you know, every variable is a memory location and every memory location
has its address defined which can be accessed using ampersand (&) operator,
which denotes an address in memory
...
h>

int main ()
{
int

var1;

char var2[10];

printf("Address of var1 variable: %x\n", &var1

);

printf("Address of var2 variable: %x\n", &var2

);

return 0;
}
When the above code is compiled and executed, it produces the following result:
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6

What are Pointers?
A pointer is a variable whose value is the address of another variable, i
...
,
direct address of the memory location
...
The general form
of a pointer variable declaration is:
101

C Programming

type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and varname is the name of the pointer variable
...
However, in this statement,
the asterisk is being used to designate a variable as a pointer
...
The only difference between pointers of different data types
is the data type of the variable or constant that the pointer points to
...
(a) We define a pointer variable, (b) assign the address of a
variable to a pointer, and (c) finally access the value at the address available in
the pointer variable
...
The
following example makes use of these operations:
#include ...
This is done at the time of
variable declaration
...

The NULL pointer is a constant with a value of zero defined in several standard
libraries
...
h>

int main ()
{
int

*ptr = NULL;

printf("The value of ptr is : %x\n", ptr

);

return 0;
}
When the above code is compiled and executed, it produces the following result:
The value of ptr is 0
In most of the operating systems, programs are not permitted to access
memory at address 0 because that memory is reserved by the operating system
...
But by
103

C Programming
convention, if a pointer contains the null (zero) value, it is assumed to point to
nothing
...
The following important pointer concepts should be clear to any C
programmer:
Concept

Description

Pointer arithmetic

There are four arithmetic operators that
can be used in pointers: ++, --, +, -

Array of pointers

You can define arrays to hold a number of
pointers
...


Passing pointers to functions in C

Passing an argument by reference or by
address enable the passed argument to be
changed in the calling function by the
called function
...


Pointer Arithmetic
A pointer in C is an address, which is a numeric value
...

There are four arithmetic operators that can be used on pointers: ++, --, +, and
-

104

C Programming
To understand pointer arithmetic, let us consider that ptr is an integer pointer
which points to the address 1000
...
This operation will move the pointer to the next
memory location without impacting the actual value at the memory location
...


Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the
variable pointer can be incremented, unlike the array name which cannot be
incremented because it is a constant pointer
...
h>

const int MAX = 3;

int main ()
{
int

var[] = {10, 100, 200};

int

i, *ptr;

/* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++)
{

printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );

/* move to the next location */
ptr++;
}
105

C Programming

return 0;
}
When the above code is compiled and executed, it produces the following result:
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200

Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its
value by the number of bytes of its data type as shown below:
#include ...

If p1 and p2 point to variables that are related to each other, such as elements
of the same array, then p1 and p2 can be meaningfully compared
...
h>

const int MAX = 3;

int main ()
{
int

var[] = {10, 100, 200};

int

i, *ptr;

/* let us have address of the first element in pointer */
ptr = var;
i = 0;
while ( ptr <= &var[MAX - 1] )
{

107

C Programming

printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );

/* point to the previous location */
ptr++;
i++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Address of var[0] = bfdbcb20
Value of var[0] = 10
Address of var[1] = bfdbcb24
Value of var[1] = 100
Address of var[2] = bfdbcb28
Value of var[2] = 200

Array of Pointers
Before we understand the concept of arrays of pointers, let us consider the
following example, which uses an array of 3 integers:
#include ...
Following is the
declaration of an array of pointers to an integer:
int *ptr[MAX];
It declares ptr as an array of MAX integer pointers
...
The following example uses three integers, which
are stored in an array of pointers, as follows:
#include ...
*/
}
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;

109

C Programming

}
When the above code is compiled and executed, it produces the following result:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
You can also use an array of pointers to character to store a list of strings as
follows:
#include ...

Normally, a pointer contains the address of a variable
...


A variable that is a pointer to a pointer must be declared as such
...
For example, the following
declaration declares a pointer to a pointer of type int:
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing
that value requires that the asterisk operator be applied twice, as is shown
below in the example:
#include ...
To do so, simply declare
the function parameter as a pointer type
...
h>
#include ...
h>

/* function declaration */
double getAverage(int *arr, int size);

int main ()
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;

/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;

/* output the returned value

*/

printf("Average value is: %f\n", avg );

return 0;
}

double getAverage(int *arr, int size)
{
int

i, sum = 0;

double avg;
113

C Programming

for (i = 0; i < size; ++i)
{
sum += arr[i];
}

avg = (double)sum / size;

return avg;
}
When the above code is compiled together and executed, it produces the
following result:
Average value is: 214
...
Similarly, C also allows to return a pointer from a function
...


...

}
Second point to remember is that, it is not a good idea to return the address of
a local variable outside the function, so you would have to define the local
variable as static variable
...
e
...

#include ...
h>

114

C Programming

/* function to generate and retrun random numbers
...
STRINGS

C Programming

Strings are actually one-dimensional array of characters terminated by
a null character '\0'
...

The following declaration and initialization create a string consisting of the word
"Hello"
...
"
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization, then you can write the above
statement as follows:
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C/C++:

Actually, you do not place the null character at the end of a string constant
...
Let us try to print the above mentioned string:
#include ...
N
...


2

strcat(s1, s2);
Concatenates string s2 onto the end of string s1
...


4

strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s10 if s1>s2
...


6

strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1
...
h>
#include ...
STRUCTURES

C Programming

Arrays allow to define type of variables that can hold several data items of the
same kind
...

Structures are used to represent a record
...
You might want to track the following attributes about
each book:


Title



Author



Subject



Book ID

Defining a Structure
To define a structure, you must use the struct statement
...
The format of the struct
statement is as follows:
struct [structure tag]
{
member definition;
member definition;

...
At the
end of the structure's definition, before the final semicolon, you can specify one
or more structure variables but it is optional
...
The member access operator is coded as a period between the structure
variable name and the structure member that we wish to access
...
The following
example shows how to use a structure in a program:
#include ...
h>

struct Books
{
char

title[50];

char

author[50];

char

subject[100];

int

book_id;

};

int main( )
{
struct Books Book1;

/* Declare Book1 of type Book */

struct Books Book2;

/* Declare Book2 of type Book */

/* book 1 specification */
strcpy( Book1
...
author, "Nuha Ali");
strcpy( Book1
...
book_id = 6495407;

/* book 2 specification */
strcpy( Book2
...
author, "Zara Ali");
strcpy( Book2
...
book_id = 6495700;

/* print Book1 info */
printf( "Book 1 title : %s\n", Book1
...
author);
printf( "Book 1 subject : %s\n", Book1
...
book_id);

/* print Book2 info */
printf( "Book 2 title : %s\n", Book2
...
author);
printf( "Book 2 subject : %s\n", Book2
...
book_id);

return 0;
}
When the above code is compiled and executed, it produces the following result:
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

Structures as Function Arguments
You can pass a structure as a function argument in the same way as you pass
any other variable or pointer
...
h>
122

C Programming

#include ...
title, "C Programming");
strcpy( Book1
...
subject, "C Programming Tutorial");
Book1
...
title, "Telecom Billing");
strcpy( Book2
...
subject, "Telecom Billing Tutorial");
Book2
...
title);
printf( "Book author : %s\n", book
...
subject);
printf( "Book book_id : %d\n", book
...
To find the address of a structure variable, place the ‘&’
operator before the structure's name as follows:
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must
use the -> operator as follows:
struct_pointer->title;
124

C Programming
Let us rewrite the above example using structure pointer
...
h>
#include ...
title, "C Programming");
strcpy( Book1
...
subject, "C Programming Tutorial");
Book1
...
title, "Telecom Billing");
strcpy( Book2
...
subject, "Telecom Billing Tutorial");
Book2
...
This is especially useful when
memory or data storage is at a premium
...
g
...




Reading external file formats -- non-standard file formats could be read
in, e
...
, 9-bit integers
...
For example:
struct packed_struct {

126

C Programming

unsigned int f1:1;
unsigned int f2:1;
unsigned int f3:1;
unsigned int f4:1;
unsigned int type:4;
unsigned int my_int:9;
} pack;
Here, the packed_struct contains 6 members: Four 1 bit flags f1
...

C automatically packs the above bit fields as compactly as possible, provided
that the maximum length of the field is less than or equal to the integer word
length of the computer
...


127

18
...
You can define a union with many
members, but only one member can contain a value at any given time
...


Defining a Union
To define a union, you must use the union statement in the same way as you
did while defining a structure
...
The format of the union statement is
as follows:
union [union tag]
{
member definition;
member definition;

...
At the
end of the union's definition, before the final semicolon, you can specify one or
more union variables, but it is optional
...
It means a single variable, i
...
, same memory location, can

128

C Programming
be used to store multiple types of data
...

The memory occupied by a union will be large enough to hold the largest
member of the union
...
The following example displays the total memory
size occupied by the above union:
#include ...
h>

union Data
{
int i;
float f;
char

str[20];

};

int main( )
{
union Data data;

printf( "Memory size occupied by data : %d\n", sizeof(data));

return 0;
}
When the above code is compiled and executed, it produces the following result:
Memory size occupied by data : 20

Accessing Union Members
To access any member of a union, we use the member access operator (
...
You would use the keyword
union to define variables of union type
...
h>
129

C Programming

#include ...
i = 10;
data
...
5;
strcpy( data
...
i : %d\n", data
...
f : %f\n", data
...
str : %s\n", data
...
i : 1917853763
data
...
000000
data
...

Now let's look into the same example once again where we will use one variable
at a time which is the main purpose of having unions:
#include ...
h>

union Data
{
int i;
float f;
char

str[20];

};

int main( )
{
union Data data;

data
...
i : %d\n", data
...
f = 220
...
f : %f\n", data
...
str, "C Programming");
printf( "data
...
str);

return 0;
}
When the above code is compiled and executed, it produces the following result:
data
...
f : 220
...
str : C Programming
Here, all the members are getting printed very well because one member is
being used at a time
...
BIT FIELDS

C Programming

Suppose your C program contains a number of TRUE/FALSE variables grouped in
a structure called status, as follows:
struct
{
unsigned int widthValidated;
unsigned int heightValidated;
} status;
This structure requires 8 bytes of memory space but in actual, we are going to
store either 0 or 1 in each of the variables
...

If you are using such variables inside a structure, then you can define the width
of a variable which tells the C compiler that you are going to use only those
number of bytes
...

If you will use up to 32 variables, each one with a width of 1 bit, then also the
status structure will use 4 bytes
...
Let us
check the following example to understand the concept:
#include ...
h>

/* define simple structure */
struct
{

132

C Programming

unsigned int widthValidated;
unsigned int heightValidated;
} status1;

/* define a structure with bit fields */
struct
{
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status2;

int main( )
{
printf( "Memory size occupied by status1 : %d\n", sizeof(status1));
printf( "Memory size occupied by status2 : %d\n", sizeof(status2));

return 0;
}
When the above code is compiled and executed, it produces the following result:
Memory size occupied by status1 : 8
Memory size occupied by status2 : 4

Bit Field Declaration
The declaration of a bit-field has the following form inside a structure:
struct
{
type [member_name] : width ;
};
The following table describes the variable elements of a bit field:
Elements

Description

133

C Programming

type

An integer type that determines how a bit-field's value is
interpreted
...


member_name

The name of the bit-field
...
The width must be less
than or equal to the bit width of the specified type
...
A bit field can
hold more than a single bit; for example, if you need a variable to store a value
from 0 to 7, then you can define a bit-field with a width of 3 bits as follows:
struct
{
unsigned int age : 3;
} Age;
The above structure definition instructs the C compiler that the age variable is
going to use only 3 bits to store the value
...
Let us try the following example:
#include ...
h>

struct
{
unsigned int age : 3;
} Age;

int main( )
{
Age
...
age : %d\n", Age
...
age = 7;
printf( "Age
...
age );
134

C Programming

Age
...
age : %d\n", Age
...
age : 4
Age
...
age : 0

135

20
...
Following is an example to define a
term BYTE for one-byte numbers:
typedef unsigned char BYTE;
After this type definition, the identifier BYTE can be used as an abbreviation for
the type unsigned char, for example:
BYTE

b1, b2;

By convention, uppercase letters are used for these definitions to remind the
user that the type name is really a symbolic abbreviation, but you can use
lowercase, as follows:
typedef unsigned char byte;
You can use typedef to give a name to your user-defined data types as well
...
h>
#include ...
title, "C Programming");
strcpy( book
...
subject, "C Programming Tutorial");
book
...
title);
printf( "Book author : %s\n", book
...
subject);
printf( "Book book_id : %d\n", book
...
g
...




typedef interpretation is performed by the compiler whereas #define
statements are processed by the preprocessor
...
h>

#define TRUE

1

#define FALSE 0

int main( )

137

C Programming

{
printf( "Value of TRUE : %d\n", TRUE);
printf( "Value of FALSE : %d\n", FALSE);

return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of TRUE : 1
Value of FALSE : 0

138

C Programming

21
...
An input can be
given in the form of a file or from the command line
...

When we say Output, it means to display some data on screen, printer, or in
any file
...


The Standard Files
C programming treats all the devices as files
...

Standard File

File Pointer

Device

Standard input

stdin

Keyboard

Standard output

stdout

Screen

Standard error

stderr

Your screen

The file pointers are the means to access the file for reading and writing
purpose
...


The getchar() and putchar() Functions
The int getchar(void) function reads the next available character from the
screen and returns it as an integer
...
You can use this method in the loop in case you want to read more than
one character from the screen
...
This function puts only single character at a time
...
Check the following example:
139

C Programming

#include ...
When you enter a text and press enter, then the program proceeds and
reads only a single character and displays it as follows:
$
...
out
Enter a value : this is test
You entered: t

The gets() and puts() Functions
The char *gets(char *s) function reads a line from stdin into the buffer
pointed to by s until either a terminating newline or EOF (End of File)
...

#include ...
When you enter a text and press enter, then the program proceeds and
reads the complete line till end, and displays it as follows:
$
...
out
Enter a value : this is test
You entered: This is test

The scanf() and printf() Functions
The int scanf(const char *format,
...

The int printf(const char *format,
...

The format can be a simple constant string, but you can specify %s, %d, %c,
%f, etc
...
There
are many other formatting options available which can be used based on
requirements
...
h>
int main( )
{
char str[100];
int i;

printf( "Enter a value :");
scanf("%s %d", str, &i);

printf( "\nYou entered: %s %d ", str, i);

141

C Programming

return 0;
}
When the above code is compiled and executed, it waits for you to input some
text
...
/a
...
If you provide "string string" or "integer integer", then it will be
assumed as wrong input
...


142

22
...
This chapter covers how C programmers can create,
open, close text or binary files for their data storage
...
C programming language provides access on high-level functions as well as
low-level (OS level) calls to handle file on your storage devices
...


Opening Files
You can use the fopen( ) function to create a new file or to open an existing file
...
The prototype of this function call is
as follows:
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file, and
access mode can have one of the following values:
Mode

Description

r

Opens an existing text file for reading purpose
...
If it does not exist, then a new file is
created
...


a

Opens a text file for writing in appending mode
...
Here your program will start appending
content in the existing file content
...


w+

Opens a text file for both reading and writing
...


143

C Programming

a+

Opens a text file for both reading and writing
...
The reading will start from the beginning but writing
can only be appended
...
The prototype of this function is:
int fclose( FILE *fp );
The fclose() function returns zero on success, or EOF if there is an error in
closing the file
...
The EOF is
a constant defined in the header file stdio
...

There are various functions provided by C standard library to read and write a
file, character by character, or in the form of a fixed length string
...
It returns the written character written on success
otherwise EOF if there is an error
...
It
returns a non-negative value on success, otherwise EOF is returned in case of
any error
...
) function
as well to write a string into a file
...

Make sure you have /tmp directory available
...


#include ...
txt", "w+");
fprintf(fp, "This is testing for fprintf
...
\n", fp);
fclose(fp);
}
When the above code is compiled and executed, it creates a new file test
...
Let us read this
file in the next section
...
The
return value is the character read, or in case of any error, it returns EOF
...
It copies the read string into the buffer buf, appending
a null character to terminate the string
...
You can
also use int fscanf(FILE *fp, const char *format,
...

#include ...
txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);
printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);
printf("3: %s\n", buff );
fclose(fp);

}
When the above code is compiled and executed, it reads the file created in the
previous section and produces the following result:
1 : This
2: is testing for fprintf
...

Let's see a little more in detail about what happened here
...
Finally,
the last call fgets() reads the second line completely
...


146

C Programming

23
...
In simple terms, a C Preprocessor is just a text substitution
tool and it instructs the compiler to do required preprocessing before the actual
compilation
...

All preprocessor commands begin with a hash symbol (#)
...
The following section lists down all the important preprocessor
directives:
Directive

Description

#define

Substitutes a preprocessor macro
...


#undef

Undefines a preprocessor macro
...


#ifndef

Returns true if this macro is not defined
...


#else

The alternative for #if
...


#endif

Ends preprocessor conditional
...


#pragma

Issues special commands to the compiler, using a standardized
147

C Programming

method
...

#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20
...

#include ...
h"
These directives tell the CPP to get stdio
...
The next line tells CPP to get myheader
...

#undef

FILE_SIZE

#define FILE_SIZE 42
It tells the CPP to undefine existing FILE_SIZE and define it as 42
...

#ifdef DEBUG
/* Your debugging statements here */
#endif
It tells the CPP to process the statements enclosed if DEBUG is defined
...
This will define DEBUG, so you can turn debugging on and off onthe-fly during compilation
...
Although each one is available for use in
programming, the predefined macros should not be directly modified
...


__TIME__

The current time as a character literal in "HH:MM:SS" format
...


__LINE__

This contains the current line number as a decimal constant
...


Let's try the following example:
#include ...
c is compiled and executed, it produces the
following result:
File :test
...
The macro continuation operator
(\) is used to continue a macro that is too long for a single line
...
This operator may be used
only in a macro having a specified argument or parameter list
...
h>

#define

message_for(a, b)

\

printf(#a " and " #b ": We love you!\n")

int main(void)
{
message_for(Carole, Debra);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Carole and Debra: We love you!

The Token Pasting (##) Operator
The token-pasting operator (##) within a macro definition combines two
arguments
...
For example:
#include ...


The Defined() Operator
The preprocessor defined operator is used in constant expressions to determine
if an identifier is defined using #define
...
If the symbol is not defined, the value is false (zero)
...
h>

#if !defined (MESSAGE)
#define MESSAGE "You wish!"
#endif

int main(void)
{
printf("Here is the message: %s\n", MESSAGE);
return 0;
}
151

C Programming
When the above code is compiled and executed, it produces the following result:
Here is the message: You wish!

Parameterized Macros
One of the powerful functions of the CPP is the ability to simulate functions using
parameterized macros
...
The argument list is enclosed in parentheses and must immediately
follow the macro name
...
For example:
#include ...
HEADER FILES

C Programming

A header file is a file with extension
...
There are two
types of header files: the files that the programmer writes and the files that
comes with your compiler
...
h header
file, which comes along with your compiler
...

A simple practice in C or C++ programs is that we keep all the constants,
macros, system wide global variables, and function prototypes in the header files
and include that header file wherever it is required
...
It has the following two forms:
#include
This form is used for system header files
...
You can prepend directories to this list with
the -I option while compiling your source code
...
It searches for a file
named ‘file’ in the directory containing the current file
...


Include Operation
The #include directive works by directing the C preprocessor to scan the
specified file as input before continuing with the rest of the current source file
...
For example, if you have
a header file header
...
c that uses the header file, like this:
int x;
#include "header
...
c read
...
The standard way to prevent this is
to enclose the entire real contents of the file in a conditional, like this:
#ifndef HEADER_FILE
#define HEADER_FILE

the entire header file file

#endif
This construct is commonly known as a wrapper #ifndef
...

The preprocessor will skip over the entire contents of the file, and the compiler
will not see it twice
...
For instance, they might specify configuration
parameters to be used on different sorts of operating systems
...
h"
#elif SYSTEM_2
# include "system_2
...

#endif
But as it grows, it becomes tedious, instead the preprocessor offers the ability to
use a macro for the header name
...
Instead
of writing a header name as the direct argument of #include, you simply put a
macro name there:
#define SYSTEM_H "system_1
...

#include SYSTEM_H
SYSTEM_H will be expanded, and the preprocessor will look for system_1
...
SYSTEM_H could be defined
by your Makefile with a -D option
...
TYPE CASTING

C Programming

Type casting is a way to convert a variable from one data type to another data
type
...
You can convert the values from one type to
another explicitly using the cast operator as follows:
(type_name) expression
Consider the following example where the cast operator causes the division of
one integer variable by another to be performed as a floating-point operation:
#include ...
400000
It should be noted here that the cast operator has precedence over division, so
the value of sum is first converted to type double and finally it gets divided by
count yielding a double value
...
It is considered good programming practice to use the cast operator
whenever type conversions are necessary
...
Consider
an example of adding a character with an integer:
#include ...


Usual Arithmetic Conversion
The usual arithmetic conversions are implicitly performed to cast their values
to a common type
...
Let us take the following
example to understand the concept:
#include ...
000000
Here, it is simple to understand that first c gets converted to integer, but as the
final value is double, usual arithmetic conversion applies and the compiler
converts i and c into ‘float’ and adds them yielding a ‘float’ result
...
ERROR HANDLING

As such, C programming does not provide direct support for error handling but
being a sytem programming language, it provides you access at lower level in
the form of return values
...
It is set as a global
variable and indicates an error occurred during any function call
...
h> header file
...
It is a good practice to set errno to 0 at
the time of initializing a program
...


errno, perror(), and strerror()
The C programming language provides perror() and strerror() functions which
can be used to display the text message associated with errno
...




The strerror() function, which returns
representation of the current errno value
...
Here I'm using both the functions to show the usage, but you can use one
or more ways of printing your errors
...

#include ...
h>
#include ...
txt", "rb");
if (pf == NULL)
{
errnum = errno;
fprintf(stderr, "Value of errno: %d\n", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
}
else
{
fclose (pf);
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of errno: 2
Error printed by perror: No such file or directory
Error opening file: No such file or directory

Divide by Zero Errors
It is a common problem that at the time of dividing any number, programmers
do not check if a divisor is zero and finally it creates a runtime error
...
h>
#include ...
\n");
exit(-1);
}
quotient = dividend / divisor;
fprintf(stderr, "Value of quotient : %d\n", quotient );

exit(0);
}
When the above code is compiled and executed, it produces the following result:
Division by zero! Exiting
...
Here, EXIT_SUCCESS is a
macro and it is defined as 0
...
So let's write
above program as follows:
#include ...
h>

main()
{
int dividend = 20;
int divisor = 5;
int quotient;

if( divisor == 0){
fprintf(stderr, "Division by zero! Exiting
...
RECURSION

C Programming

Recursion is the process of repeating items in a self-similar way
...

void recursion()
{
recursion();

/* function calls itself */

}

int main()
{
recursion();
}
The C programming language supports recursion, i
...
, a function to call itself
...

Recursive functions are very useful to solve many mathematical problems, such
as calculating the factorial of a number, generating Fibonacci series, etc
...
h>

int factorial(unsigned int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
164

C Programming

}
int

main()

{
int i = 15;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
When the above code is compiled and executed, it produces the following result:
Factorial of 15 is 2004310016

Fibonacci Series
The following example generates the Fibonacci series for a given number using a
recursive function:
#include ...
VARIABLE ARGUMENTS

Sometimes, you may come across a situation, when you want to have a
function, which can take variable number of arguments, i
...
, parameters,
instead of predefined number of parameters
...

The following example shows the definition of such a function
...
)
{

...


...
e
...
) and the one just before the ellipses is always an int which
will represent the total number variable arguments passed
...
h header file which provides the
functions and macros to implement the functionality of variable arguments and
follow the given steps:
1
...

2
...
This type is
defined in stdarg
...

3
...
The macro va_start is defined in stdarg
...

4
...

167

C Programming
5
...


clean

up

the

memory

assigned

Now let us follow the above steps and write down a simple function which can
take the variable number of parameters and return their average:
#include ...
h>

double average(int num,
...
0;
int i;

/* initialize valist for num number of arguments */
va_start(valist, num);

/* access all the arguments assigned to valist */
for (i = 0; i < num; i++)
{
sum += va_arg(valist, int);
}
/* clean memory reserved for valist */
va_end(valist);

return sum/num;
}

int main()
{
printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));
printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));
}

168

C Programming
When the above code is compiled and executed, it produces the following result
...
Only ellipses will be used to pass variable number of arguments
...
500000
Average of 5, 10, 15 = 10
...
MEMORY MANAGEMENT

This chapter explains dynamic memory management in C
...

These functions can be found in the ...


S
...


Function and Description

1

void *calloc(int num, int size);
This function allocates an array of num elements each of which size in
bytes will be size
...


3

void *malloc(int num);
This function allocates an array of num bytes and leave them initialized
...


Allocating Memory Dynamically
While programming, if you are aware of the size of an array, then it is easy and
you can define it as an array
...
Here we need to define a pointer to character without defining
how much memory is required and later, based on requirement, we can allocate
memory as shown in the below example:
#include ...
h>
#include ...

Name = Zara Ali
Description: Zara ali a DPS student in class 10th
Same program can be written using calloc(); only thing is you need to replace
malloc with calloc as follows:
calloc(200, sizeof(char));
So you have complete control and you can pass any size value while allocating
memory, unlike arrays where once the size is defined, you cannot change it
...

Alternatively, you can increase or decrease the size of an allocated memory
block by calling the function realloc()
...
h>
#include ...
h>

int main()
{
char name[100];
char *description;

strcpy(name, "Zara Ali");

/* allocate memory dynamically */
description = malloc( 30 * sizeof(char) );
if( description == NULL )
{
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else
{
strcpy( description, "Zara ali a DPS student
...

Name = Zara Ali
Description: Zara ali a DPS student
...


173

C Programming

30
...
These values are called command line
arguments and many times they are important for your program especially
when you want to control your program from outside instead of hard coding
those values inside the code
...
Following is a
simple example which checks if there is any argument supplied from the
command line and take action accordingly:
#include ...
\n");
}
else
{
printf("One argument expected
...

$
...
out testing
The argument supplied is testing
174

C Programming
When the above code is compiled and executed with two arguments, it produces
the following result
...
/a
...

When the above code is compiled and executed without passing any argument,
it produces the following result
...
/a
...
If no arguments are supplied, argc will be one,
and if you pass one argument, then argc is set at 2
...
Let us re-write above example once again
where we will print program name and we also pass a command line argument
by putting inside double quotes:
#include ...
\n");
}
else
{
printf("One argument expected
...

$
...
out "testing1 testing2"

Progranm name
...
out
The argument supplied is testing1 testing2

176


Title: c languange
Description: this is a c language