0% found this document useful (0 votes)
993 views75 pages

Bcom Ca II Sem Material

Bcom II sem C & C++

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
993 views75 pages

Bcom Ca II Sem Material

Bcom II sem C & C++

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

lOMoARcPSD|18721855

B.Com CA II Sem Material

B.Com (Telangana University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by J suresh kumar ([email protected])
lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

B.Com CA II SEMESTER
COMPUTER APPLICATIONS STUDY MATERIAL
SUBJECT : PROGRAMMING WITH C & C++
DEPARTMENT OF COMPUTER APPLICATIONS
GOVERNMENT ARTS AND SCIENCE COLLEGE,
KAMAREDDY

1
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

UNIT-I
Introduction to Language, Variables, Data Types and Operators
Introduction :
What is a language?

Language is the medium of communication to share ideas, opinion with each other. For
an example, if we want to communicate with someone, we need a language it may be English,
Hindi, Spanish or another language. But you need at least one language to communicate with
someone (human/person).
What is a programming language?

To communicate with a person, you need a language. Same if you need to communicate
with the computer, you need a programming language. Without any programming language you
cannot communicate with the computer.
Thus, programming language is the medium of communication between you (a person) and a
computer system. It is the set of some instructions written in a specific style (coding) to instruct
the computer to do some specific task.
Types of computer programming languages

There are basically three types of computer programming languages, they are
1. Low level programming languages
2. High level programming languages
3. Middle level programming languages
1) Low level programming languages

These are machine dependent programming languages such as Binary (Machine code)
and Assembly language. Since computer only understand the Binary language that means
instructions in the form of 0’s and 1’s (Signals - that can be either High or Low), so these
programming languages are the best way to give signals (Binary Instructions) to the computer
directly.
Machine Code (Binary Language) does not need any interpreter or compiler to convert
language in any form because computer understands these signals directly. But, Assembly

2
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

language needs to be converted in equivalent Binary code, so that computer can understand the
instructions written in Assembly. Assembler is used to convert an assembly code to its
equivalent Binary code.
The codes written in such kind of languages are difficult to write, read, edit and understand; the
programs are not portable to any other computer system.
Low Level programming language programs are faster than High Level programming
language programs as they have less keywords, symbols and no need (less need) to convert into
Machine Code.
2) High level programming languages

These are the machine independent programming languages, which are easy to write,
read, edit and understand. The languages like Java, .Net, Pascal, COBOL, C++, C, C# and other
(which are very popular now to develop user end applications). These languages come under the
high level programming language category. High level programming languages have some
special keywords, functions and class libraries by using them we can easily build a program for
the computer. Computer does not understand program written in such languages directly, as I
have written above that computer understands only Machine code. So, here programming
translators are required to convert a high level program to its equivalent Machine code.
Programming translators such as Compilers and Interpreters are the system software’s
which converts a program written in particular programming languages to its equivalent Machine
code.
Here are the features of High Level programming languages
 The programs are written in High Level programming languages and are independent that
means a program written on a system can be run on another system.
 Easy to understand - Since these programming languages have keywords, functions, class
libraries (which are similar to English words) we can easily understand the meaning of
particular term related to that programming language.
 Easy to code, read and edit - The programs written in High Level programming
languages are easy to code, read and edit. Even we can edit programs written by other
programmers easily by having little knowledge of that programming language.

3
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

 Since, High Level language programs are slower than Low level language programs; still
these programming languages are popular to develop User End Applications.
3) Middle Level programming language

Since, there is no such category of computer programming languages, but the


programming languages that have features of low level and high level programming languages
come under this category.
Hence, we can say that the programming languages which have features of Low Level
as well as High Level programming languages known as "Middle Level" programming
language.
C programming languages is the best example of Low Level Programming languages as it has
features of low level and high level programming languages both.
History of C language :
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of
AT&T (American Telephone & Telegraph), located in the U.S.A. Dennis Ritchie is known as the
founder of the c language. It was developed to overcome the problems of
previous languages such as B, BCPL, etc.
Basic Structure of c language
Any C program is consists of 6 main sections. Below you will find a brief explanation of each of them.

Basic Structure of C Program

1. Documentation Section
2. Link Section

4
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

3. Definition Section
4. Global Declaration Section
5. main() Function Section
6. Subprogram Section
1. Documentation Section

This section consists of comment lines which include the name of the program, the name
of the programmer, the author and other details like time and date of writing the program.
Documentation section helps anyone to get an overview of the program.
2. Link Section

The link section consists of the header files of the functions that are used in the program.
It provides instructions to the compiler to link functions from the system library such as using the
#include directive.
#include<stdio.h> //link section
#include<conio.h> //link section/
3. Definition Section

All the symbolic constants are written in the definition section. Macros are known as
symbolic constants.
#define PI 3.14 //definition section
4. Global Declaration Section
The global variables that can be used anywhere in the program are declared in the global
declaration section. This section also declares the user defined functions.
float area; //global declaration section
5. main() Function Section

It is necessary to have one main() function section in every C program. This section
contains two parts, declaration and executable part. The declaration part declares all the variables
that are used in executable part. These two parts must be written in between the opening and
closing braces. Each statement in the declaration and executable part must end with a semicolon
(;). The execution of the program starts at opening braces and ends at closing braces.

5
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

6. Subprogram Section

The subprogram section contains all the user defined functions that are used to perform a
specific task. These user defined functions are called in the main() function.
If the program is a multifunction program then the sub program section contains all the user-
defined functions that are called in the main () function. User-defined functions are generally
placed immediately after the main () function, although they may appear in any order.

