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 programming tuitorial-copy
Description: This purposely for someone undertaking programming course in C language.The notes are well detailed and simple to understand.They have pictorial diagrams and worked out problems on C programming ,again for easier understanding of your course.I hope you will love this

Document Preview

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


C Programming Tutorial

C PROGRAMMING TUTORIAL

Simply Easy Learning by tutorialspoint
...
com
i

COPYRIGHT & DISCLAIMER NOTICE



All the content and graphics on this tutorial are the property of tutorialspoint
...
Any content from
tutorialspoint
...
com
...

This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of
the site or its contents including this tutorial
...
com site or this tutorial
content contains some errors, please contact us at webmaster@tutorialspoint
...
1
Facts about C
...
2
C Programs
...
3
Text Editor
...
3
Installation on Unix/Linux
...
4
Installation on Windows
...
5
C Hello World Example
...
6

C Basic Syntax
...
7
Semicolons ;
...
8
Identifiers
...
8
Whitespace in C
...
10
Integer Types
...
11
The void Type
...
13
Variable Declaration in C
...

Variable Initialization in C
...

Lvalues and Rvalues in C
...
17
Integer literals
...
18
Character constants
...
19
Defining Constants
...
19
The const Keyword
...
22
The auto Storage Class
...
22
The static Storage Class
...
24

C Operators
...
25
Relational Operators
...
28
Bitwise Operators
...
31
Misc Operators ↦ sizeof & ternary
...
33

Decision Making in C
...
36
Syntax
...
36
Example
...
else statement
...
37
Flow Diagram
...
38

The if
...
else Statement
...
39
Example
...
40
Syntax
...
40

switch statement
...
41
Flow Diagram
...
42

Nested switch statements
...
43
Example
...
44

C Loops
...
46
Syntax
...
46
Example
...
47
Syntax
...
48
Example
...
while loop in C
...
49
Flow Diagram
...
50

nested loops in C
...
51
Example
...
53
Syntax
...
53
Example
...
54
Syntax
...
55
Example
...
56
Syntax
...
56
Example
...
57

C Functions
...
59
Example
...
60
Calling a Function
...
61
Function call by value
...
63

C Scope Rules
...
65
Global Variables
...
67
Initializing Local and Global Variables
...
69
Declaring Arrays
...
70
Accessing Array Elements
...
71
Two-Dimensional Arrays
...
72
Accessing Two-Dimensional Array Elements
...
73
Way-1
...
74

Way-3
...
74

Return array from function
...
77

C Pointers
...
80
How to use Pointers?
...
81
Pointer arithmetic
...
82
Decrementing a Pointer
...
83
Array of pointers
...
86
Passing pointers to functions
...
88

C Strings
...
94
Defining a Structure
...
95
Structures as Function Arguments
...
97

C Unions
...
100
iii

Accessing Union Members
...
103
Bit Field Declaration
...
106
typedef vs #define
...
108
The Standard Files
...
108
The gets() & puts() functions
...
110

File I/O
...
111
Closing a File
...
112
Reading a File
...
114

Preprocessors
...
115
Predefined Macros
...
117
Macro Continuation (\)
...
117
Token Pasting (##)
...
118

Parameterized Macros
...
120
Include Syntax
...
121
Once-Only Headers
...
122

Type Casting
...
124
Usual Arithmetic Conversion
...
126
The errno, perror() and strerror()
...
127
Program Exit Status
...
129
Number Factorial
...
130

Variable Arguments
...
133
Allocating Memory Dynamically
...
134

Command Line Arguments
...


T

he C programming language 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 applications programs
have been written in C
...




Easy to learn



Structured language



It produces efficient programs
...




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




C is a successor of B language, which was introduced around 1970
...

(ANSI)
...


TUTORIALS POINT
Simply Easy Learning

Page 1



Today, C is the most widely used and popular System Programming Language
...




Today's most ][popular Linux OS and RBDMS MySQL have been written in C
...
C was adopted as a system development language because it
produces code that runs nearly as fast as code written in assembly language
...
c"; for example, hello
...
You can use "vi", "vim" or any
other text editor to write your C program into a file
...


TUTORIALS POINT
Simply Easy Learning

Page 2

2

CHAPTER

C Environment Setup
This section describes how to set up your system environment before you start doing your
programming using C language
...


Text Editor
This will be used to type your program
...

Name and version of text editor can vary on different operating systems
...

The files you create with your editor are called source files and contain program source
code
...
c”
...


The C Compiler
The source code written in source file is the human readable source for your program
...

This C programming language compiler will be used to compile your source code into final
executable program
...

Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you can
have compilers either from HP or Solaris if you have respective Operating Systems
...
I'm
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 athttp://gcc
...
org/install/
This tutorial has been written based on Linux and all the given examples have been
compiled on Cent OS flavor of Linux system
...
Once you
have Xcode setup, you will be able to use GNU compiler for C/C++
...
apple
...


Installation on Windows
To install GCC at Windows you need to install MinGW
...
mingw
...
Download
the latest version of the MinGW installation program, which should be named MinGW
...

While installing MinWG, at a minimum, you must install gcc-core, gcc-g++, binutils, and
the MinGW runtime, but you may wish to install more
...

When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and
several other GNU tools from the Windows command line
...


B

efore 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
...
h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
Let us look various parts of the above program:

TUTORIALS POINT
Simply Easy Learning

Page 5

1
...
h> is a preprocessor command, which tells
a C compiler to include stdio
...


2
...


3
...
*/ will be ignored by the compiler and it has been put to add additional
comments in the program
...


4
...
) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen
...


