Bcom Ca II Sem Material
Bcom Ca II Sem Material
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
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
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
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
1. Documentation Section
2. Link Section
4
GDC-Kamareddy Prepared By : D.Balakrishna
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
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
Algorithm:
A process or set of rules to be followed in calculations or other problem-solving
operations, especially by a computer.
7
GDC-Kamareddy Prepared By : D.Balakrishna
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
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
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
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
Strings Initialization in C
Example:
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
% Modulus
2. Relational Operators
Relational operators are used to comparing two quantities or values.
Operator Description
== Is equal to
!= Is not 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)
14
GDC-Kamareddy Prepared By : D.Balakrishna
Operato Description
r
= Assign
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
Operato Description
r
* 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 −
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
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
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 () {
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
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
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
int age;
char letter;
float height, width;
20
GDC-Kamareddy Prepared By : D.Balakrishna
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
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;
scanf("%d", &i);
22
GDC-Kamareddy Prepared By : D.Balakrishna
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.
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");
c = getchar();
putchar(c);}
23
GDC-Kamareddy Prepared By : D.Balakrishna
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()
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.
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
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
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
26
GDC-Kamareddy Prepared By : D.Balakrishna
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
... .. ...
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
}
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
29
GDC-Kamareddy Prepared By : D.Balakrishna
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 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
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.
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
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
33
GDC-Kamareddy Prepared By : D.Balakrishna
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
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
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
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
... .. ...}
int main()
{ ... .. ...
... .. ...
functionName();
... .. ...
... .. ...}
void functionName()
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
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
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
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
40
GDC-Kamareddy Prepared By : D.Balakrishna
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
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 */ }
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 :
43
GDC-Kamareddy Prepared By : D.Balakrishna
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 :
44
GDC-Kamareddy Prepared By : D.Balakrishna
45
GDC-Kamareddy Prepared By : D.Balakrishna
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 −
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
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
48
GDC-Kamareddy Prepared By : D.Balakrishna
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
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
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
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
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
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
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
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
Array of Structures in C
58
GDC-Kamareddy Prepared By : D.Balakrishna
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,
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.
#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
59
GDC-Kamareddy Prepared By : D.Balakrishna
Output
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.
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
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
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
63
GDC-Kamareddy Prepared By : D.Balakrishna
data.i : 10
data.f : 220.500000
data.str : C Programming
Difference Between Structure and Union :
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.
65
GDC-Kamareddy Prepared By : D.Balakrishna
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
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
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
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
"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
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
//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
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
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
Abstraction
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
74
GDC-Kamareddy Prepared By : D.Balakrishna