message()
{
printf("This Sub Function \n");
printf("we can take more Sub Function \n");
}
Rules to Write a C program
 All lines of C statements must end with a semicolon.
 C is case-sensitive. That is, uppercase and lowercase characters are different. Usually, the
statements are typed in lowercase.
 A C Program statement can be split into many lines or can be written in one line.
 Braces must always match upon pairs, i.e., every opening brace {must have a matching
closing brace}.
 All C program starts with main( ) function.
Flow chart:
A diagram of the sequence of movements or actions of people or things involved in a
complex system or activity.
OR
A graphical representation of a computer program in relation to its sequence of functions
(as distinct from the data it processes).

6
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

Algorithm:
A process or set of rules to be followed in calculations or other problem-solving
operations, especially by a computer.

Commonly used library functions:


C Standard library functions or simply C Library functions are inbuilt functions in C
programming.
The prototype and data definitions of these functions are present in their respective header files.
To use these functions we need to include the header file in our program
C Header
Description
Files
<ctype.h> Charact
ertypefunctions
<mat h.h> Mathemati
csfunct i
ons
<stdi
o.h> St
andardInput/Outputfunct
i
ons
<stdl
ib.h> St
andardUt i
li
t
yf uncti
ons
<st
r i
ng.h> St
ri
nghandl i
ngf uncti
ons
<ti
me. h> Dateti
mefunctions
Executing the C program
Step 1: Creating a Source Code
Source code is a file with C programming instructions in a high-level language. To create source
code, we use any text editor to write the program instructions.
 Click on File -> New in C Editor window

7
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

 Type the program


 Save it as FileName.c (Use shortcut key F2 to save)
Step 2: Compile Source Code (Alt + F9)
 The compilation is the process of converting high-level language instructions into low-
level language instructions. We use the shortcut key Alt + F9 to compile a C program
in Turbo C.
The compilation is the process of converting high-level language instructions into low-level
language instructions.
Step 3: Executing / Running Executable File (Ctrl + F9)
After completing compilation successfully, an executable file is created with a .exe extension.
The processor can understand this .exe file content so that it can perform the task specified in the
source file.
We use a shortcut key Ctrl + F9 to run a C program.
Pre-processors in “C” :
The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it
instructs the compiler to do required pre-processing before the actual compilation.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in the first column. The
following section lists down all the important preprocessor directives –
Sr.No Directive & Description
.
#define
1
Substitutes a preprocessor macro.
#include
2
Inserts a particular header from another file.
#undef
3
Undefines a preprocessor macro.
#ifdef
4
Returns true if this macro is defined.
#ifndef
5
Returns true if this macro is not defined.
6 #if
8
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

Tests if a compile time condition is true.


#else
7
The alternative for #if.
#elif
8
#else and #if in one statement.
#endif
9
Ends preprocessor conditional.
#error
10
Prints error message on stderr.

C Tokens :
The compiler breaks a program into the smallest possible units and proceeds to the
various stages of the compilation, which is called token.
C Supports Six Types of Tokens:
1. Identifiers
2. Keywords
3. Constants
4. Strings
5. Operators
6. Special Symbols
1. Identifiers :
Identifiers are names given to different names given to entities such as constants, variables,
structures, functions etc.
Example:
int amount;
double totalbalance;
In the above example, amount and totalbalance are identifiers and int, and double are keywords.
Rules for Naming Identifiers :
 An identifier can only have alphanumeric characters (a-z , A-Z , 0-9) (i.e. letters & digits)
and underscore( _ ) symbol.
 Identifier names must be unique
 The first character must be an alphabet or underscore.

9
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

 You cannot use a keyword as identifiers.


 Only first thirty-one (31) characters are significant.
 Must not contain white spaces.
 Identifiers are case-sensitive.
2. Keywords
The C Keywords must be in your information because you cannot use them as a variable
name. You can't use a keyword as an identifier in your C programs, its reserved words in C
library and used to perform an internal operation. The meaning and working of these keywords
are already known to the compiler.
A list of 32 reserved keywords in c language is given below:

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do If static while
3. Constants
Constants are like a variable, except that their value never changes during execution once
defined. Constants in C are the fixed values that are used in a program, and its value remains the
same during the entire execution of the program.
 Constants are also called literals.
 Constants can be any of the data types.
 It is considered best practice to define constants using only upper-case names.

Syntax :
const type constant_name;
10
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

const keyword defines a constant in C.


Constant types in C :
Constants are categorized into two basic types, and each of these types has its subtypes/
categories. These are:
Primary Constants
1. Numeric Constants
o Integer Constants
o Real Constants
2. Character Constants
o Single Character Constants
o String Constants
o Backslash Character Constants
Integer Constant :
It's referring to a sequence of digits. Integers are of three types viz:
1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Example:
15, -265, 0, 99818, +25, 045, 0X6
Real constant

The numbers containing fractional parts like 99.25 are called real or floating points constant.
Single Character Constants

It simply contains a single character enclosed within ' and ' (a pair of single quote). It is to
be noted that the character '8' is not the same as 8. Character constants have a specific set of
integer values known as ASCII values (American Standard Code for Information Interchange).
Example:
'X', '5', ';'

11
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

String Constants

These are a sequence of characters enclosed in double quotes, and they may include
letters, digits, special characters, and blank spaces. It is again to be noted that "G" and 'G' are
different - because "G" represents a string as it is enclosed within a pair of double quotes
whereas 'G' represents a single character.
Example:
"Hello!", "2015", "2+1"
Backslash character constant

C supports some character constants having a backslash in front of it. The lists of
backslash characters have a specific meaning which is known to the compiler. They are also
termed as "Escape Sequence".
For Example:
\t is used to give a tab
\n is used to give a new line
Secondary Constant
 Array
 Pointer
 Structure
 Union
 Enum