The next line return 0; terminates main()function and returns the value 0
...
Following
are the simple steps:

1
...


2
...
c

3
...


4
...
c and press enter to compile your code
...


If there are no errors in your code, the command prompt will take you to the next line and
would generate a
...


6
...
out to execute your program
...


You will be able to see "Hello World" printed on the screen

$ gcc hello
...
/a
...
c
...


Y

ou have seen a basic structure of 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 C program, the semicolon is a statement terminator
...
It indicates the end of one logical entity
...

They start with /* and terminates with the characters */ as shown below:

/* my first program in C */
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 or 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
myname50

zara
_temp

abc
j

move_name
a23b9

a_123
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

TUTORIALS POINT
Simply Easy Learning

Page 8

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 for readability purpose
...
The type of a variable determines how
much space it occupies in storage and how the bit pattern stored is interpreted
...
N
...


2

Enumerated types:
They are again arithmetic types and they are used to define variables that can only be
assigned certain discrete integer values throughout the program
...


4

Derived types:
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and
(e) Function types
...
The
type of a function specifies the type of the function's return value
...


Integer Types
Following table gives you details 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

TUTORIALS POINT
Simply Easy Learning

Page 10

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

#include ...
h>
int main()
{
printf("Storage size for int : %d \n", sizeof(int));
return 0;
}
When you compile and execute the above program, it produces the following result on
Linux:

Storage size for int : 4

Floating-Point Types
Following table gives you details about standard floating-point types with storage sizes and
value ranges and their precision:

Type

Storage size

Value range

Precision

float

4 byte

1
...
4E+38

6 decimal places

double

8 byte

2
...
7E+308

15 decimal places

long double

10 byte

3
...
1E+4932

19 decimal places

The header file float
...
Following example will
print storage space taken by a float type and its range values:

#include ...
h>
int main()

TUTORIALS POINT
Simply Easy Learning

Page 11

{
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 the following result on
Linux:

Storage size for float : 4
Minimum float positive value: 1
...
402823E+38
Precision value: 6

The void Type
The void type specifies that no value is available
...
N
...

A function with no return value has the return type as void
...
A function with no
parameter can accept as a void
...
For example,
a memory allocation function void *malloc( size_t size ); returns a pointer to void which
can be casted to any data type
...


TUTORIALS POINT
Simply Easy Learning

Page 12

6

CHAPTER

C Variables

A

variable is nothing but a name given to a storage area that our programs can

manipulate
...

The name of a variable can be composed of letters, digits, and the underscore character
...
Upper and lowercase letters are distinct
because C is case-sensitive
...
This is an integer type
...


Float

A single-precision floating point value
...


Void

Represents the absence of type
...

For this chapter, let us study only basic variable types
...
A variable definition specifies a data 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, w_char, int, float, double, bool or any userdefined object, etc
...
Some valid declarations are shown here:

TUTORIALS POINT
Simply Easy Learning

Page 13

int
char
float
double

i, j, k;
c, ch;
f, salary;
d;

The line int i, j, k; both declares and defines the variables i, j and k; which instructs 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;
int d = 3, f = 5;
byte z = 22;
char x = 'x';

//
//
//
//

declaration of
definition and
definition and
the variable x

d and f
...

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 is undefined
...
A variable declaration has its meaning at the time of
compilation only, compiler needs actual variable declaration at the time of linking of the program
...
You will
use extern keyword 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:
#include ...
0/3
...
333334
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
...


lvalue: An expression that is an lvalue may appear as either the left-hand or right-hand
side of an assignment
...


rvalue: An expression that is an rvalue may appear on the right- but not left-hand side
of an assignment
...
Numeric
literals are rvalues and so may not be assigned and cannot appear on the left-hand side
...
These fixed values are also called literals
...
There are also enumeration
constants as well
...


Integer literals
An integer literal can be a decimal, octal, or hexadecimal constant
...

An integer literal can also have a suffix that is a combination of U and L, for unsigned and
long, respectively
...

Here are some examples of integer literals:

212
215u
0xFeeL
078
032UU

/*
/*
/*
/*
/*

Legal */
Legal */
Legal */
Illegal: 8 is not an octal digit */
Illegal: cannot repeat a suffix */

Following are other examples of various types of Integer literals:

85
0213
0x4b
30
30u
30l
30ul

/*
/*
/*
/*
/*
/*
/*

decimal */
octal */
hexadecimal */
int */
unsigned int */
long */
unsigned long */

TUTORIALS POINT
Simply Easy Learning

Page 17

Floating-point literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an
exponent part
...

While representing using decimal form, you must include the decimal point, the exponent,
or both and while representing using exponential form, you must include the integer part,
the fractional part, or both
...

Here are some examples of floating-point literals:

3
...
e55

/*
/*
/*
/*
/*

Legal */
Legal */
Illegal: incomplete exponent */
Illegal: no decimal or exponent */
Illegal: missing integer or fraction */

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

There are certain characters in C when they are preceded by a backslash they will have
special meaning and they are used to represent like newline (\n) or tab (\t)
...


Hexadecimal number of one or more digits

Following is the example to show few escape sequence characters:

#include ...
A string contains characters
that are similar to character literals: plain characters, escape sequences, and universal
characters
...

Here are some examples of string literals
...


"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"

Defining Constants
There are two simple ways in C to define constants:

1
...


Using #define preprocessor
...


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

TUTORIALS POINT
Simply Easy Learning

Page 19

#define identifier value
Following example explains it in detail:

#include ...
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 the following result:

TUTORIALS POINT
Simply Easy Learning

Page 20

value of area : 50
Note that it is a good programming practice to define constants in CAPITALS
...
These specifiers precede the type that they modify
...


{
int mount;
auto int month;
}
The example above defines two variables with the same storage class, auto can only be
used within functions, i
...
, local variables
...
This means that the variable has a maximum size equal to the
register size (usually one word) and can't have the unary '&' operator applied to it (as it
does not have a memory location)
...
It
should also be noted that defining 'register' does not mean that the variable will be stored
in a register
...


