C Programming Tutorial
C Programming Tutorial
tutorialspoint.com
i
Table of Contents
C Language Overview .............................................................. 1
Facts about C ............................................................................................... 1
Why to use C ? ............................................................................................. 2
C Programs .................................................................................................. 2
C Environment Setup ............................................................... 3
Text Editor ................................................................................................... 3
The C Compiler ............................................................................................ 3
Installation on Unix/Linux ............................................................................. 4
Installation on Mac OS .................................................................................. 4
Installation on Windows ............................................................................... 4
C Program Structure ................................................................ 5
C Hello World Example ................................................................................. 5
Compile & Execute C Program ....................................................................... 6
C Basic Syntax ......................................................................... 7
Tokens in C .................................................................................................. 7
Semicolons ; ................................................................................................ 7
Comments ................................................................................................... 8
Identifiers .................................................................................................... 8
Keywords .................................................................................................... 8
Whitespace in C ........................................................................................... 9
C Data Types ......................................................................... 10
Integer Types ............................................................................................. 10
Floating-Point Types ................................................................................... 11
The void Type ............................................................................................ 12
C Variables ............................................................................ 13
Variable Declaration in C ................................Error! Bookmark not defined.
Variable Initialization in C ...............................Error! Bookmark not defined.
Lvalues and Rvalues in C ............................................................................. 15
C Constants and Literals ........................................................ 17
Integer literals............................................................................................ 17
Floating-point literals.................................................................................. 18
Character constants.................................................................................... 18
iii
The ? : Operator ......................................................................................... 44
C Loops.................................................................................. 45
while loop in C ........................................................................................... 46
Syntax ..................................................................................................... 46
Flow Diagram .......................................................................................... 46
Example .................................................................................................. 47
for loop in C ............................................................................................... 47
Syntax ..................................................................................................... 47
Flow Diagram .......................................................................................... 48
Example .................................................................................................. 48
do...while loop in C ..................................................................................... 49
Syntax ..................................................................................................... 49
Flow Diagram .......................................................................................... 50
Example .................................................................................................. 50
nested loops in C ........................................................................................ 51
Syntax ..................................................................................................... 51
Example .................................................................................................. 52
break statement in C .................................................................................. 53
Syntax ..................................................................................................... 53
Flow Diagram .......................................................................................... 53
Example .................................................................................................. 54
continue statement in C .............................................................................. 54
Syntax ..................................................................................................... 54
Flow Diagram .......................................................................................... 55
Example .................................................................................................. 55
goto statement in C .................................................................................... 56
Syntax ..................................................................................................... 56
Flow Diagram .......................................................................................... 56
Example .................................................................................................. 57
The Infinite Loop ........................................................................................ 57
C Functions ............................................................................ 59
Defining a Function .................................................................................... 59
Example .................................................................................................. 60
Function Declarations ................................................................................. 60
Calling a Function ....................................................................................... 60
Function Arguments ................................................................................... 61
Function call by value ............................................................................. 62
Function call by reference ....................................................................... 63
C Scope Rules ....................................................................... 65
iii
Accessing Union Members ........................................................................ 101
Bit Fields .............................................................................. 103
Bit Field Declaration ................................................................................. 104
Typedef ................................................................................ 106
typedef vs #define .................................................................................... 107
Input & Output ...................................................................... 108
The Standard Files .................................................................................... 108
The getchar() & putchar() functions ........................................................... 108
The gets() & puts() functions ..................................................................... 109
The scanf() and printf() functions ............................................................... 110
File I/O ................................................................................. 111
Opening Files ........................................................................................... 111
Closing a File ............................................................................................ 112
Writing a File ........................................................................................... 112
Reading a File........................................................................................... 113
Binary I/O Functions ................................................................................. 114
Preprocessors ...................................................................... 115
Preprocessors Examples............................................................................ 115
Predefined Macros ................................................................................... 116
Preprocessor Operators ............................................................................ 117
Macro Continuation (\) .......................................................................... 117
Stringize (#) ........................................................................................... 117
Token Pasting (##)................................................................................ 118
The defined() Operator ......................................................................... 118
Parameterized Macros .............................................................................. 119
Header Files ......................................................................... 120
Include Syntax.......................................................................................... 120
Include Operation .................................................................................... 121
Once-Only Headers .................................................................................. 121
Computed Includes................................................................................... 122
Type Casting ........................................................................ 123
Integer Promotion .................................................................................... 124
Usual Arithmetic Conversion ..................................................................... 124
Error Handling ...................................................................... 126
The errno, perror() and strerror() ............................................................... 126
Divide by zero errors ................................................................................ 127
Program Exit Status .................................................................................. 128
Recursion ............................................................................. 129
Number Factorial ..................................................................................... 129
iii
1
CHAPTER
C Language Overview
This chapter describes the basic details about C programming language, how it emerged,
what are strengths of C and why we should use C.
originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell
Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.
In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available
description of C, now known as the K&R standard.
The UNIX operating system, the C compiler, and essentially all UNIX applications programs
have been written in C. The C has now become a widely used professional language for
various reasons.
Easy to learn
Structured language
Facts about C
C was invented to write an operating system called UNIX.
The language was formalized in 1988 by the American National Standard Institute.
(ANSI).
TUTORIALS POINT
Simply Easy Learning Page 1
2
CHAPTER
C Environment Setup
This section describes how to set up your system environment before you start doing your
programming using C language.
Before you start doing programming using C programming language, you need the following
two softwares available on your computer, (a) Text Editor and (b) The C Compiler.
Text Editor
This will be used to type your program. Examples of few editors include Windows Notepad,
OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
Name and version of text editor can vary on different operating systems. For example,
Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or
UNIX.
The files you create with your editor are called source files and contain program source
code. The source files for C programs are typically named with the extension “.c”.
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.
The C Compiler
The source code written in source file is the human readable source for your program. It
needs to be "compiled", to turn into machine language so that your CPU can actually
execute the program as per instructions given.
This C programming language compiler will be used to compile your source code into final
executable program. I assume you have basic knowledge about a programming language
compiler.
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.
Following section guides you on how to install GNU C/C++ compiler on various OS. I'm
mentioning C/C++ together because GNU gcc compiler works for both C and C++
programming languages.
TUTORIALS POINT
Simply Easy Learning Page 3
3
CHAPTER
C Program Structure
Let’s look into Hello World example using C Programming Language.
B efore we study basic building blocks of the C programming language, let us look a
Preprocessor Commands
Functions
Variables
Comments
Let us look at a simple code that would print the words "Hello World":
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
TUTORIALS POINT
Simply Easy Learning Page 5
4
CHAPTER
C Basic Syntax
This chapter will give details about all the basic syntax about C programming language
including tokens, keywords, identifiers, etc.
Tokens in C
A C program consists of various tokens and a token is either a keyword, an identifier, a
constant, a string literal, or a symbol. For example, the following C statement consists of
five tokens:
printf
(
"Hello, World! \n"
)
;
Semicolons ;
In C program, the semicolon is a statement terminator. That is, each individual statement
must be ended with a semicolon. It indicates the end of one logical entity.
TUTORIALS POINT
Simply Easy Learning Page 7
Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line, and a
C compiler totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters and
comments. Whitespace separates one part of a statement from another and enables the
compiler to identify where one element in a statement, such as int, ends and the next
element begins. Therefore, in the following statement:
int age;
There must be at least one whitespace character (usually a space) between int and age for
the compiler to be able to distinguish them. On the other hand, in the following statement:
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.
TUTORIALS POINT
Simply Easy Learning Page 9
signed char 1 byte -128 to 127
To get the exact size of a type or a variable on a particular platform, you can use
the sizeof operator. The expressions sizeof(type) yields the storage size of the object or
type in bytes. Following is an example to get the size of int type on any machine:
#include <stdio.h>
#include <limits.h>
int main()
{
printf("Storage size for int : %d \n", sizeof(int));
return 0;
}
When you compile and execute the above program, it produces the following result on
Linux:
Floating-Point Types
Following table gives you details about standard floating-point types with storage sizes and
value ranges and their precision:
The header file float.h defines macros that allow you to use these values and other details
about the binary representation of real numbers in your programs. Following example will
print storage space taken by a float type and its range values:
#include <stdio.h>
#include <float.h>
int main()
TUTORIALS POINT
Simply Easy Learning Page 11
6
CHAPTER
C Variables
A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and layout of
the variable's memory; the range of values that can be stored within that memory; and the
set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It
must begin with either a letter or an underscore. Upper and lowercase letters are distinct
because C is case-sensitive. Based on the basic types explained in previous chapter, there
will be the following basic variable types:
Type Description
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.
For this chapter, let us study only basic variable types.
Variable Definition in C:
A variable definition means to tell the compiler where and how much to create the storage for the
variable. 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 user-
defined object, etc., and variable_list may consist of one or more identifier names separated by
commas. Some valid declarations are shown here:
TUTORIALS POINT
Simply Easy Learning Page 13
b =20;
c = a + b;
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of c : 30
value of f : 23.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. For example:
// function declaration
int func();
int main()
{
// function call
int i = func();
}
// function definition
int func()
{
return 0;
}
1. lvalue: An expression that is an lvalue may appear as either the left-hand or right-hand
side of an assignment.
2. rvalue: An expression that is an rvalue may appear on the right- but not left-hand side
of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric
literals are rvalues and so may not be assigned and cannot appear on the left-hand side.
Following is a valid statement:
int g = 20;
But following is not a valid statement and would generate compile-time error:
TUTORIALS POINT
Simply Easy Learning Page 15
7
CHAPTER
T he constants refer to fixed values that the program may not alter during its
Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are also enumeration
constants as well.
The constants are treated just like regular variables except that their values cannot be
modified after their definition.
Integer literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the
base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and
long, respectively. The suffix can be uppercase or lowercase and can be in any order.
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
TUTORIALS POINT
Simply Easy Learning Page 17
\xhh . . . Hexadecimal number of one or more digits
#include <stdio.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 "". A string contains characters
that are similar to character literals: plain characters, escape sequences, and universal
characters.
You can break a long line into multiple lines using string literals and separating them using
whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
Defining Constants
There are two simple ways in C to define constants:
TUTORIALS POINT
Simply Easy Learning Page 19
value of area : 50
TUTORIALS POINT
Simply Easy Learning Page 21
The register should only be used for variables that require quick access such as counters. It
should also be noted that defining 'register' does not mean that the variable will be stored
in a register. It means that it MIGHT be stored in a register depending on hardware and
implementation restrictions.
The static modifier may also be applied to global variables. When this is done, it causes
that variable's scope to be restricted to the file in which it is declared.
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.
#include <stdio.h>
/* function declaration */
void func(void);
main()
{
while(count--)
{
func();
}
return 0;
}
/* function definition */
void func( void )
{
static int i = 5; /* local static variable */
i++;
You may not understand this example at this time because I have used function and global
variables, which I have not explained so far. So for now, let us proceed even if you do not
understand it completely. 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
9
CHAPTER
C Operators
A n operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C language is rich in built-in operators and provides the following types of
operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other
operators one by one.
Arithmetic Operators
Following table shows all the arithmetic operators supported by C language. Assume
variable A holds 10 and variable B holds 20, then:
TUTORIALS POINT
Simply Easy Learning Page 25
Checks if the values of two operands are equal or not, if
== (A == B) is not true.
yes then condition becomes true.
Try the following example to understand all the relational operators available in C
programming language:
#include <stdio.h>
main()
{
int a = 21;
int b = 10;
int c ;
if( a == b )
{
printf("Line 1 - a is equal to b\n" );
}
else
{
printf("Line 1 - a is not equal to b\n" );
}
if ( a < b )
{
printf("Line 2 - a is less than b\n" );
}
else
{
printf("Line 2 - a is not less than b\n" );
}
if ( a > b )
{
printf("Line 3 - a is greater than b\n" );
}
else
{
printf("Line 3 - a is not greater than b\n" );
}
/* Lets change value of a and b */
a = 5;
b = 20;
if ( a <= b )
TUTORIALS POINT
Simply Easy Learning Page 27
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:
Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. The truth tables for &, |,
and ^ are as follows:
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
TUTORIALS POINT
Simply Easy Learning Page 29
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
Assignment Operators
There are following assignment operators supported by C language:
Try the following example to understand all the assignment operators available in C
programming language:
TUTORIALS POINT
Simply Easy Learning Page 31
Line 9 - &= Operator Example, Value of c = 2
Line 10 - ^= Operator Example, Value of c = 0
Line 11 - |= Operator Example, Value of c = 2
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression. This affects how
an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
TUTORIALS POINT
Simply Easy Learning Page 33
CHAPTER
10
Decision Making in C
D ecision making structures require that the programmer specify one or more
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. C programming language provides
following types of decision making statements.
TUTORIALS POINT
Simply Easy Learning Page 35
/* 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:
if...else statement
An if statement can be followed by an optional else statement, which executes when the
boolean expression is false.
Syntax
The syntax of an if...else statement in C programming language is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
C programming language assumes any non-zero and non-null values as true and if it is
either zero or null then it is assumed as false value.
TUTORIALS POINT
Simply Easy Learning Page 37
The if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind:
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax
The syntax of an if...else if...else statement in C programming language is:
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
TUTORIALS POINT
Simply Easy Learning Page 39
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:
switch statement
A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each switch case.
Syntax
The syntax for a switch statement in C programming language is as follows:
switch(expression){
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
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.
TUTORIALS POINT
Simply Easy Learning Page 41
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
Syntax
The syntax for a nested switch statement is as follows:
switch(ch1) {
case 'A':
printf("This A is part of outer switch" );
switch(ch2) {
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* case code */
}
break;
case 'B': /* case code */
}
Example
#include <stdio.h>
int main ()
{
TUTORIALS POINT
Simply Easy Learning Page 43
CHAPTER
11
C Loops
T here may be a situation, when you need to execute a block of code several number
Programming languages provide various control structures that allow for more complicated
execution paths.
TUTORIALS POINT
Simply Easy Learning Page 45
Here, key point of the while loop is that the loop might not ever run. 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.
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
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.
Syntax
The syntax of a for loop in C programming language is:
TUTORIALS POINT
Simply Easy Learning Page 47
{
/* 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
Unlike for and while loops, which test the loop condition at the top of the loop,
the do...while loop in C programming language checks its condition at the bottom of the
loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax
The syntax of a do...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 execute once before the condition is tested.
TUTORIALS POINT
Simply Easy Learning Page 49
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
nested loops in C
C programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.
Syntax
The syntax for a nested for loop statement in C is as follows:
The syntax for a nested while loop statement in C programming language is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
TUTORIALS POINT
Simply Easy Learning Page 51
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
break statement in C
The break statement in C programming language has the following two usages:
1. 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.
2. It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops (i.e., one loop inside another loop), the break statement
will stop the execution of the innermost loop and start executing the next line of code after
the block.
Syntax
The syntax for a break statement in C is as follows:
break;
Flow Diagram
TUTORIALS POINT
Simply Easy Learning Page 53
Flow Diagram
Example
#include <stdio.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++;
}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
TUTORIALS POINT
Simply Easy Learning Page 55
Example
#include <stdio.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
#include <stdio.h>
int main ()
{
TUTORIALS POINT
Simply Easy Learning Page 57
CHAPTER
12
C Functions
F unction is a group of statements that together perform a task. Every C program has at least
one function, which is main(), and all the most trivial programs can define additional
functions.
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is so each function
performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For
example, function strcat() to concatenate two strings, function memcpy() to copy one
memory location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure, etc.
Defining a Function
The general form of a function definition in C programming language is as follows:
Return Type: A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
TUTORIALS POINT
Simply Easy Learning Page 59
When a program calls a function, program control is transferred to the called function. 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.
To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value. For example:
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
return 0;
}
return result;
}
I kept max() function along with main() function and compiled the source code. While
running final executable, it would produce the following result:
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.
TUTORIALS POINT
Simply Easy Learning Page 61
After swap, value of a :100
After swap, value of b :200
Which shows that there is no change in the values though they had been changed inside
the function.
To pass the value by reference, argument pointers are passed to the functions just like
any other value. 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.
return;
}
Let us call the function swap() by passing values by reference as in the following example:
#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
TUTORIALS POINT
Simply Easy Learning Page 63
CHAPTER
13
C Scope Rules
A scope in any programming is a region of the program where a defined variable can have
its existence and beyond that variable cannot be accessed. There are three places where
variables can be declared in C programming language:
Let us explain what are local and global variables and formal parameters.
Local Variables
Variables that are declared inside a function or block are called local variables. They can
be used only by statements that are inside that function or block of code. Local variables
are not known to functions outside their own. Following is the example using local
variables. Here all the variables a, b and c are local to main() function.
#include <stdio.h>
int main ()
{
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
return 0;
}
TUTORIALS POINT
Simply Easy Learning Page 65
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. Following is an
example:
#include <stdio.h>
int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
return 0;
}
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
int 0
TUTORIALS POINT
Simply Easy Learning Page 67
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. An array is used to store a
collection of data, but it is often more useful to think of an array as a collection of variables
of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by
an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.
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:
double balance[10];
Now balance is a variable array which is sufficient to hold up-to 10 double numbers.
TUTORIALS POINT
Simply Easy Learning Page 69
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Multi-dimensional Arrays
C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration:
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:
int threedim[5][10][4];
Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size x, y you would write something as follows:
type arrayName [ x ][ y ];
TUTORIALS POINT
Simply Easy Learning Page 71
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
When the above code is compiled and executed, it produces the following result:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is
likely that most of the arrays you create will be of one or two dimensions.
Way-1
Formal parameters as a pointer as follows. You will study what is pointer in next chapter.
TUTORIALS POINT
Simply Easy Learning Page 73
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
return 0;
}
When the above code is compiled together and executed, it produces the following result:
As you can see, the length of the array doesn't matter as far as the function is concerned
because C performs no bounds checking for the formal parameters.
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()
{
.
.
.
}
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.
Now, consider the following function which will generate 10 random numbers and return
them using an array and call this function as follows:
#include <stdio.h>
TUTORIALS POINT
Simply Easy Learning Page 75
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.
double balance[50];
balance is a pointer to &balance[0], which is the address of the first element of the array
balance. Thus, the following program fragment assigns p 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. Therefore, *(balance +
4) is a legitimate way of accessing the data at balance[4].
Once you store the address of first element in p, you can access array elements using *p,
*(p+1), *(p+2) and so on. Below is the example to show all the concepts discussed above:
#include <stdio.h>
int main ()
{
/* an array with 5 elements */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;
p = balance;
return 0;
}
When the above code is compiled and executed, it produces the following result:
TUTORIALS POINT
Simply Easy Learning Page 77
CHAPTER
15
C Pointers
P ointers in C are easy and fun to learn. Some C programming tasks are performed
more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be
performed without using pointers. So it becomes necessary to learn pointers to become a
perfect C programmer. Let's start learning them in simple and easy steps.
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.
Consider the following example, which will print the address of the variables defined:
#include <stdio.h>
int main ()
{
int var1;
char var2[10];
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
So you understood what is memory address and how to access it, so base of the concept is
over. Now let us see what is a pointer.
TUTORIALS POINT
Simply Easy Learning Page 79
When the above code is compiled and executed, it produces result something as follows:
NULL Pointers in C
It is always a good practice to assign a NULL value to a pointer variable in case you do not
have exact address to be assigned. This is done at the time of variable declaration. A
pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries.
Consider the following program:
#include <stdio.h>
int main ()
{
int *ptr = NULL;
return 0;
}
When the above code is compiled and executed, it produces the following result:
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. However, the
memory address 0 has special significance; it signals that the pointer is not intended to
point to an accessible memory location. But by convention, if a pointer contains the null
(zero) value, it is assumed to point to nothing.
Pointer arithmetic
As explained in main chapter, C pointer is an address, which is a numeric value. Therefore,
you can perform arithmetic operations on a pointer just as you can a numeric value. There
are four arithmetic operators that can be used on pointers: ++, --, +, and -
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points
to the address 1000. Assuming 32-bit integers, let us perform the following arithmetic
operation on the pointer:
TUTORIALS POINT
Simply Easy Learning Page 81
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 <stdio.h>
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr;
When the above code is compiled and executed, it produces result something as follows:
Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. 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.
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 <stdio.h>
TUTORIALS POINT
Simply Easy Learning Page 83
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. Following is the declaration of an array of
pointers to an integer:
int *ptr[MAX];
This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds
a pointer to an int value. Following example makes use of three integers, which will be
stored in an array of pointers as follows:
#include <stdio.h>
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr[MAX];
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 <stdio.h>
int main ()
{
char *names[] = {
TUTORIALS POINT
Simply Easy Learning Page 85
/* take the address of var */
ptr = &var;
return 0;
}
When the above code is compiled and executed, it produces the following result:
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 <stdio.h>
#include <time.h>
int main ()
{
unsigned long sec;
getSeconds( &sec );
return 0;
}
TUTORIALS POINT
Simply Easy Learning Page 87
.
.
.
}
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.
Now, consider the following function, which will generate 10 random numbers and returns
them using an array name which represents a pointer, i.e., address of first array element.
#include <stdio.h>
#include <time.h>
return r;
}
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:
1523198053
1187214107
1108300978
430494959
TUTORIALS POINT
Simply Easy Learning Page 89
CHAPTER
16
C Strings
The following declaration and initialization create a string consisting of the word "Hello".
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".
If you follow the rule of array initialization then you can write the above statement as
follows:
Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try
to print above mentioned string:
#include <stdio.h>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
return 0;
}
TUTORIALS POINT
Simply Easy Learning Page 91
strcat( str1, str2): HelloWorld
strlen(str1) : 10
You can find a complete list of C string related functions in C Standard Library.
TUTORIALS POINT
Simply Easy Learning Page 93
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
#include <stdio.h>
#include <string.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.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
return 0;
}
TUTORIALS POINT
Simply Easy Learning Page 95
printBook( Book2 );
return 0;
}
void printBook( struct Books book )
{
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}
When the above code is compiled and executed, it produces the following result:
Pointers to Structures
You can define pointers to structures in very similar way as you define pointer to any other
variable as follows:
Now, you can store the address of a structure variable in the above defined pointer
variable. 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;
Let us re-write above example using structure pointer, hope this will be easy for you to
understand the concept:
#include <stdio.h>
TUTORIALS POINT
Simply Easy Learning Page 97
Book subject : Telecom Billing Tutorial
Book book_id : 6495700
TUTORIALS POINT
Simply Easy Learning Page 99
The memory occupied by a union will be large enough to hold the largest member of the
union. For example, in above example Data type will occupy 20 bytes of memory space
because this is the maximum space which can be occupied by character string. Following is
the example which will display total memory size occupied by the above union:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
return 0;
}
When the above code is compiled and executed, it produces the following result:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
TUTORIALS POINT
Simply Easy Learning Page 101
CHAPTER
19
Bit Fields
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. The C programming language offers a better way to utilize
the memory space in such situation. 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. 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. If you will use up to 32 variables each one with a
width of 1 bit , then also status structure will use 4 bytes, but as soon as you will have 33
variables, then it will allocate next slot of the memory and it will start using 64 bytes. Let
us check the following example to understand the concept:
#include <stdio.h>
#include <string.h>
TUTORIALS POINT
Simply Easy Learning Page 103
#include <stdio.h>
#include <string.h>
struct
{
unsigned int age : 3;
} Age;
int main( )
{
Age.age = 4;
printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
printf( "Age.age : %d\n", Age.age );
Age.age = 7;
printf( "Age.age : %d\n", Age.age );
Age.age = 8;
printf( "Age.age : %d\n", 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 : 4
Age.age : 7
Age.age : 0
TUTORIALS POINT
Simply Easy Learning Page 105
book.book_id = 6495407;
return 0;
}
When the above code is compiled and executed, it produces the following result:
typedef vs #define
The #define is a C-directive which is also used to define the aliases for various data types
similar to typedef but with three differences:
The typedef is limited to giving symbolic names to types only where as #define can be
used to define alias for values as well, like you can define 1 as ONE etc.
#include <stdio.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
in the loop in case you want to display more than one character on the screen. Check the
following example:
#include <stdio.h>
int main( )
{
int 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:
$./a.out
Enter a value : this is test
You entered: t
The int puts(const char *s) function writes the string s and a trailing newline to stdout.
#include <stdio.h>
int main( )
{
char str[100];
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 complete line till
end and displays it as follows:
$./a.out
Enter a value : this is test
TUTORIALS POINT
Simply Easy Learning Page 109
CHAPTER
22
File I/O
L ast chapter explained about standard input and output devices handled by C
programming language. This chapter we will see how C programmers can create, open,
close text or binary files for their data storage.
A file represents a sequence of bytes, does not matter if it is a text file or binary file. C
programming language provides access on high level functions as well as low level (OS
level) calls to handle file on your storage devices. This chapter will take you through
important calls for the file management.
Opening Files
You can use the fopen( ) function to create a new file or to open an existing file, this call
will initialize an object of the type FILE, which contains all the information necessary to
control the stream. Following is the prototype of this function call:
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
Opens a text file for writing, if it does not exist then a new file is created. Here your program will
w
start writing content from the beginning of the file.
Opens a text file for writing in appending mode, if it does not exist then a new file is created.
a
Here your program will start appending content in the existing file content.
Opens a text file for reading and writing both. It first truncate the file to zero length if it exists
w+
otherwise create the file if it does not exist.
Opens a text file for reading and writing both. It creates the file if it does not exist. The reading
a+
will start from the beginning but writing can only be appended.
TUTORIALS POINT
Simply Easy Learning Page 111
When the above code is compiled and executed, it creates a new file test.txt in /tmp
directory and writes two lines using two different functions. Let us read this file in next
section.
Reading a File
Following is the simplest function to read a single character from a file:
The fgetc() function reads a character from the input file referenced by fp. The return value
is the character read, or in case of any error it returns EOF. The following functions allow
you to read a string from a stream:
The functions fgets() reads up to n - 1 characters from the input stream referenced by fp.
It copies the read string into the buffer buf, appending a null character to terminate the
string.
If this function encounters a newline character '\n' or the end of the file EOF before they
have read the maximum number of characters, then it returns only the characters read up
to that point including new line character. You can also use int fscanf(FILE *fp, const char
*format, ...) function to read strings from a file but it stops reading after the first space
character encounters.
#include <stdio.h>
main()
{
FILE *fp;
char buff[100];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );
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...
TUTORIALS POINT
Simply Easy Learning Page 113
CHAPTER
23
Preprocessors
All preprocessor commands begin with a pound symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in first column.
Following section lists down all important preprocessor directives:
Directive Description
Preprocessors Examples
Analyze following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
TUTORIALS POINT
Simply Easy Learning Page 115
{
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("ANSI :%d\n", __STDC__ );
When the above code in a file test.c is compiled and executed, it produces the following
result:
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1
Preprocessor Operators
The C preprocessor offers following operators to help you in creating macros:
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
Stringize (#)
The stringize or number-sign operator ('#'), when used within a macro definition, converts
a macro parameter into a string constant. This operator may be used only in a macro that
has a specified argument or parameter list. For example:
#include <stdio.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
When the above code is compiled and executed, it produces the following result:
Parameterized Macros
One of the powerful functions of the CPP is the ability to simulate functions using
parameterized macros. For example, we might have some code to square a number as
follows:
int square(int x) {
return x * x;
}
Macros with arguments must be defined using the #define directive before they can be
used. The argument list is enclosed in parentheses and must immediately follow the macro
name. Spaces are not allowed between and macro name and open parenthesis. For
example:
#include <stdio.h>
int main(void)
{
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}
When the above code is compiled and executed, it produces the following result:
TUTORIALS POINT
Simply Easy Learning Page 119
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. The output from the
preprocessor contains the output already generated, followed by the output resulting from
the included file, followed by the output that comes from the text after
the #include directive. For example, if you have a header file header.h as follows:
and a main program called program.c that uses the header file, like this:
int x;
#include "header.h"
the compiler will see the same token stream as it would if program.c read
int x;
char *test (void);
Once-Only Headers
If a header file happens to be included twice, the compiler will process its contents twice
and will result an error. 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
#endif
This construct is commonly known as a wrapper #ifndef. When the header is included
again, the conditional will be false, because HEADER_FILE is defined. The preprocessor will
skip over the entire contents of the file, and the compiler will not see it twice.
TUTORIALS POINT
Simply Easy Learning Page 121
CHAPTER
25
Type Casting
T ype casting is a way to convert a variable from one data type to another data type.
For example, if you want to store a long value into a simple integer then you can type cast
long to int. 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 <stdio.h>
main()
{
int sum = 17, count = 5;
double mean;
When the above code is compiled and executed, it produces the following result:
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.
TUTORIALS POINT
Simply Easy Learning Page 123
The usual arithmetic conversions are not performed for the assignment operators, nor for
the logical operators && and ||. Let us take following example to understand the concept:
#include <stdio.h>
main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %f\n", sum );
When the above code is compiled and executed, it produces the following result:
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.
TUTORIALS POINT
Simply Easy Learning Page 125
pf = fopen ("unexist.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
The code below fixes this by checking if the divisor is zero before dividing:
#include <stdio.h>
#include <stdlib.h>
main()
{
int dividend = 20;
int divisor = 0;
int quotient;
exit(0);
}
When the above code is compiled and executed, it produces the following result:
TUTORIALS POINT
Simply Easy Learning Page 127
CHAPTER
27
Recursion
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.
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go in infinite loop.
Recursive function are very useful to solve many mathematical problems like to calculate
factorial of a number, generating Fibonacci series, etc.
Number Factorial
Following is an example, which calculates factorial for a given number using a recursive
function:
#include <stdio.h>
TUTORIALS POINT
Simply Easy Learning Page 129
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.e., parameters, instead of predefined
number of parameters. The C programming language provides a solution for this situation
and you are allowed to define a function which can accept variable number of parameters
based on your requirement. The following example shows the definition of such a function.
int main()
{
func(1, 2, 3);
func(1, 2, 3, 4);
}
It should be noted that function func() has last argument as ellipses i.e. three dotes (...)
and the one just before the ellipses is always an int which will represent total number
variable arguments passed. To use such functionality you need to make use
of stdarg.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.
Create a va_list type variable in the function definition. This type is defined in stdarg.h
header file.
Use int parameter and va_start macro to initialize the va_list variable to an argument
list. The macro va_start is defined in stdarg.h header file.
Use va_arg macro and va_list variable to access each item in argument list.
Use a macro va_end to clean up the memory assigned to va_list variable.
Now let us follow the above steps and write down a simple function which can take variable
number of parameters and returns their average:
#include <stdio.h>
TUTORIALS POINT
Simply Easy Learning Page 131
CHAPTER
29
Memory Management
language provides several functions for memory allocation and management. These
functions can be found in the<stdlib.h> header file.
char name[100];
But now let us consider a situation where you have no idea about the length of the text you
need to store, for example you want to store a detailed description about a topic. 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char name[100];
TUTORIALS POINT
Simply Easy Learning Page 133
strcpy(name, "Zara Ali");
When the above code is compiled and executed, it produces the following result.
You can try above example without re-allocating extra memory and strcat() function will
give an error due to lack of available memory in description.
TUTORIALS POINT
Simply Easy Learning Page 135
$./a.out testing1 testing2
Too many arguments supplied.
When the above code is compiled and executed without passing any argument, it produces
the following result.
$./a.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. If
no arguments are supplied, argc will be one, otherwise and if you pass one argument
then argc is set at 2.
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 ''. 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 <stdio.h>
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\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.
TUTORIALS POINT
Simply Easy Learning Page 137