4. Strings
In C programming, the one-dimensional array of characters is called strings, which is
terminated by a null character '\0'.
There are two ways to declare a string in C programming:
Example:
Through an array of characters.
char name[6];

Through pointers.

char *name;

12
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

Strings Initialization in C

Example:

char name[6] = {'C', 'l', 'o', 'u', 'd', ''};

char name[6] = {'C', 'l', 'o', 'u', 'd', '\0'};

or
char name[] = "Cloud";

5. Operators
C operators are symbols that are used to perform mathematical or logical manipulations.
The C programming language is rich with built-in operators. Operators take part in a program for
manipulating data and variables and form a part of the mathematical or logical expressions.
Types of Operators:
C programming language offers various types of operators having different functioning
capabilities.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operator
7. Special Operators
1. Arithmetic Operators are used to performing mathematical calculations like addition
(+), subtraction (-), multiplication (*), division (/) and modulus (%).

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

13
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

% Modulus

2. Relational Operators
Relational operators are used to comparing two quantities or values.

Operator Description

== Is equal to

!= Is not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

3. Logical Operators
C provides three logical operators when we test more than one condition to make
decisions. These are: && (meaning logical AND), || (meaning logical OR) and ! (meaning
logical NOT).

Operator Description

&& And operator. It performs logical conjunction of two expressions. (if both
expressions evaluate to True, result is True. If either expression evaluates to False,
the result is False)

|| Or operator. It performs a logical disjunction on two expressions. (if either or both


expressions evaluate to True, the result is True)

! Not operator. It performs logical negation on an expression.


4. Assignment Operators
Assignment operators applied to assign the result of an expression to a variable. C has a
collection of shorthand assignment operators.

14
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

Operato Description
r

= Assign

+= Increments then assign

-= Decrements then assign

*= Multiplies then assign

/= Divides then assign

%= Modulus then assign

<<= Left shift and assign

>>= Right shift and assign


5. Increment and Decrement Operators
Increment and Decrement Operators are useful operators generally used to minimize the
calculation, i.e. ++x and x++ means x=x+1 or --x and x--means x=x-1.

Operator Description

++ Increment

−− Decrement

6. Conditional Operator
C offers a ternary operator which is the conditional operator (?: in combination) to
construct conditional expressions.

Operator Description

?: Conditional Expression
7. Special Operators
C supports some special operators
15
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

Operato Description
r

sizeof() Returns the size of a memory location.

& Returns the address of a memory location.

* Pointer to a variable.
Variables :
A variable is a named memory location which is used to store the data value. 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. There will be the following basic variable types −

Sr.No. Type & Description

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

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

3 float
A single-precision floating point value.

4 double
A double-precision floating point value.

5 void
Represents the absence of type.

16
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

Variable Definition in C

A variable definition tells the compiler where and how much storage to create 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, int, float, double
and variable_list may consist of one or more identifier names separated by commas. Some
valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the
compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Rules for defining variables:
 All variable names must begin with a letter of the alphabet or an. underscore( _ ). ...
 After the first initial letter, variable names can also contain letters and numbers. ...
 Uppercase characters are distinct from lowercase characters. ...
 You cannot use a C++ keyword (reserved word) as a variable name.
Scope and Life of a Variable :
A scope in any programming is a region of the program where a defined variable can
have its existence and beyond that variable it cannot be accessed. There are three places where
variables can be declared in C programming language −
 Inside a function or a block which is called local variables.
 Outside of all functions which is called global variables.

17
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

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. The following example shows how local variables are
used. 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;

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

return 0;}

Global Variables