The static Storage Class
The static storage class instructs the compiler to keep a local variable in existence during
the life-time of the program instead of creating and destroying it each time it comes into
and goes out of scope
...

The static modifier may also be applied to global variables
...

In C programming, when static is used on a class data member, it causes only one copy of
that member to be shared by all objects of its class
...
h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main()
{
while(count--)
{
func();
}
return 0;
}
/* function definition */
void func( void )
{
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
You may not understand this example at this time because I have used function and global
variables, which I have not explained so far
...
When the above code is compiled and executed, it produces the
following result:

i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

TUTORIALS POINT
Simply Easy Learning

Page 23

The extern Storage Class
The extern storage class is used to give a reference of a global variable that is visible to
ALL the program files
...

When you have multiple files and you define a global variable or function, which will be
used in other files also, then extern will be used in another file to give reference of defined
variable or function
...

The extern modifier is most commonly used when there are two or more files sharing the
same global variables or functions as explained below
...
c
#include ...
c
#include ...
c
...
c write
...
out executable program, when this program is executed, it produces
the following result:

5

TUTORIALS POINT
Simply Easy Learning

Page 24

9

CHAPTER

C Operators

A

n operator is a symbol that tells the compiler to perform specific mathematical or logical

manipulations
...


Arithmetic Operators
Following table shows all the arithmetic operators supported by C language
...
h>
main()
{
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line
c = a - b;
printf("Line
c = a * b;
printf("Line
c = a / b;
printf("Line
c = a % b;
printf("Line
c = a++;
printf("Line
c = a--;
printf("Line

1 - Value of c is %d\n", c );
2 - Value of c is %d\n", c );
3 - Value of c is %d\n", c );
4 - Value of c is %d\n", c );
5 - Value of c is %d\n", c );
6 - Value of c is %d\n", c );
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
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
...


(A == B) is not true
...


(A != B) is true
...


(A > B) is not true
...


(A < B) is true
...


(A >= B) is not true
...


(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
{
printf("Line 3 - a is not greater than b\n" );
}
/* Lets change value of a and b */
a = 5;
b = 20;
if ( a <= b )

TUTORIALS POINT
Simply Easy Learning

Page 27

{
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,
(A && B) is false
...


||

Called Logical OR Operator
...


(A || B) is true
...
Use to reverses the logical state
of its operand
...


!(A && B) is true
...
h>
main()
{
int a = 5;
int b = 20;
int c ;
if ( a && b )
{
printf("Line 1 - Condition is true\n" );
}
if ( a || b )
{

TUTORIALS POINT
Simply Easy Learning

Page 28

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 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 operator works on bits and performs 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
...


(A | B) will give 61, which is 0011 1101

^

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


(~A ) will give -60, which is 1100 0011

<<

Binary Left Shift Operator
...


A << 2 will give 240, which is 1111 0000

>>

Binary Right Shift Operator
...


A >> 2 will give 15, which is 0000 1111

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

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

TUTORIALS POINT
Simply Easy Learning

Page 32

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
There are few other important operators including sizeof and ? : supported by C Language
...


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


&a; will give actual address of
the variable
...


*a; will pointer to a variable
...
This affects how
an expression is evaluated
...

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has 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

TUTORIALS POINT
Simply Easy Learning

Page 33

Logical AND

&&

Left to right

Logical OR

||

Left to right

Conditional

?:

Right to left

Assignment

= += -= *= /= %=>>= <<= &= ^= |=

Right to left

Comma

,

Left to right

Try the following example to understand the operator precedence available in C
programming language:

#include ...

Following is the general form 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
...


TUTORIALS POINT
Simply Easy Learning

Page 35

if statement
An if statement consists of a boolean expression followed by one or more statements
...
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
...


Flow Diagram

Example
#include ...
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 of code will be executed,
otherwise else block of code will be executed
...


TUTORIALS POINT
Simply Easy Learning

Page 37

Flow Diagram

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




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 */
printf("Value of a is 10\n" );
}
else if( a == 20 )
{
/* if else if condition is true */
printf("Value of a is 20\n" );

TUTORIALS POINT
Simply Easy Learning

Page 39

}
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 statement
...
h>
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
/* check the boolean condition */

TUTORIALS POINT
Simply Easy Learning

Page 40

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:

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

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' :

TUTORIALS POINT
Simply Easy Learning

Page 42

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 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" );
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
...
If it is true, then
Exp2 is evaluated and becomes the value of the entire ? expression
...


TUTORIALS POINT
Simply Easy Learning

Page 44

CHAPTER

11
C Loops

T

here may be a situation, when you need to execute a block of code several number

of times
...

Programming languages provide various control structures that allow for more complicated
execution paths
...


TUTORIALS POINT
Simply Easy Learning

Page 45

while loop in C
A while loop statement in C programming language repeatedly executes a target
statement as long as a given condition is true
...

The condition may be any expression, and true is any nonzero value
...

When the condition becomes false, program control passes to the line immediately
following the loop
...
When the condition is
tested and the result is false, the loop body will be skipped and the first statement after
the while loop will be executed
...
h>
int main ()
{
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}
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
value of a: 16
value of a: 17
value of a: 18
value of a: 19

for loop in C
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times
...


The init step is executed first, and only once
...
You are not required to put a statement here, as long
as a semicolon appears
...


Next, the condition is evaluated
...
If it is
false, the body of the loop does not execute and flow of control jumps to the next
statement just after the for loop
...


After the body of the for loop executes, the flow of control jumps back up to
the increment statement
...
This statement can be left blank, as long as a semicolon appears after the
condition
...


The condition is now evaluated again
...
After the
condition becomes false, the for loop terminates
...
h>
int main ()

TUTORIALS POINT
Simply Easy Learning

Page 48

{
/* for loop execution */
for( int a = 10; a < 20; a = a + 1 )
{
printf("value of a: %d\n", a);
}
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
value of a: 16
value of a: 17
value of a: 18
value of a: 19

do
...
while loop in C programming language checks its condition at the bottom of the
loop
...
while loop is similar to a while loop, except that a do
...


Syntax
The syntax of a do
...


TUTORIALS POINT
Simply Easy Learning

Page 49

If the condition is true, the flow of control jumps back up to do, and the statement(s) in
the loop execute again
...


Flow Diagram

Example
#include ...
Following section
shows few examples to illustrate the concept
...
while loop statement in C programming language is as
follows:

do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );

TUTORIALS POINT
Simply Easy Learning

Page 51

A final note on loop nesting is that you can put any type of loop inside of any other type of
loop
...


Example
The following program uses a nested for loop to find the prime numbers from 2 to 100:

#include ...


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


It can be used to terminate a case in the switch statement (covered in the next chapter)
...
e
...


Syntax
The syntax for a break statement in C is as follows:

break;

Flow Diagram

TUTORIALS POINT
Simply Easy Learning

Page 53

Example
#include ...
Instead of forcing termination, however, continue forces the next
iteration of the loop to take place, skipping any code in between
...
For the while and do
...


Syntax
The syntax for a continue statement in C is as follows:

continue;

TUTORIALS POINT
Simply Easy Learning

Page 54

Flow Diagram

Example
#include ...

NOTE: Use of goto statement is highly discouraged in any programming language because
it makes difficult to trace the control flow of a program, making the program hard to
understand and hard to modify
...


Syntax
The syntax for a goto statement in C is as follows:

goto label;

...

label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C
program above or below to goto statement
...
h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}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

The Infinite Loop
A loop becomes infinite loop if a condition never becomes false
...
Since none of the three expressions that form the for
loop are required, you can make an endless loop by leaving the conditional expression
empty
...
h>
int main ()
{

TUTORIALS POINT
Simply Easy Learning

Page 57

for( ; ; )
{
printf("This loop will run forever
...
You may have an
initialization and increment expression, but C programmers more commonly use the for(;;)
construct to signify an infinite loop
...


TUTORIALS POINT
Simply Easy Learning

Page 58

CHAPTER

12
C Functions

F

unction 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 is known with various names like 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
Following 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 defined task, and when its return statement is executed or when
its function-ending closing brace is reached, it returns program control back to the main
program
...
For example:

#include ...
While
running 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
...

The 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
...
In
general, this means that code within a function cannot alter the arguments used to call the
function
...


/* function definition to swap the values */
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y;
/* put y into x */
y = temp; /* put x into y */
return;
}
Now, let us call the function swap() by passing actual values as in the following example:

#include ...


Function call by reference
The call by reference method of passing arguments to a function copies the address of an
argument into the formal parameter
...
This means that changes made to the parameter affect
the passed argument
...
So accordingly you need to declare the function parameters as pointer
types as in the following function swap(), which exchanges the values of the two integer
variables pointed to by its arguments
...
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 );
/* calling a function to swap the values
...
address of variable a and
* &b indicates pointer to b ie
...

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

TUTORIALS POINT
Simply Easy Learning

Page 63

return 0;
}
Let us put 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 :200
After swap, value of b :100
Which shows that there is no change in the values though they had been changed inside
the function
...
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 explain 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
...
Following is the example using local
variables
...


#include ...
The
global variables will hold their value 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
...
h>
/* global variable declaration */
int g;
int main ()
{
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
A program can have same name for local and global variables but value of local variable
inside a function will take preference
...
h>
/* global variable declaration */
int g = 20;
int main ()
{
/* local variable declaration */
int g = 10;
printf ("value of g = %d\n",

g);

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

value of g = 10

TUTORIALS POINT
Simply Easy Learning

Page 66

Formal Parameters
Function parameters, so called formal parameters, are treated as local variables within
that function and they will take preference over the global variables
...
h>
/* global variable declaration */
int a = 20;
int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n",
c = sum( a, b);
printf ("value of c in main() = %d\n",

a);
c);

return 0;
}
/* function to add
int sum(int a, int
{
printf ("value
printf ("value

two integers */
b)
of a in sum() = %d\n",
of b in sum() = %d\n",

a);
b);

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

value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30

Initializing Local and Global Variables
When a local variable is defined, it is not initialized by the system, you must initialize it
yourself
...


TUTORIALS POINT
Simply Easy Learning

Page 68

CHAPTER

14
C Arrays

C

programming language provides a data structure called the array, which 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 10element array called balance of type double, use this statement:

double balance[10];
Now balance is a variable array which is sufficient to hold up-to 10 double numbers
...
0, 2
...
4, 17
...
0};
The number of values between braces { } can not 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
...


balance[4] = 50
...
0
...
e
...
Following is the pictorial representation of the
same 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 10th element from the array and assign the value to salary
variable
...
declaration, assignment and accessing arrays:

#include ...
Here is the general form of a
multidimensional array declaration:

type name[size1][size2]
...
10
...
A twodimensional array is, in essence, a list of one-dimensional arrays
...
A twodimensional array can be think as a table which will have x number of rows and y number
of columns
...


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


int a[3][4] = {
{0, 1, 2, 3} ,
{4, 5, 6, 7} ,
{8, 9, 10, 11}
};

/*
/*
/*

initializers for row indexed by 0 */
initializers for row indexed by 1 */
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 4th element from the 3rd row of the array
...
Let us check below program where we have used nested loop to
handle a two dimensional array:

#include ...


Passing Arrays as Function Arguments
If you want to pass a single-dimension array as an argument in a function, you would have
to declare function 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 as follows
...


void myFunction(int *param)
{

...


...


...

}

Way-3
Formal parameters as an unsized array as follows:

void myFunction(int param[])
{

...


...
h>
/* function declaration */
double getAverage(int arr[], int size);
int main ()

TUTORIALS POINT
Simply Easy Learning

Page 74

{
/* 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 function
C programming language does not allow to return an entire array as an argument to a
function
...
You will study pointer in next chapter so you can skip this chapter until
you understand the concept of Pointers in C
...


...

}
Second point to remember is that C does not advocate to return the address of a local
variable to outside of the function so you would have to define the local variable
as static variable
...
h>
/* function to generate and return random numbers */
int * getRandom( )
{
static int r[10];
int i;

TUTORIALS POINT
Simply Easy Learning

Page 75

/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i)
{
r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}
return r;
}
/* main function to call above defined function */
int main ()
{
/* a pointer to an int */
int *p;
int i;
p = getRandom();
for ( i = 0; i < 10; i++ )
{
printf( "*(p + %d) : %d\n", i, *(p + i));
}
return 0;
}
When the above code is compiled together and executed, it produces result something as
follows:

r[0] = 313959809
r[1] = 1759055877
r[2] = 1113101911
r[3] = 2133832223
r[4] = 2073354073
r[5] = 167288147
r[6] = 1827471542
r[7] = 834791014
r[8] = 1901409888
r[9] = 1990469526
*(p + 0) : 313959809
*(p + 1) : 1759055877
*(p + 2) : 1113101911
*(p + 3) : 2133832223
*(p + 4) : 2073354073
*(p + 5) : 167288147
*(p + 6) : 1827471542
*(p + 7) : 834791014
*(p + 8) : 1901409888
*(p + 9) : 1990469526

TUTORIALS POINT
Simply Easy Learning

Page 76

Pointer to an Array
It is most likely that you would not understand this chapter until you are through the
chapter related to Pointers in C
...
Therefore, in
the declaration:

double balance[50];
balance is a pointer to &balance[0], which is the address of the first element of the array
balance
...
Therefore, *(balance +
4) is a legitimate way of accessing the data at balance[4]
...
Below is the example to show all the concepts discussed above:

#include ...
0, 2
...
4, 17
...
0};
double *p;
int i;
p = balance;
/* output each array element's value */
printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ )
{
printf("*(p + %d) : %f\n", i, *(p + i) );
}
printf( "Array values using balance as address\n");
for ( i = 0; i < 5; i++ )
{
printf("*(balance + %d) : %f\n", i, *(balance + i) );
}
return 0;
}
When the above code is compiled and executed, it produces the following result:

TUTORIALS POINT
Simply Easy Learning

Page 77

Array values using pointer
*(p + 0) : 1000
...
000000
*(p + 2) : 3
...
000000
*(p + 4) : 50
...
000000
*(balance + 1) : 2
...
400000
*(balance + 3) : 17
...
000000
In the above example, p is a pointer to double, which means it can store address of a
variable of double type
...


TUTORIALS POINT
Simply Easy Learning

Page 78

CHAPTER

15
C Pointers

P

ointers 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 result something as follows:

Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6
So you understood what is memory address and how to access it, so base of the concept is
over
...


TUTORIALS POINT
Simply Easy Learning

Page 79

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:

type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name 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
...
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
On 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 convention, if a pointer contains the null
(zero) value, it is assumed to point to nothing
...
Therefore,
you can perform arithmetic operations on a pointer just as you can a numeric value
...
Assuming 32-bit integers, let us perform the following arithmetic
operation on the pointer:

TUTORIALS POINT
Simply Easy Learning

Page 81

ptr++
Now, after the above operation, the ptr will point to the location 1004 because each time
ptr is incremented, it will point to the next integer location which is 4 bytes next to the
current location
...
If ptr points to a character whose address
is 1000, then above operation will point to the location 1001 because next character will be
available at 1001
...
The following program increments the variable pointer to access each
succeeding element of the array:

#include ...
h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--)
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* move to the previous location */
ptr--;
}
return 0;
}
When the above code is compiled and executed, it produces result something as follows:

Address of var[3] = bfedbcd8
Value of var[3] = 200
Address of var[2] = bfedbcd4
Value of var[2] = 100
Address of var[1] = bfedbcd0
Value of var[1] = 10

Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >
...

The following program modifies the previous example one by incrementing the variable
pointer so long as the address to which it points is either less than or equal to the address
of the last element of the array, which is &var[MAX - 1]:

#include ...
h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i;
for (i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, var[i] );
}
return 0;
}

