"Basic of C and C++ ": Summer Training Report
"Basic of C and C++ ": Summer Training Report
Session: 2019-20
1
Certificate
2
ACKNOWLEDGEMENT
First of all, I am thankful to Associate Prof Mr Ankush sir and under whose guidance I have
timely completed the report. I Feel pleasure in acknowledging my deepest gratitude to Principal
Dr.Ramesh Kumar Pachar and Head of Dept. Dr. Akash Saxena. Providing me opportunity
of practical training. The internship opportunity I had with c and c++ was a great chance for
learning and professional development. Therefore, I consider myself as a very lucky individual
as I was provided with an opportunity to be a part of it. I am also grateful for having a chance to
meet so many wonderful people and professionals who led me though this internship period.
I find it hard to express my grateful to the almighty in words for bestowing upon me his deepest
blessings and providing me with the most wonderful opportunity in the form of life of a human
being and for the warmth and kindness he has showered upon me by giving me life’s best
I am also grateful to Er. G.K.Rathi to support me at each and every step of my training
Schedule. I attribute hearties thanks to all Engineering departments and Engineers for their
Ample Guidance during my training period..
Last but not least I am thankful to all who helped me direct or indirect for my endeavour.
Himasnhu Soni
(16ESKEE722)
(VII Sem Electrical)
3
Overview
C is a general-purpose, high-level language that was 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
application programs have been written in C. C has now become a
widely used professional language for various reasons:
Easy to learn
Structured language
It produces efficient programs
It can handle low-level activities
It can be compiled on a variety of computer platforms
Facts about C
C was invented to write an operating system called UNIX.
C is a successor of B language which was introduced
around the early 1970s.
The language was formalized in 1988 by the American
National Standard Institute (ANSI).
The UNIX OS was totally written in C.
Today C is the most widely used and popular System
Programming Language.
Most of the state-of-the-art software have been
implemented using C.
Today's most popular Linux OS and RDBMS MySQL have
been written in C.
4
Facts about C
C was invented to write an operating system called UNIX.
C is a successor of B language which was introduced
around the early 1970s.
The language was formalized in 1988 by the American
National Standard Institute (ANSI).
The UNIX OS was totally written in C.
Today C is the most widely used and popular System
Programming Language.
Most of the state-of-the-art software have been
implemented using C.
Today's most popular Linux OS and RDBMS MySQL have
been written in C.
Why Use C ?
C was initially used for system development work,
particularly the programs that
make-up the operating system. C was adopted as a
system development
language because it produces code that runs nearly as
fast as the code written
in assembly language. Some examples of the use of C
might be:
Operating Systems
Language Compilers
Assemblers
5
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
6
If you want to set up your environment for C
programming language, you need the following two
software tools available on your computer,
(a) Text Editor and
(b) The C Compiler.
Text Editor
This will be used to type your program. Examples of a few
editors include Windows Notepad, OS Edit command,
Brief, Epsilon, EMACS, and vim or vi. The name and
version of text editors 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 on Linux or UNIX.
The files you create with your editor are called the source
files and they contain the program source codes. 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" into machine language so that your CPU can
7
actually execute the program as per the instructions
given.
The compiler compiles the source codes into final
executable programs. The most frequently used and free
available compiler is the GNU C/C++ compiler,
otherwise you can have compilers either from HP or
Solaris if you have the respective operating systems.
The following section explains how to install GNU C/C++
compiler on various OS. We keep mentioning C/C++
together because GNU gcc compiler works for
both C and C++ programming languages.
Identifiers
A C identifier is a name used to identify a variable,
function, or any other userdefined item. An identifier
starts with a letter A to Z, a to z, or an underscore ‘_’
followed by zero or more letters, underscores, and digits
(0 to 9). C does not allow punctuation characters such as
@, $, and % within identifiers. C is a case-sensitive
programming language. Thus, Manpower and manpower
are two different identifiers in C. Here are some examples
of acceptable identifiers:
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
Keywords
The following list shows the reserved words in C. These
reserved words may not be used as constants or
variables or any other identifier names.
8
auto else long switch
break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _Packed
double
Whitespace in C
A line containing only whitespace, possibly with a
comment, is known as a blankline, and a C compiler
totally ignores it. Whitespace is the term used in C to
describe blanks, tabs, newline characters and comments.
Whitespace separates one part of a statement from
another and enables the compiler to identify where one
element in a statement, such as int, ends and the next
element begins. Therefore, in the following statement:
int age;
there must be at least one whitespace character (usually
a space) between int and age for the compiler to be able
to distinguish them. On the other hand, in
the following statement:
fruit = apples + oranges; // get the total fruit
no whitespace characters are necessary between fruit
and =, or between = and apples, although you are free to
include some if you wish to increase readability.
9
Datatypes
Data types in C refer to an extensive system used for
declaring variables or functions of different types. The
type of a variable determines how much space it occupies
in storage and how the bit pattern stored is interpreted.
The types in C can be classified as follows:
1 Basic Types: They are arithmetic types and are further
classified into: (a) integer types and (b) floating-point
types.
2 Enumerated types: They are again arithmetic types and
they are used to define variables that can only assign
certain discrete integer values throughout the program.
3 The type void: The type specifier void indicates that no
value is available.
4 Derived types: They include (a) Pointer types, (b)
Array types, (c) Structure types, (d) Union types, and
(e) Function types.
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
1
0
either a letter or an underscore. Upper and lowercase
letters are distinct because C is case-sensitive. Based on
the basic types explained in the previous chapter, there
will be the following basic variable types:
Type Description
char Typically a single octet
(one byte). This is an integer type.
int The most natural size of
integer for the machine.
. float A single-precision
floating point value.
Double A double-precision
floating point value.
Void Represents the
absence of type.
type variable_list;
Some valid declarations are shown here:
int i, j, k;
char c, ch;
float f, salary;
1
1
double d;
Variable Declaration in C
A variable declaration provides assurance to the
compiler that there exists a variable with the given
type and name so that the compiler can proceed for
further compilation without requiring the complete
detail about the variable. A variable declaration has its
meaning at the time of compilation only, the
compiler needs actual variable declaration at the time
of linking the program.
A variable declaration is useful when you are using
multiple files and you define your variable in one of
the files which will be available at the time of linking
the program. You will use the keyword extern to
declare a variable at any place.
Though you can declare a variable multiple times in
your C program, it can be defined only once in a file, a
function, or a block of code.
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 <stdio.h>
// Variable declaration:
extern int a, b;
1
2
extern int c;
extern float f;
int main ()
{
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
Storage classes
A storage class defines the scope (visibility) and life-
time of variables and/or functions within a C Program.
1
3
They precede the type that they modify. We have four
different storage classes in a C program:
auto
register
static
extern
The auto Storage Class
The auto storage class is the default storage class for
all local variables.
{
int mount;
auto int month;
}
The example above defines two variables within the
same storage class. ‘auto’ can only be used within
functions, i.e., local variables.
The register Storage Class
The register storage class is used to define local
variables that should be stored in a register instead of
RAM. 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).
{
register int miles;
}
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
1
4
the variable will be stored in a register. It means that
it MIGHT be stored in a register depending on
hardware and implementation restrictions.
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main()
{
1
5
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);
}
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
1
6
storage location that has been previously defined.
When you have multiple files and you define a global
variable or function, which will also be used in other
files, then extern will be used in another file to provide
the reference of defined variable or function. Just for
understanding, extern is used to declare a global
variable or function in another file.
First File: main.c
#include <stdio.h>
int count;
extern void write_extern();
main()
{
count = 5;
write_extern();
}
OPERATORS
An operator is a symbol that tells the compiler to
perform specific mathematical or logical functions. C
1
7
language is rich in built-in operators and provides the
following types of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators
The following table shows all the arithmetic operators
supported by the C language. Assume variable A holds
10 and variable B holds 20, then:
Operator Description
Example
+ Adds two operands.
A + B = 30
- Subtracts second operand from the first.
A - B = -10
* Multiplies both operands.
A * B = 200
/ Divides numerator by de-numerator.
B/A=2
% Modulus Operator and remainder of after an
integer division.
B%A=0
++ Increment operator increases the integer
value
1
8
by one.
A++ = 11
- Decrement operator decreases the integer
value by one.
A-- = 9
Relational Operators
The following table shows all the relational operators
supported by C. Assume variable A holds 10 and
variable B holds 20, then:
Operator Description
Example
== Checks if the values of two operands are equal
or not. If yes, then the condition becomes true .
(A ==
B) is not true.
!= Checks if the values of two operands are equal
or not. If the values are not equal, then the
condition becomes true.
(A != B) is true.
> Checks if the value of left operand is greater
than the value of right operand. If yes, then
the condition becomes true.
(A > B) is not
true.
< Checks if the value of left operand is less than
the value of right operand. If yes, then the
condition becomes true.
1
9
(A < B) is true.
>= Checks if the value of left operand is greater
than or equal to the value of right operand. If
yes, then the condition becomes true.
(A >= B) is not
true.
<= Checks if the value of left operand is less than
or equal to the value of right operand. If yes,
then the condition becomes true.
(A <= B) is true
Logical Operators
Following table shows all the logical operators
supported by C language. Assume
variable A holds 1 and variable B holds 0, then:
Operator Description
Example
&& Called Logical AND operator. If both
the
operands are non-zero, then the conditi
becomes true.
(A && B) is
false.
|| Called Logical OR Operator. If any of the
two
operands is non-zero, then the condition
(A || B) is true.
! Called Logical NOT Operator. It is used to
reverse the logical state of its operand. If a
condition is true, then Logical NOT operator will
2
0
make it false.
(A && B) is
true.
Bitwise Operators
Bitwise operators work on bits and perform bit-by-bit
operation. The truth table for &, |, and ^ is as follows:
P q p&q p|q
p^q
0 0 0 0
0
0 1 0 1
1
1 1 1 1
0
1 0 0 1
1
Assignment Operators
The following tables lists the assignment operators
supported by the C language:
Operator Description
Example
= Simple assignment operator.
Assigns values from right side operands
to left
side operand.
C = A + B will assign
2
1
the value of A + B to
C
+= Add AND assignment operator. It adds the
right operand to the left operand and
assigns the result to the left operand.
C += A is equivalent
to C = C + A
-= Subtract AND assignment operator. It
subtracts the right operand from the left
operand and assigns the result to the left
operand.
C -= A is equivalent
to C = C - A
*= Multiply AND assignment operator. It
multiplies the right operand with the left
operand and assigns the result to the left
operand.
C *= A is equivalent
to C = C * A
/= Divide AND assignment operator. It
divides the left operand with the right
operand and assigns the result to the left
operand.
C /= A is equivalent
to C = C / A
%= Modulus AND assignment operator. It
takes modulus using two operands and
assigns the result to the left operand.
C %= A is equivalent
2
2
to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is
same as C
= C << 2
>>= Right shift AND assignment operator. C >>= 2 is
same as C
= C >> 2
&= Bitwise AND assignment operator. C &= 2 is same
as C
^= Bitwise exclusive OR and assignment
operator.
C ^= 2 is same as C
=C^2
|= Bitwise inclusive OR and assignment
operator.
C |= 2 is same as C =
C|2
2
3
Operator Description Example
sizeof() Returns the size of a variable.
sizeof(a), where a is integer, will return 4.
& Returns the address of a variable. &a; returns the
actual
address of the
variable.
* Pointer to a variable. *a;
? : Conditional Expression. If Condition is true ?
then value X :
otherwise value Y
FUNCTIONS
A function 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.
2
4
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 is such that 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, strcat() to concatenate two strings,
memcpy() to copy one memory location to another location, and many
more functions.
A function can also be referred as 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 function_name( parameter list )
{
body of the function
}
A function definition in C programming consists of a function header
and function body. Here are all the parts of a function:
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 parameter list refers to the type,
2
5
order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.
Function Declarations
A function declaration tells the compiler about a function
name and how to call the function. The actual body of the
function can be defined separately A function declaration
has the following parts:
return_type function_name( parameter list );
For the above defined function max(),the function
declaration is as follows:
int max(int num1, int num2);
Parameter names are not important in function
declaration, only their type is required, so the following is
also a valid declaration:
2
6
int max(int, int);
Calling a Function
While creating a C function, you give a definition of what
the function has to do.
To use a function, you will have to call that function to
perform the defined task.
When a program calls a function, the program control is
transferred to the called
function. A called function performs a defined task and
when its return
statement is executed or when its function-ending
closing brace is reached, it
returns the program control back to the main program.
To call a function, you simply need to pass the required
parameters along with
the function name, and if the function returns a value,
then you can store the 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;
/* calling a function to get max value */
ret = max(a, b);
2
7
printf( "Max value is : %d\n", ret );
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
We have kept max()along with main() and compiled
the source code. While running the final executable, it
would produce the following result:
Max value is : 200
Function Arguments
If a function is to use arguments, it must declare
variables that accept the values of the arguments.
These variables are called the formal parameters of
the function.
Formal parameters behave like other local variables
inside the function and are created upon entry into
the function and destroyed upon exit.
While calling a function, there are two ways in which
arguments can be passed to a function:
Call Type Description
2
8
Call by value This method copies the actual value of
an argument
into the formal parameter of the function. In this case,
changes made to the parameter inside the function
have no effect on the argument.
Call by reference
This method copies the address of an argument into
the formal parameter. Inside the function, the address
is used to access the actual argument used in the call.
This means that changes made to the parameter
affect
the argument.
2
9
Array
Arrays a kind of data structure that 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:
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize
must be an integer constant greater than zero and
type can be any valid C data type.
For example,
to declare a 10-element array called balance of type
double, use this statement:
double balance[10];
3
0
Here, balance is a variable array which is sufficient to
hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or
using a single statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be
larger than the number of elements that we declare
for the array between square brackets [ ].
If you omit the size of the array, an array just big
enough to hold the initialization is created. Therefore,
if you write:
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
we will create exactly the same array as you did in the
previous example.
Following is an example to assign a single element of
the array:
balance[4] = 50.0;
The above statement assigns the 5th element in the
array with a value of 50.0. All arrays have 0 as the
index of their first element which is also called the
base index and the last index of an array will be total
size of the array minus 1.
Accessing Array Elements
An element is accessed by indexing the array name.
This is done by placing the index of the element within
square brackets after the name of the array.
For example:
3
1
double salary = balance[9];
The above statement will take the 10th element from
the array and assign the value to salary variable. The
following example shows how to use all the three
above-mentioned concepts viz. declaration,
assignment, and accessing arrays:
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
3
2
Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by
specifying bracketed values for each row. Following is
an array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row,
are optional. The following initialization is equivalent
to the previous example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
3
3
You can verify it in the above figure. Let us check the
following program where
we have used a nested loop to handle a two-
dimensional array:
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
return 0;
}
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
3
4
a[4][0]: 4
a[4][1]: 8
Pointer to an Array
It is most likely that you would not understand this
section until you are through with the chapter
‘Pointers’.
Assuming you have some understanding of pointers in
C, let us start: An array name is a constant pointer to
the first element of the array. 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.
Thus, the following program fragment assigns p as the
address of the first element of balance:
double *p;
double balance[10];
p = balance;
It is legal to use array names as constant pointers,
and vice versa. Therefore,
3
5
*(balance + 4) is a legitimate way of accessing the
data at balance[4].
Once you store the address of the first element in ‘p’,
you can access the array elements using *p, *(p+1),
*(p+2), and so on. Given 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;
/* 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;
}
NULL Pointers
It is always a good practice to assign a NULL value to
a pointer variable in case you do not have an 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;
printf("The value of ptr is : %x\n", ptr );
3
8
return 0;
}
Result:
The value of ptr is 0
Strings
Strings are actually one-dimensional array of
characters terminated by a null character '\0'. Thus a
null-terminated string contains the characters that
comprise the string followed by a null.
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."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
3
9
If you follow the rule of array initialization, then you
can write the above statement as follows:
char greeting[] = "Hello";
return 0;
}
Result:
Greeting message: Hello
Structure
Arrays allow to define type of variables that can hold
several data items of the same kind. Similarly,
structure is another user-defined data type available
in C that allows to combine data items of different
kinds.
Structures are used to represent a record. Suppose
you want to keep track of your books in a library. You
might want to track the following attributes about
each book:
Title
4
0
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct
statement. The struct statement defines a new data
type, with more than one member. The format of the
struct statement is as follows:
struct [structure tag]
{
member definition;
member definition;
...
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. At the
end of the structure's definition, before the final
semicolon, you can specify one or more structure
variables but it is optional. Here is the way you would
declare
the Book structure:
struct Books
{
char title[50];
char author[50];
char subject[100];
4
1
int book_id;
} book;
Pointers to Structures
You can define pointers to structures in the same way
as you define pointer to any other variable:
struct Books *struct_pointer;
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 rewrite the above example using structure
pointer.
#include <stdio.h>#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books *book );
int main( )
4
2
{
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;
/* print Book1 info by passing address of Book1 */
printBook( &Book1 );
/* print Book2 info by passing address of Book2 */
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);
}
Result:
Book title : C Programming
Book author : Nuha Ali
4
3
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
union
A union is a special data type available in C that
allows to store different data types in the same
memory location. You can define a union with many
members, but only one member can contain a value
at any given time. Unions provide an efficient way of
using the same memory location for multiple purpose.
Defining a Union
To define a union, you must use the union statement
in the same way as you did while defining a structure.
The union statement defines a new data type with
more than one member for your program. The format
of the union statement is as follows:
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition
is a normal variable definition, such as int i; or float f;
4
4
or any other valid variable 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.
Here is the way you would define a
union type named Data having three members i, f,
and str:
union Data
{
int i;
float f;
char str[20];
} data;
Recursion
4
5
Recursion is the process of repeating items in a self-
similar way. In programming languages, if a program
allows you to call a function inside the same function,
then it is called a recursive call of the function.
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 into an
infinite loop.
Recursive functions are very useful to solve many
mathematical problems, such as calculating the
factorial of a number, generating Fibonacci series, etc.
Number Factorial
The following example calculates the factorial of a
given number using a recursive function:
#include <stdio.h>
int factorial(unsigned int i)
{
if(i <= 1)
{
return 1;
4
6
}
return i * factorial(i - 1);
}
int main()
{
int i = 15;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
Result:
Factorial of 15 is 2004310016
Fibonacci Series
The following example generates the Fibonacci series
for a given number using a recursive function:
#include <stdio.h>
int fibonaci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonaci(i-1) + fibonaci(i-2);
}
int main()
{
4
7
int i;
for (i = 0; i < 10; i++)
{
printf("%d\t%n", fibonaci(i));
}
return 0;
}
Result:
0 1 1 2 3 5 8 13 21 34
4
8