Global variables are defined outside a function, usually on top of the program. Global
variables hold their values throughout the lifetime of your program and they can be accessed
inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available
for use throughout your entire program after its declaration. The following program show how
global variables are used in a program.
#include <stdio.h>
/* global variable declaration */
int g;
int main () {

18
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

/* local variable declaration */


int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
A program can have same name for local and global variables but the value of local variable
inside a function will take preference. Here is an example −
#include <stdio.h>
/* global variable declaration */
int g = 20;
int main () {
/* local variable declaration */
int g = 10;
printf ("value of g = %d\n", g);
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of g = 10

Data Types :
A data-type in C programming is a set of values and is determined to act on those values.
C provides various types of data-types which allow the programmer to select the appropriate type
for the variable to set its value.
The data-type in a programming language is the collection of data with values having fixed
meaning as well as characteristics. Some of them are an integer, floating point, character, etc.
Usually, programming languages specify the range values for given data-type.

19
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

C Data Types are used to:


 Identify the type of a variable when it declared.
 Identify the type of the return value of a function.
 Identify the type of a parameter expected by a function.
ANSI C provides three types of data types:
1. Primary(Built-in) Data Types:
void, int, char, double and float.
2. Derived Data Types:
Array, References, and Pointers.
3. User Defined Data Types:
Structure, Union, and Enumeration
1.Primary(Built-in) Data Types:
Every C compiler supports five primary data types:
void As the name suggests, it holds no value and is generally used for specifying
the type of function or what it returns. If the function has a void type, it
means that the function will not return any value.
int Used to denote an integer type.
char Used to denote a character type.
float, double Used to denote a floating point type.
int *, float *, Used to denote a pointer type.
char *

Declaring Primitive Datatypes :


After taking suitable variable names, they need to be assigned with a data type. This is how the
data types are used along with variables:
Example:

int age;
char letter;
float height, width;

20
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

2.Derived Data Types

C supports three derived data types:


Data Types Description
Arrays Arrays are sequences of data items having homogeneous values. They have
adjacent memory locations to store values.
References Function pointers allow referencing functions with a particular signature.
Pointers These are powerful C features which are used to access the memory and deal
with their addresses.
3.User Defined Data Types :
C allows the feature called type definition which allows programmers to define their
identifier that would represent an existing data type. There are three such types:
Data Types Description
Structure It is a package of variables of different types under a single name. This is done
to handle data efficiently. "struct" keyword is used to define a structure.
Union These allow storing various data types in the same memory location.
Programmers can define a union with different members, but only a single
member can contain a value at a given time. It is used for
Enum Enumeration is a special data type that consists of integral constants, and each
of them is assigned with a specific name. "enum" keyword is used to define the
enumerated data type.

Type Conversion:
A type cast is basically a conversion from one type to another. There are two types of
type conversion:
1. Implicit Type Conversion
2. Explicit Type Conversion
1.Implicit Type Conversion
This is also known as ‘automatic type conversion’.
 Done by the compiler on its own, without any external trigger from the user.
 Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid lose of data.
21
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

 All the data types of the variables are upgraded to the data type of the variable with
largest data type.
char -> int -> float -> double
2.Explicit Type Conversion
This process is also called type casting and it is user defined. Here the user can type cast
the result to make it of a particular data type.
The syntax in C:
(type) expression

Type indicated the data type to which the final result is converted.
Formatted Input and Output Operations
Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file. C
programming language provides many built-in functions to read any given input and to display
data on screen when there is a need to output the result.
All these built-in functions are present in C header files, we will also specify the name of header
files in which a particular function is defined while discussing about it.
scanf() and printf() functions

The standard input-output header file, named stdio.h contains the definition of the
functions printf() and scanf(), which are used to display output on screen and to take input from
user respectively.
#include<stdio.h>

void main()

{ // defining a variable

int i;

/*displaying message on the screen asking the user to input a value*/

printf("Please enter a value...");

/*reading the value entered by the user*/

scanf("%d", &i);

22
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

/* displaying the number as output*/

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

When you will compile the above code, it will ask you to enter a value. When you will enter the
value, it will display the value you have entered on screen.
You must be wondering what is the purpose of %d inside the scanf() or printf() functions. It is
known as format string and this informs the scanf() function, what type of input to expect and
in printf() it is used to give a heads up to the compiler, what type of output to expect.

Format String Meaning

%d Scan or print an integer as signed decimal number

%f Scan or print a floating point number

%c To scan or print a character

%s To scan or print a character string. The scanning ends at whitespace.


getchar() & putchar() functions

The getchar() function reads a character from the terminal and returns it as an integer.
This function reads only single character at a time. You can use this method in a loop in case you
want to read more than one character. The putchar() function displays the character passed to it
on the screen and returns the same character. This function too displays only a single character at
a time. In case you want to display more than one characters, use putchar() method in a loop.
#include <stdio.h>

void main( )

{ int c;

printf("Enter a character");

/*Take a character as input and store it in variable c */

c = getchar();

/*display the character stored in variable c */

putchar(c);}

23
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

When you will compile the above code, it will ask you to enter a value. When you will
enter the value, it will display the value you have entered.
gets() & puts() functions

The gets() function reads a line from stdin(standard input) into the buffer pointed to
by str pointer, until either a terminating newline or EOF (end of file) occurs. The puts() function
writes the string str and a trailing newline to stdout.
str → This is the pointer to an array of chars where the C string is stored. (Ignore if you are not
able to understand this now.)
#include<stdio.h>

void main()

{ /* character array of length 100 */

char str[100];

printf("Enter a string");

gets( str );

puts( str );

getch();}

When you will compile the above code, it will ask you to enter a string. When you will enter the
string, it will display the value you have entered.

UNIT-II : WORKING WITH CONTROL STATEMENTS, LOOPS


Conditional Statements :
What is a Conditional Statement?

In a 'C' programs are executed sequentially. This happens when there is no condition
around the statements. If you put some condition for a block of statements the flow of execution
might change based on the result evaluated by the condition. This process is referred to as
decision making in 'C.' The decision-making statements are also called as control statements.

24
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

In 'C' programming conditional statements are possible with the help of the following two
constructs:
1. If statement
2. If-else statement
It is also called as branching as a program decides which statement to execute based on the result
of the evaluated condition.
If statement

It is one of the powerful conditional statement. If statement is responsible for modifying


the flow of execution of a program. If statement is always used with a condition. The condition is
evaluated first before executing any statement inside the body of If. The syntax for if statement is
as follows:
if (condition)
instruction;
The condition evaluates to either true or false. True is always a non-zero value, and false is a
value that contains zero. Instructions can be a single instruction or a code block enclosed by
curly braces { }.
The If-Else statement

The if-else is statement is an


extended version of If. The general form of if-else is as follows:
if (test-expression)
{ True block of statements}
else
{ False block of statements}
25
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

Statements;
In this type of a construct, if the value of test-expression is true, then the true block of statements
will be executed. If the value of test-expression if false, then the false block of statements will be
executed. In any case, after the execution, the control will be automatically transferred to the
statements appearing outside the block of If.
Nested If-else Statements

When a series of decision is required, nested if-else is used. Nesting means using one if-
else construct within another one.
Nested Else-if statements

Nested else-if is used when multipath decisions are required.


The general syntax of how else-if ladders are constructed in 'C' programming is as follows:
if (test - expression 1) {
statement1;
} else if (test - expression 2) {
Statement2;
} else if (test - expression 3) {
Statement3;
} else if (test - expression n) {
Statement n;
} else {
default;
}
Statement x;
Break Statement :
The break statement ends the loop immediately when it is encountered. Its syntax is:
break;
The break statement is almost always used with if...else statement inside the loop.
How break statement works?

26
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

C continue

The continue statement skips the current iteration of the loop and continues with the next
iteration. Its syntax is:
continue;

The continue statement is almost always used with the if...else statement.

C goto Statement
The goto statement allows us to transfer control of the program to the specified label.
Syntax of goto Statement

goto label;

... .. ...

27
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

... .. ...

label:

statement;

The label is an identifier. When the goto statement is encountered, the control of the program
jumps to label: and starts executing the code.

C switch Statement
The switch statement allows us to execute one code block among many alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax of
the switch statement is much easier to read and write.
Syntax of switch...case

switch (expression)
{ case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
default:
// default statements

28
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

}
Looping statements :
In programming, a loop is used to repeat a block of code until the specified condition is met.
C programming has three types of loops:
1. for loop
2. while loop
3. do...while loop
1.for Loop

The syntax of the for loop is:


for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}

How for loop works?

 The initialization statement is executed only once.


 Then, the test expression is evaluated. If the test expression is evaluated to false,
the for loop is terminated.
 However, if the test expression is evaluated to true, statements inside the body of for loop
are executed, and the update expression is updated.
 Again the test expression is evaluated.

29
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

This process goes on until the test expression is false. When the test expression is false, the loop
terminates.
C while and do...while Loop
while loop

The syntax of the while loop is:


while (testExpression)

{ // statements inside the body of the loop }

How while loop works?

 The while loop evaluates the test expression inside the parenthesis ().
 If the test expression is true, statements inside the body of while loop are executed. Then,
the test expression is evaluated again.
 The process goes on until the test expression is evaluated to false.
 If the test expression is false, the loop terminates (ends).

do...while loop

The do..while loop is similar to the while loop with one important difference. The body
of do...while loop is executed at least once. Only then, the test expression is evaluated.
The syntax of the do...while loop is:
do
{ // statements inside the body of the loop }
while (testExpression);

30
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

How do...while loop works?

 The body of do...while loop is executed once. Only then, the test expression is evaluated.
 If the test expression is true, the body of the loop is executed again and the test
expression is evaluated.
 This process goes on until the test expression becomes false.
 If the test expression is false, the loop ends.

Flowchart of do...while Loop

Nested Loops in C
Nested loop means a loop statement inside another loop statement. That is why nested loops are
also called as “loop inside loop“.
Syntax for Nested For loop:
for ( initialization; condition; increment ) {
for ( initialization; condition; increment ) {
// statement of inside loop
}
// statement of outer loop
}
Syntax for Nested While loop:
while(condition) {
31
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

while(condition) {
// statement of inside loop
}
// statement of outer loop
}
Syntax for Nested Do-While loop:
do{
do{
// statement of inside loop
}while(condition);
// statement of outer loop
}while(condition);

32
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

UNIT-III FUNCTIONS, ARRAYS AND STRINGS


Introduction :
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.
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 a 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.

33
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

 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, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
 Function Body − The function body contains a collection of statements that define what
the function does.
Example

Given below is the source code for a function called max(). This function takes two parameters
num1 and num2 and returns the maximum value between the two −
/* 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;
}
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 −
34
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

int max(int, int);


Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the top of the
file calling the function.
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);
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)

35
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

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
Types of functions

There are two types of function in C programming:


1. Standard library functions
2. User-defined functions
1.Standard library functions

The standard library functions are built-in functions in C programming.


These functions are defined in header files. For example,
 The printf() is a standard library function to send formatted output to the screen (display
output on the screen). This function is defined in the stdio.h header file.
Hence, to use the printf()function, we need to include the stdio.h header file using #include
<stdio.h>.
 The sqrt() function calculates the square root of a number. The function is defined in
the math.h header file.
2. User-defined function

You can also create functions as per your need. Such functions created by the user are known as
user-defined functions.
How user-defined function works?

#include <stdio.h>
void functionName()
{ ... .. ...

36
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

... .. ...}
int main()
{ ... .. ...
... .. ...
functionName();
... .. ...
... .. ...}

The execution of a C program begins from the main() function.


When the compiler encounters functionName();, control of the program jumps to

void functionName()

And, the compiler starts executing the codes inside functionName().


The control of the program jumps back to the main() function once code inside the function
definition is executed.

Note, function names are identifiers and should be unique.


Advantages of user-defined function

1. The program will be easier to understand, maintain and debug.


37
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

2. Reusable codes that can be used in other programs


3. A large program can be divided into smaller modules. Hence, a large project can be
divided among many programmers.
C Math Functions

There are various methods in math.h header file. The commonly used functions of math.h header
file are given below.
No. Function Description
1) ceil(number) rounds up the given number. It returns the integer value which is greater
than or equal to given number.
2) floor(number) rounds down the given number. It returns the integer value which is less
than or equal to given number.
3) sqrt(number) returns the square root of given number.
4) pow(base, returns the power of given number.
exponent)
5) abs(number) returns the absolute value of given number.

String Functions :
The nine most commonly used functions in the string library are:
 strcat - concatenate two strings.
 strchr - string scanning operation.
 strcmp - compare two strings.
 strcpy - copy a string.
 strlen - get string length.
 strncat - concatenate one string with part of another.
 strncmp - compare parts of two strings.
Char Functions :
List of inbuilt int, char validation functions in C programming language:
Functions Description
isalnum() Checks whether character is alphanumeric
isspace() Checks whether character is space
islower() Checks whether character is lower case
isupper() Checks whether character is upper case

38
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

Time functions in C are used to interact with system time routine and formatted time outputs are
displayed. Example programs for the time functions are given below.

Function Description

setdate() This function used to modify the system date

getdate() This function is used to get the CPU time

clock() This function is used to get current system time

time() This function is used to get current system time as structure

This function is used to get the difference between two given


difftime() times

strftime() This function is used to modify the actual time format

localtime( This function shares the tm structure that contains date and time
) informations

This function shares the tm structure that contains date and time
gmtime() informations

This function is used to return string that contains date and time
ctime() informations
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 –
Sr.No Call Type & Description
.
Call by value
This method copies the actual value of an argument into the formal parameter of the
1
function. In this case, changes made to the parameter inside the function have no
effect on the argument.
2 Call by reference
39
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

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.

By default, C uses call by value to pass arguments. In general, it means the code within a
function cannot alter the arguments used to call the function.
Recursive Functions :
Recursion is a programming technique that allows the programmer to express operations
in terms of themselves. In C, this takes the form of a function that calls itself. A useful way to
think of recursive functions is to imagine them as a process being performed where one of the
instructions is to "repeat the process".
Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>
int sum(int n);
int main() {
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
return 0;}
int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;}

Output

Enter a positive integer:3, sum = 6

40
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

C - Arrays
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];
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 −
41
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};


You 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. Shown below is the pictorial representation of
the array we discussed above −

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 −
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 */ }

/* output each array element's value */


for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );}
return 0;}
When the above code is compiled and executed, it produces the following result −
42
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

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
Multidimensional array :
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 integer array −
int threedim[5][10][4];
Two-dimensional Arrays :