TUTORIALS POINT
Simply Easy Learning

Page 84

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
There may be a situation when we want to maintain an array, which can store pointers to
an int or char or any other data type available
...
Thus, each element in ptr, now holds
a pointer to an int value
...
h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; /* assign the address of integer
...
h>
const int MAX = 4;
int main ()
{
char *names[] = {

TUTORIALS POINT
Simply Easy Learning

Page 85

"Zara
"Hina
"Nuha
"Sara

Ali",
Ali",
Ali",
Ali",

};
int i = 0;
for ( i = 0; i < MAX; i++)
{
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result:

Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali

Pointer to Pointer
A pointer to a pointer is a form of multiple indirection, or a chain of pointers
...
When we define a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that
contains the actual value as shown below
...
This is done by placing
an additional asterisk in front of its name
...
h>
int main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;

TUTORIALS POINT
Simply Easy Learning

Page 86

/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
When the above code is compiled and executed, it produces the following result:

Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000

Passing pointers to functions
C programming language allows you to pass a pointer to a function
...

Following a simple example where we pass an unsigned long pointer to a function and
change the value inside the function which reflects back in the calling function:

#include ...
h>
void getSeconds(unsigned long *par);
int main ()
{
unsigned long sec;
getSeconds( &sec );
/* print the actual value */
printf("Number of seconds: %ld\n", sec );
return 0;
}
void getSeconds(unsigned long *par)
{
/* get the current number of seconds */
*par = time( NULL );
return;
}