The simplest form of 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 ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A
two-dimensional array can be considered as a table which will have x number of rows and y
number of columns. A two-dimensional array a, which contains three rows and four columns
can be shown as follows −

43
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where
'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in
'a'.
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};
Accessing Two-Dimensional Array Elements :

An element in a two-dimensional array is accessed by using the subscripts, i.e., row


index and column index of the array. For example −
int val = a[2][3];
The above statement will take the 4th element from the 3rd row of the array. 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++ ) {

44
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

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
a[4][0]: 4
a[4][1]: 8
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'};
If you follow the rule of array initialization then you can write the above statement as follows −
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C/C++ −

45
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

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 the above mentioned string –

#include <stdio.h>
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
C supports a wide range of functions that manipulate null-terminated strings −

Sr.No. Function & Purpose

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

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

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

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

46
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

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

6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
The following example uses some of the above-mentioned functions −
#include <stdio.h>
#include <string.h>
int main () {
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;}
When the above code is compiled and executed, it produces the following result −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10

47
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

UNIT-IV POINTERS, STRUCTURES AND UNIONS


Introduction :
Pointers 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 prints the address of the variables defined −
#include <stdio.h>
int main () {
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2 );
return 0;}
When the above code is compiled and executed, it produces the following result −
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6

48
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

What are Pointers?

A pointer is a variable whose value is the address of another variable, i.e., direct address
of the memory location. Like any variable or constant, you must declare a pointer before using
it to store any variable address. The general form of a pointer variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of
the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for
multiplication. However, in this statement the asterisk is being used to designate a variable as a
pointer. Take a look at some of the valid pointer declarations −
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or otherwise,
is the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.
How to Use Pointers?

There are a few important operations, which we will do with the help of pointers very
frequently. (a) We define a pointer variable, (b) assign the address of a variable to a pointer
and (c) finally access the value at the address available in the pointer variable. This is done by
using unary operator * that returns the value of the variable located at the address specified by
its operand. The following example makes use of these operations −
#include <stdio.h>
int main () {
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var );
/* address stored in pointer variable */
49
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

printf("Address stored in ip variable: %x\n", ip );


/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;}
When the above code is compiled and executed, it produces the following result −
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic
operations on a pointer just as you can on 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 −
ptr++
After the above operation, the ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer location which is 4 bytes next to the current
location. This operation will move the pointer to the next memory location without impacting
the actual value at the memory location. If ptr points to a character whose address is 1000, then
the above operation will point to the location 1001 because the next character will be available
at 1001.
Incrementing a Pointer

We prefer using a pointer in our program instead of an array because the variable pointer can be
incremented, unlike the array name which cannot be incremented because it is a constant
pointer. The following program increments the variable pointer to access each succeeding
element of the array −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};

50
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

int i, *ptr;
/* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++) {
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* move to the next location */
ptr++; }
return 0;}
When the above code is compiled and executed, it produces the following result −
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200
Decrementing a Pointer

The same considerations apply to decrementing a pointer, which decreases its value by the
number of bytes of its data type as shown below −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--) {
printf("Address of var[%d] = %x\n", i-1, ptr );
printf("Value of var[%d] = %d\n", i-1, *ptr );
/* move to the previous location */

51
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

ptr--;}
return 0;}
When the above code is compiled and executed, it produces the following result −
Address of var[2] = bfedbcd8
Value of var[2] = 200
Address of var[1] = bfedbcd4
Value of var[1] = 100
Address of var[0] = bfedbcd0
Value of var[0] = 10
Structures :
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
 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,
52
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

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];
int book_id;
} book;
Accessing Structure Members

To access any member of a structure, we use the member access operator (.). The
member access operator is coded as a period between the structure variable name and the
structure member that we wish to access. You would use the keyword struct to define variables
of structure type. The following example shows how to use a structure in a program −
#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 */

53
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

strcpy( Book2.title, "Telecom Billing");


strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Structures as Function Arguments

You can pass a structure as a function argument in the same way as you pass any other
variable or pointer.
#include <stdio.h>
#include <string.h>