TUTORIALS POINT
Simply Easy Learning

Page 87

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

Number of seconds :1294450468
The function, which can accept a pointer, can also accept an array as shown in the
following example:

#include ...
40000

Return pointer from functions
As we have seen in last chapter how C programming language allows to return an array
from a function, similar way C allows you to return a pointer from a function
...


...

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


#include ...
h>
/* function to generate and retrun random numbers
...
Thus a null-terminated string
contains the characters that comprise the string followed by a null
...

To hold the null character at the end of the array, the size of the character array containing
the string is one more than the number of characters in the word "Hello"
...
The C compiler
automatically places the '\0' at the end of the string when it initializes the array
...
h>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}

TUTORIALS POINT
Simply Easy Learning

Page 91

When the above code is compiled and executed, it produces result something as follows:

Greeting message: Hello
C supports a wide range of functions that manipulate null-terminated strings:

S
...
Function & Purpose
1

strcpy(s1, s2);
Copies string s2 into string s1
...


3

strlen(s1);
Returns the length of string s1
...


5

strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1
...


Following example makes use of few of the above-mentioned functions:

#include ...
h>
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) :

%s\n", str3 );

/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2):
%s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}
When the above code is compiled and executed, it produces result something as follows:

strcpy( str3, str1) :

TUTORIALS POINT
Simply Easy Learning

Hello

Page 92

strcat( str1, str2):
strlen(str1) :

HelloWorld

10

You can find a complete list of C string related functions in C Standard Library
...

Structures are used to represent a record, suppose you want to keep track of your books in
a library
...
The struct statement defines a
new data type, with more than one member for your program
...

member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition
...
Here is the way you would declare the Book structure:

struct Books
{

TUTORIALS POINT
Simply Easy Learning

Page 94

char
char
char
int
} book;

title[50];
author[50];
subject[100];
book_id;

Accessing Structure Members
To access any member of a structure, we use the member access operator (
...
You would use struct keyword to define
variables of structure type
...
h>
#include ...
title, "C Programming");
strcpy( Book1
...
subject, "C Programming Tutorial");
Book1
...
title, "Telecom Billing");
strcpy( Book2
...
subject, "Telecom Billing Tutorial");
Book2
...
title);
author : %s\n", Book1
...
subject);
book_id : %d\n", Book1
...
title);
author : %s\n", Book2
...
subject);
book_id : %d\n", Book2
...
You would access structure variables in the similar way as you have
accessed in the above example:

#include ...
h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int
book_id;
};

/* function declaration */
void printBook( struct Books book );
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 */
printBook( Book1 );