54
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;};
/* function declaration */
void printBook( struct Books book );
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.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 */
printBook( Book1 );
/* Print Book2 info */
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 −
55
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

Book title : C Programming


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

You can define pointers to structures in 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 re-write 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( ) {
56
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

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);}
When the above code is compiled and executed, it produces the following result −
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700
57
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

Array of Structures in C

An array of structres in C can be defined as the collection of multiple structures variables


where each variable contains information about different entities. The array of structures in C are
used to store information about multiple entities of different data types. The array of structures is
also known as the collection of structures.
Let's see an example of an array of structures that stores information of 5 students and
prints it.
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name); }
return 0; }
Output:
Enter Records of 5 students
Enter Rollno:1

58
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Student Information List:
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
Enum in C
Enumeration is a user defined datatype in C language. It is used to assign names to the
integral constants which makes a program easy to read and maintain. The keyword “enum” is
used to declare an enumeration.
Here is the syntax of enum in C language,

enum enum_name{const1, const2, ....... };

The enum keyword is also used to define the variables of enum type. There are two ways to
define the variables of enum type as follows.

enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};


enum week day;

Here is an example of enum in C language,


Example

#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};

59
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};


int main() {
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thur,
Fri, Sat, Sun);
printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn,
Thurs, Frid, Satu, Sund);
return 0;
}

Output

The value of enum week: 10 11 12 13 10 16 17


The default value of enum day: 0 1 2 3 18 11 12

In the above program, two enums are declared as week and day outside the main()
function. In the main() function, the values of enum elements are printed.

enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};


enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main() {
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thur,
Fri, Sat, Sun);
printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn,
Thurs, Frid, Satu, Sund);
}

Union :
A union is a special data type available in C that allows storing 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.

60
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

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; 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;
Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple
types of data. You can use any built-in or user defined data types inside a union based on your
requirement.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by a character string. The following example
displays the total memory size occupied by the above union −
#include <stdio.h>
#include <string.h>
61
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by data : 20
Accessing Union Members

To access any member of a union, we use the member access operator (.). The member
access operator is coded as a period between the union variable name and the union member
that we wish to access. You would use the keyword union to define variables of union type.
The following example shows how to use unions in a program −
#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");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);

62
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

printf( "data.str : %s\n", data.str);


return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got corrupted because the
final value assigned to the variable has occupied the memory location and this is the reason that
the value of str member is getting printed very well.
Now let's look into the same example once again where we will use one variable at a time
which is the main purpose of having unions −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result −

63
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

data.i : 10
data.f : 220.500000
data.str : C Programming
Difference Between Structure and Union :

UNIT-V OBJECT ORIENTED CONCEPTS USING C++


OBJECT ORIENTED PROGRAMMING:
Introduction:
The Object Oriented programming paradigm plays an important role in human computer
interface. It has different components that takes real world objects and performs actions on
them, making live interactions between man and the machine. Following are the components of
OOPP −
 This paradigm describes a real-life system where interactions are among real objects.
 It models applications as a group of related objects that interact with each other.
64
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

 The programming entity is modeled as a class that signifies the collection of related real
world objects.
 Programming starts with the concept of real world objects and classes.
 Application is divided into numerous packages.
 A package is a collection of classes.
 A class is an encapsulated group of similar real world objects.
Structure of C++ Program :
Structure of a C+ + Program. Programs are a sequence of instructions or statements. These
statements form the structure of a C++ program. C++ program structure is divided into
various sections, namely, headers, class definition, member functions definitions and main
function.

Headers: Generally, a program includes various


programming elements like built-in functions, classes, keywords, constants, operators, etc., that
are already defined in the standard C++ library. In order to use such pre-defined elements in a
program, an appropriate header must be included in the program. The standard headers contain
the information like prototype, definition and return type of library functions, data type of
constants, etc. As a result, programmers do not need to explicitly declare (or define) the
predefined programming elements.
Main Function: The main () is a startup function that starts the execution of a c++ program. All
C++ statements that need to be executed are written within main ( ). The compiler executes all
the instructions written within the opening and closing curly braces' {}' that enclose the body of

65
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

main ( ). Once all the instructions in main () are executed, the control passes out of main ( ),
terminating the entire program and returning a value to the operating system.
Simple Program of C++ :
#include <iostream.h>
#include<conio.h>
main()
{ cout << "Hello, World!";
getch();}
Output
Hello, World!
Every C++ program starts from the main() function.
The cout is the standard output stream which prints the "Hello, World!" string on the monitor.
#include <iostream>
#include<conio.h>
main()
{ int number;
cout << "Enter an integer: ";
cin >> number;
cout << "You entered " << number; }
Output
Enter an integer: 23
You entered 23

#include <iostream.h>
#include<conio.h>
main()
{ int firstNumber, secondNumber, sumOfTwoNumbers;
cout << "Enter two integers: ";
cin >> firstNumber >> secondNumber;
sumOfTwoNumbers = firstNumber + secondNumber;
66
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

cout << firstNumber << " + " << secondNumber << " = " << sumOfTwoNumbers; }
Output
Enter two integers: 4
5
4+5=9
In this program, user is asked to enter two integers. These two integers are stored in
variables firstNumber and secondNumber respectively.
Then, the variables firstNumberand secondNumber are added using + operator and
stored in sumOfTwoNumbers variable.
Finally, sumOfTwoNumbers is displayed on the screen.
Storage Class :
A storage class defines the scope (visibility) and life-time of variables and/or functions
within a C++ Program. There are following storage classes, which can be used 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 with 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.
{ register int miles;}

67
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

The static Storage Class :

The static storage class instructs the compiler to keep a local variable in existence during
the life-time of the program instead of creating and destroying it each time it comes into and
goes out of scope. Therefore, making local variables static allows them to maintain their values
between function calls.
include <iostream.h>
// Function declaration
void func(void);
static int count = 10; /* Global variable */
main() {
while(count--) {
func();
}
return 0;}
// Function definition
void func( void ) {
static int i = 5; // local static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is " << count << std::endl;}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1

68
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

i is 15 and count is 0
The extern Storage Class :

The extern storage class is used to give a reference of a global variable that is visible to ALL
the program files. When you use 'extern' the variable cannot be initialized as all it does is point
the variable name at a storage location that has been previously defined.
Difference between C and C++ :
Similarities between C and C++ are:
 Both the languages have a similar syntax.
 Code structure of both the languages is same.
 The compilation of both the languages is similar.
 They share the same basic syntax. Nearly all of C’s operators and keywords are also
present in C++ and do the same thing.
 C++ has a slightly extended grammar than C, but the basic grammar is the same.
 Basic memory model of both is very close to the hardware.
Differences between C and C++ are:
C++ can be said a superset of C. Major added features in C++ are Object-Oriented
Programming, Exception Handling and rich C++ Library.
C C++
C was developed by Dennis Ritchie between C++ was developed by Bjarne Stroustrup in
the year 1969 and 1973 at AT&T Bell Labs. 1979.
C does no support polymorphism,
encapsulation, and inheritance which means C++ supports polymorphism, encapsulation,
that C does not support object oriented and inheritance because it is an object oriented
programming. programming language.
C is a subset of C++. C++ is a superset of C.
C contains 32 keywords. C++ contains 52 keywords.
C++ is known as hybrid language because C++
For the development of code, C supports both procedural and object oriented
supports procedural programming. programming paradigms.
Data and functions are separated in C because Data and functions are encapsulated together in
it is a procedural programming language. form of an object in C++.
C does not support information hiding. Data is hidden by the Encapsulation to ensure

69
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

that data structures and operators are used as


intended.
Built-in & user-defined data types is supported
Built-in data types is supported in C. in C++.
C is a function driven language because C is a C++ is an object driven language because it is
procedural programming language. an object oriented programming.
Function and operator overloading is not Function and operator overloading is supported
supported in C. by C++.
Data members and Member functions in C++

"Data Member" and "Member Functions" are the new names/terms for the members
of a class, which are introduced in C++ programming language.
The variables which are declared in any class by using any fundamental data types (like
int, char, float etc) or derived data type (like class, structure, pointer etc.) are known as Data
Members. And the functions which are declared either in private section of public section are
known as Member functions.
There are two types of data members/member functions in C++:
1. Private members
2. Public members
1) Private members

The members which are declared in private section of the class (using private access
modifier) are known as private members. Private members can also be accessible within the
same class in which they are declared.
2) Public members

The members which are declared in public section of the class (using public access
modifier) are known as public members. Public members can access within the class and outside
of the class by using the object name of the class in which they are declared.
Consider the example:
class Test
{ private:
int a;
float b;
70
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

char *name;
void getA() { a=10; }
...;
public:
int count;
void getB() { b=20; }
...;};
Here, a, b, and name are the private data members and count is a public data member.
While, getA() is a private member function and getB() is public member functions.
C++ program that will demonstrate, how to declare, define and access data members an
member functions in a class?
#include <iostream.h>
#include <string.h>
#define MAX_CHAR 30
//class definition
class person
{ //private data members
private:
char name [MAX_CHAR];
int age;
//public member functions
public:
//function to get name and age
void get(char n[], int a)
{strcpy(name , n);
age = a;}
//function to print name and age
void put()
{
cout<< "Name: " << name <<endl;
cout<< "Age: " <<age <<endl;}};
71
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

//main function
int main()
{ //creating an object of person class
person PER;
//calling member functions
PER.get("Manju Tomar", 23);
PER.put();
return 0;}
Output
Name: Manju Tomar
Age: 23
As we can see in the program, that private members are directly accessible within the
member functions and member functions are accessible within in main() function (outside of the
class) by using period (dot) operator like object_name.member_name;
C++ OOPs Concepts
The major purpose of C++ programming is to introduce the concept of object orientation
to the C programming language. Object Oriented Programming is a paradigm that provides many
concepts such as inheritance, data binding, polymorphism etc.
The programming paradigm where everything is represented as an object is known as
truly object-oriented programming language. Smalltalk is considered as the first truly object-
oriented programming language.
OOPs (Object Oriented Programming System)

Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It
simplifies the software development and maintenance by providing some concepts:

72
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object

Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.
Class

Collection of objects is called class. It is a logical entity.


Inheritance

When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For
example: to convince the customer differently, to draw something e.g. shape or rectangle etc.
In C++, we use Function overloading and Function overriding to achieve polymorphism.

73
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])


lOMoARcPSD|18721855

B.Com CA. II SEMESTER PROGRAMMING WITH C & C++

Abstraction

Hiding internal details and showing functionality is known as abstraction. For


example: phone call, we don't know the internal processing.
In C++, we use abstract class and interface to achieve abstraction.
Encapsulation

Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
Advantage of OOPs over Procedure-oriented programming language

1. OOPs makes development and maintenance easier where as in Procedure-oriented


programming language it is not easy to manage if code grows as project size grows.
2. OOPs provide data hiding whereas in Procedure-oriented programming language a global
data can be accessed from anywhere.
3. OOPs provide ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented
Programming language.

74
GDC-Kamareddy Prepared By : D.Balakrishna

Downloaded by J suresh kumar ([email protected])

You might also like