/* Print Book2 info */

TUTORIALS POINT
Simply Easy Learning

Page 96

printBook( Book2 );
return 0;
}
void printBook( struct Books book )
{
printf( "Book title : %s\n", book
...
author);
printf( "Book subject : %s\n", book
...
book_id);
}
When the above code is compiled and executed, it produces the following result:

Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

Pointers to Structures
You can define pointers to structures in very similar way as you define pointer to any other
variable as follows:

struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer
variable
...
h>

TUTORIALS POINT
Simply Easy Learning

Page 97

#include ...
title, "C Programming");
strcpy( Book1
...
subject, "C Programming Tutorial");
Book1
...
title, "Telecom Billing");
strcpy( Book2
...
subject, "Telecom Billing Tutorial");
Book2
...
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 very similar was as you did while
defining 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
...
This means that a single variable i
...
same memory location can be used to
store multiple types of data
...


TUTORIALS POINT
Simply Easy Learning

Page 100

The memory occupied by a union will be large enough to hold the largest member of the
union
...
Following is
the example which will display 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 union keyword to define variables of union
type
...
h>
#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 union:

#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
...
The C programming language offers a better way to utilize
the memory space in such situation
...
For example, above structure can be re-written as follows:

struct
{
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status;
Now, the above structure will require 4 bytes of memory space for status variable but only
2 bits will be used to store the values
...
Let
us check the following example to understand the concept:

#include ...
h>
/* define simple structure */
struct
{
unsigned int widthValidated;
unsigned int heightValidated;
} status1;
/* define a structure with bit fields */

TUTORIALS POINT
Simply Easy Learning

Page 103

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 form inside a structure:

struct
{
type [member_name] : width ;
};
Below the description of variable elements of a bit field:

Elements

Description

type

An integer type that determines how the 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 only 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 C compiler that age variable is going to use only 3
bits to store the value, if you will try to use more than 3 bits then it will not allow you to do
so
...
h>
#include ...
age = 4;
printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
printf( "Age
...
age );

Age
...
age : %d\n", Age
...
age = 8;
printf( "Age
...
age );
return 0;
}
When the above code is compiled it will compile with warning and when executed, it
produces the following result:

Sizeof( Age ) : 4
Age
...
age : 7
Age
...
Following is an example to define a term BYTE for one-byte
numbers:

typedef unsigned char BYTE;
After this type definitions, 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 user defined data type as well
...
h>
#include ...
title, "C Programming");
strcpy( book
...
subject, "C Programming Tutorial");

TUTORIALS POINT
Simply Easy Learning

Page 106

book
...
title);
author : %s\n", book
...
subject);
book_id : %d\n", book
...




The typedef interpretation is performed by the compiler where as #define statements
are processed by the pre-processor
...
h>
#define TRUE 1
#define FALSE 0
int main( )
{
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

TUTORIALS POINT
Simply Easy Learning

Page 107

CHAPTER

21
Input & Output

W

hen we are saying Input that means to feed some data into program
...
C programming language provides a set
of built-in functions to read given input and feed it to the program as per requirement
...
C programming language provides a set of built-in functions to output the data on the
computer screen as well as you can save that data in text or binary files
...
So devices such as the display are
addressed in the same way as files and following three file are automatically opened when
a program executes to provide access to the keyboard and screen
...
This section
will explain you how to read values from the screen and how to print the result on the
screen
...
This function reads only single character at a time
...

The int putchar(int c) function puts the passed character on the screen and returns the
same character
...
You can use this method

TUTORIALS POINT
Simply Easy Learning

Page 108

in the loop in case you want to display more than one character on the screen
...
h>
int main( )
{
int c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
return 0;
}
When the above code is compiled and executed, it waits for you to input some text when
you enter a text and press enter then 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() & 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
...


#include ...
/a
...
) function reads input from the standard input
stream stdin and scans that input according to format provided
...
) function writes output to the standard output
stream stdout and produces output according to a format provided
...
, to
print or read strings, integer, character or float respectively
...
For a complete
detail you can refer to a man page for these function
...
h>
int main( )
{
char str[100];
int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);
printf( "\nYou entered: %s, %d ", str, i);
return 0;
}
When the above code is compiled and executed, it waits for you to input some text when
you enter a text and press enter then program proceeds and reads the input and displays it
as follows:

$
...
out
Enter a value : seven 7
You entered: seven 7
Here, it should be noted that scanf() expect input in the same format as you provided %s
and %d, which means you have to provide valid input like "string integer", if you provide
"string string" or "integer integer" then it will be assumed as wrong input
...


TUTORIALS POINT
Simply Easy Learning

Page 110

CHAPTER

22
File I/O

L

ast chapter explained about standard input and output devices handled by C

programming language
...

A file represents a sequence of bytes, does not matter if it is a text file or binary file
...
This chapter will take you through
important calls for the file management
...
Following is the prototype of this function call:

FILE *fopen( const char * filename, const char * mode );
Here, filename is 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
...
Here your program will
start writing content from the beginning of the file
...

Here your program will start appending content in the existing file content
...


w+

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


a+

Opens a text file for reading and writing both
...
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 provide by C standard library to read and write a file character
by character or in the form of a fixed length string
...


Writing a File
Following is the simplest function to write individual characters to a stream:

int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream
referenced by fp
...
You can use the following functions to write a null-terminated string to a
stream:

int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp
...
You can
use int fprintf(FILE *fp,const char *format,
...

Try the following example:

#include ...
txt", "w+");
fprintf(fp, "This is testing for fprintf
...
\n", fp);
fclose(fp);
}

TUTORIALS POINT
Simply Easy Learning

Page 112

When the above code is compiled and executed, it creates a new file test
...
Let us read this file in 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 previous section
and produces the following result:

1 : This
2: is testing for fprintf
...

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


TUTORIALS POINT
Simply Easy Learning

Page 114

CHAPTER

23
Preprocessors

T

he C Preprocessor is not part of the compiler, but is a separate step in the

compilation process
...
We'll
refer to the C Preprocessor as the CPP
...
It must be the first nonblank
character, and for readability, a preprocessor directive should begin in first column
...


#define MAX_ARRAY_LENGTH 20

TUTORIALS POINT
Simply Easy Learning

Page 115

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
This tells the CPP to undefine existing FILE_SIZE and define it as 42
...


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


__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 that
has 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:

TUTORIALS POINT
Simply Easy Learning

Page 117

Carole and Debra: We love you!

Token Pasting (##)
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;
}

TUTORIALS POINT
Simply Easy Learning

Page 118

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 ...
h which contains C function declarations and

macro definitions and to be shared between several source files
...

You request the use of a header file in your program by including it, with the C
preprocessing directive #include like you have seen inclusion of stdio
...
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 header files and include that header file
wherever it is required
...

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


TUTORIALS POINT
Simply Easy Learning

Page 120

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

int x;
char *test (void);
int main (void)
{
puts (test ());
}

Once-Only Headers
If a header file happens to be included twice, the compiler will process its contents twice
and will result an error
...
When the header is included
again, the conditional will be false, because HEADER_FILE is defined
...


TUTORIALS POINT
Simply Easy Learning

Page 121

Computed Includes
Sometimes it is necessary to select one of several different header files to be included into
your program
...
You could do this with a series of conditionals as follows:

#if SYSTEM_1
# include "system_1
...
h"
#elif SYSTEM_3

...
This is called a computed include
...
h"

...
h as if
the #include had been written that way originally
...


TUTORIALS POINT
Simply Easy Learning

Page 122

CHAPTER

25
Type Casting

T

ype casting is a way to convert a variable from one data type to another data type
...
You can convert 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 in an int:

#include ...


Usual Arithmetic Conversion
The usual arithmetic conversions are implicitly performed to cast their values in a
common type
...
Let us take following example to understand the concept:

#include ...
000000
Here, it is simple to understand that first c gets converted to integer but because final
value is double, so usual arithmetic conversion applies and compiler convert i and c into
float and add them yielding a float result
...
Most of the C or even Unix function calls return -1 or NULL in case of any
error and sets an error code errno is set which is global variable and indicates an error
occurred during any function call
...
h>
header file
...
As a good practice, developer should set errno to 0 at the
time of initialization of the program
...


The 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 a pointer to the textual 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
...
Same applies in

programming languages as well where if a programming allows you to call a function inside
the same function that is called recursive call of the function as follows
...
e
...
But while
using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go in infinite loop
...


Number Factorial
Following is an example, which calculates factorial for a given number using a recursive
function:

#include ...
h>
int fibonaci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonaci(i-1) + fibonaci(i-2);
}
int
{

main()
int i;
for (i = 0; i < 10; i++)
{
printf("%d\t%n", fibonaci(i));
}
return 0;

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

0 1

1

2

3

TUTORIALS POINT
Simply Easy Learning

5

8

13

21

34

Page 130

CHAPTER

28
Variable Arguments

S

ometimes, 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 total number
variable arguments passed
...
h header file which provides functions and macros to implement the functionality
of variable arguments and follow the following steps:







Define a function with last parameter as ellipses and the one just before the ellipses is
always an int which will represent number of arguments
...
This type is defined in stdarg
...

Use int parameter and va_start macro to initialize the va_list variable to an argument
list
...
h header file
...

Use a macro va_end to clean up the memory assigned to va_list variable
...
h>

TUTORIALS POINT
Simply Easy Learning

Page 131

#include ...
)
{
va_list valist;
double sum = 0
...
It should
be noted that the function average() has been called twice and each time first argument
represents the total number of variable arguments being passed
...


Average of 2, 3, 4, 5 = 3
...
000000

TUTORIALS POINT
Simply Easy Learning

Page 132

CHAPTER

29
Memory Management

T

his chapter will explain 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 whose 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 doing programming, if you are aware about 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 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 you defined the size can not be changed
...

Alternatively, you can increase or decrease the size of an allocated memory block by calling
the functionrealloc()
...
h>
#include ...
h>
int main()
{
char name[100];
char *description;

TUTORIALS POINT
Simply Easy Learning

Page 134

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


TUTORIALS POINT
Simply Easy Learning

Page 135

CHAPTER

30
Command Line Arguments

I

t is possible to pass some values from the command line to your C programs when

they are executed
...

The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer array which
points to each argument passed to the program
...
h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied
...
\n");
}
}
When the above code is compiled and executed with a single argument, it produces the
following result
...
/a
...


TUTORIALS POINT
Simply Easy Learning

Page 136

$
...
out testing1 testing2
Too many arguments supplied
...


$
...
out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a
pointer to the first command line argument supplied, and *argv[n] is the last argument
...

You pass all the command line arguments separated by a space, but if argument itself has
a space then you can pass such arguments by putting them inside double quotes "" or
single quotes ''
...
h>
int main( int argc, char *argv[] )
{
printf("Program name %s\n", argv[0]);
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied
...
\n");
}
}
When the above code is compiled and executed with a single argument separated by space
but inside double quotes, it produces the following result
...
/a
...
/a
Title: c programming tuitorial-copy
Description: This purposely for someone undertaking programming course in C language.The notes are well detailed and simple to understand.They have pictorial diagrams and worked out problems on C programming ,again for easier understanding of your course.I hope you will love this