Professional Documents
Culture Documents
New Edited
New Edited
Example
int a,sum,flag;
float area, circ;
Arithmetic Statements
The arithmetic statements are used to perform different arithmetical operations.
A C arithmetic statement consists of a variable name on the left hand side of = and variable names & constants on
the right hand side of =.
The variables and constants appearing on the right hand side of = are connected by arithmetic operators like +, -, *,
and /.
The syntax of arithmetic statement is
variable=expression;
Where expression may a variable, a constant or a mathematical expression.
Example
a=b;
k=10;
c=a+b;
TYPES OF ARITHMETIC
STATEMENTS
The control statements are certain kinds of statements that are able to alter program flow.
Based on the decision (i.e. true or false) it has taken, control will branch to somewhere else or it will
execute some statements repeatedly.
Hence, the control statements are broadly classified into categories. They are
i is initialized to 1.
#include<iostream.h>
void main()
{
int i=1;
do
{
cout<<i;
i++;
}while(i<=5);
}
Output
12345
Various forms of for loop in C
1. Initialization part can be skipped from loop as shown for (num=10; num<20; )
below, the counter variable is declared before the loop. {
/*Statements */
int num=10; num++;
for (;num<20;num++) }
Note: Even though we can skip initialization part but 3. The counter variable is initialized before the
semicolon (;) before condition is must, without which loop and incremented inside the loop. This is also
we will get compilation error. possible.
2. Like initialization, you can also skip the increment part int num=10;
as we did below. In this case semicolon (;) is must after for (;num<20;)
condition logic. In this case the increment or decrement {
part is done inside the loop. /*Statements*/
num++;
}
4. We can use 2 or more loop control variables.
#include<stdio.h>
void main() 5. The infinite loop
{
int i,j; for(;;) statement;
for(i=0, j=10; i<10; i++, j--) The code below will print hello world for infinite number
{ of times
cout<<i<<" +" <<j<<"=
“<<i+j<<endl; for( ; ; )
} printf("Hello World\n");
cout<<"The value of i is “<<i;
} There is no need of any expression for an infinite for
In the example above, i and j both are loop.
initialized, separated by a comma operator. In
the increment expression, i is incremented and
j is decremented.
6. Comma operator in for loop
Example
The comma operator (,)is primarily used in
conjunction with the ‘for’ statement. This #include<stdio.h>
operator permits two different expressions to void main()
appear within the for loop syntax. {
int x=0,j,k;
Syntax: cout<<“\n The values of K,J and X
are \n”;
for(initial condition1,initial condition2;Test for(k=0,j=5;k<5;k=k+2,j--)
condition;updation1, updation2) {
{ x++;
Statements; cout<<k<<"\n\t"<<j<<"\t“<<
} x<<endl;
}
We can have any number of initial conditions }
separated by comma operator and any number
of updation parts separated by comma operator
but only one test condition is allowed.
The break and continue Statements
With the help of break and continue statements, we can jump out of loop anytime and able continue
looping by skipping some part of the code.
In any loop break is used to jump out of loop skipping the code below it without caring about the
test condition.
It interrupts the flow of the program by breaking the loop and continues the execution of code
which is outside the loop.
The common use of break statement is in switch case where it is used to skip remaining part of the
code.
How does break statement works?
/* Program to calculate the sum of a maximum of 10 numbers If
a negative number is entered, the loop terminates */
# include <iostream.h>
int main()
{
int i;
double number, sum = 0.0; cout<<"Sum = “<<sum;
for(i=1; i <= 10; ++i) return 0;
{ }
cout<<"Enter a number “<<i;
cin>>number; Output
Enter a number1: 2.4
/* If the user enters a negative number, the loop ends */ Enter a number2: 4.5
if(number < 0.0) Enter a number3: 3.4
{ Enter a number4: -3
break;
} Sum = 10.30
sum += number; // sum = sum + number;
}
The continue statement in C
Like a break statement, continue statement is also used with if condition inside the loop to
alter the flow of control.
When used in while, for or do...while loop, it skips the remaining statements in the body of
that loop and performs the next iteration of the loop.
Unlike break statement, continue statement when encountered doesn’t terminate the loop,
rather interrupts a particular iteration.
How continue statement works?
/* Program to calculate the sum of a maximum of
10 numbers. Negative numbers are skipped from
the calculation */ cout<"Sum = “<<sum;
temp[0] is 13.1
temp[1] is 4.3
temp[2] is 0
temp[3] is 0
temp[4] is 0
ACCESSING ELEMENTS OF AN
ARRAY
Once an array is declared, let us see how individual elements in the array can be referred.
This is done with subscript, the number in the brackets following the array name.
Thus, marks [2] is not the second element of the array, but the third.
The first time through the loop, i has a value 0, so the cin
statement will cause the value typed to be stored in the array
element marks[0], the first element of the array.
Reading Data from an Array
The balance of the program reads the data back out of the array and uses it to calculate the average.
The for loop is much the same, but now the body of the loop causes each student’s marks to be added
to a running total stored in a variable called sum.
When all the marks have been added up, the result is divided by 30, the number of students, to get the
average.
In C there is no check to see if the subscript used for an array Usually a symptom of out of bounds access is
exceeds the size of the array. some kind of undefined runtime error.
Data entered with a subscript exceeding the array size will simply For instance, your program may be crashing
be placed in memory outside the array; probably on top of other but not display an error message.
data, or on the program itself.
This will lead to unpredictable results, to say the least, and there
will be no error message to warn you that you are going beyond
the array size.
Where data_type can be any C data type (int, char, long, long long, double, etc.) and
array_name will be a valid C identifier, or variable.
Multidimensional arrays may be used by specifying
bracketed[] values for each row.
A two-dimensional array a, which contains three rows
and four columns can be shown and thought about like Below is an array with 3 rows and each row has 4
this – columns.
int a[3][4] = {
{0, 1, 2, 3} , /*
initializers for row indexed by 0 */
{4, 5, 6, 7} , /*
In this sense, every element in the array a is identified by an initializers for row indexed by 1 */
element name in the form a[i][j], where 'a' is the name of {8, 9, 10, 11} /*
the array, and 'i' and 'j' are the indexes that uniquely initializers for row indexed by 2 */
identify, or show, each element in 'a'. };
The total number of elements in this array would be 12 The inside braces, which indicates the wanted row, are
elements(3 x 4 =12). optional.
The following initialization is the same 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
The array that we have in the example below is
An element in a two-dimensional array is having the dimensions 5 and 4.
accessed by using the subscripts, i.e., row index
and column index of the array. These dimensions are known as subscripts. So this
array has first subscript value as 5 and second
For example − subscript value as 4.
int val = a[2][3]; So the array abc[5][4] can have 5*4 = 20 elements.
The above statement will take the 4th element To store the elements entered by user we are using
from the 3rd row of the array. two for loops, one of them is a nested loop.
How to store user input data into 2D The outer loop runs from 0 to the (first subscript -
array? 1) and the inner for loops runs from 0 to the
(second subscript -1).
We can calculate how many elements a two
dimensional array can have by using this This way the the order in which user enters the
formula: elements would be abc[0][0], abc[0][1], abc[0][2]…
so on.
The array arr[n1][n2] can have n1*n2 elements.
#include<stdio.h>
int main()
{
/* 2D array declaration*/
int abc[5][4];
return 0;
}
However the actual representation of this array in memory would be something like this:
#include<iostream.h>
float findAverage(int marks[]);
int main()
returntype functionName(type1 parameter1, type2 The function body contains the declarations and
parameter2,...) the statements(algorithm) necessary for
{ performing the required task. The body is enclosed
// function body goes here within curly braces { ... } and consists of three
} parts.
In this method, We won’t pass any arguments to the function while defining, declaring or
calling the function.
This type of functions will return some value when we call the function from main() or any sub
function.
Function with no arguments means called function does not receive any data from calling
function and function with return value means one result will be sent back to the caller from
the function.
Example
int large() /* function definition */
{
int i, j, greaterNum;
#include<iostream.h>
cout<<"Enter 2 numbers that you want
to
int large(); /* function declaration */
compare...";
cin>>i>>j;
void main()
if(i > j)
{
{
int result;
greaterNum = i;
result = large(); /* function call */
}
cout<<"The greater number is: “<<result;
else
}
{
greaterNum = j;
}
/* returning the result */
return greaterNum;
}
Function with no arguments and no return
value
Function with no argument means the called function does not receive any data from calling function and
Function with no return value means calling function does not receive any data from the called function.
So there is no data transfer between calling and called function.
void large() /* function definition */
{
Example int i, j;
cout<<"Enter 2 numbers that you want to compare
include<iostream.h> cin>>i>>j;
if(i > j)
void large(); /* function declaration */ {
cout<<"The greater number is: “<<i;
int main() }
{ else
large(); /* function call */ {
return 0; cout<<"The greater number is: “<<j;
} }
}
#include <stdio.h>
Recursion int factorial(int number);
int main()
The process by which a function calls itself is known as {
recursion. int x = 6;
Two fundamental rules of recursion are cout<<"The factorial of “ <<x<<" is\n“<<
1. Base cases: A recursive function must have some factorial(x);
base cases, which can be solved without recursion. return 0;
2. Making Progress: For the cases that are to be solved }
recursively, the recursive call must always be to a int factorial(int number)
case that makes progress toward a base case. {
if (number == 1)
return (1); /* exiting condition
*/
else
return (number *
factorial(number - 1));
}
This pointer variable takes some space in memory and hence it also has an address.
We can store the address of a pointer variable in some other variable, which is known as a pointer to pointer
variable.
Similarly we can have a pointer to pointer to pointer variable and this concept can be extended to any limit, but
in practice 0nly pointer to pointer is used.
Example :
int **pptr;
Here variable pptr is a pointer to pointer and it can point to a pointer pointing to a variable of type int. The double
asterisk used in the declaration informs the compiler that a pointer to pointer is being declared.
Here the variable a is an int, j is pointer to int and k is
Let us consider the following declarations: pointer to pointer.
int a = 10; The following program demonstrates the concept of
int *j = &a; pointer to pointer.
int **k = &j;
#include<iostream.h>
Here type of variable a is int, type of variable j is (int*) or main( )
pointer to int, and type of variable k is (int **) or pointer to {
pointer to int. int a=10;
int *j;
Consider the following memory map: int **k;
j=&a;
k=&j;
a k
cout<<"Address of a = " <<&a<<endl;
j
cout<<"Value of j = Address of a= “<<j<<endl;
10 4500 3200
cout<<"Value of *j = Value of a= “<<*j<<endl;
4500 3200 4850 cout<<"Address of j = “<<&j<<endl ;
cout<<"Value of k = Address of j = “<<k<<endl;
cout<<"Value of *k = Value of j=“<<*k<<endl';
cout<<"Value of **k= Value of a = “<<**k<<endl;
cout<<"Address of k = “<<&k<<endl;
}
REFERENCE VARIABLE
C++ introduces a new kind of variable known as the reference variable.
A references variable provides an alias(alternative name) for a previously defined variable.
For example ,if we make the variable sum a reference to the variable total, then sum and total can be used
interchangeably to represent the variable.
A reference variable is created as follows:
Synatx:
Datatype & reference –name=variable name;
Example:
float total=1500;
float &sum=total;
Here sum is the alternative name for variables total, both the variables refer to the same data object in the memory .
A reference variable must be initialized at the time of declaration .
PARAMETER PASSING MECHANISMS
Functions can be invoked in three ways: Call by Value , Call by Address and Call by Reference . These
three ways are generally differentiated by the type of values passed to them as parameters.
The parameters passed to function are called actual parameters whereas the parameters received by
function are called formal parameters.
CALL BY VALUE
So any changes made inside functions are not In call by values we cannot alter the values of actual
reflected in actual parameters of caller. variables through function calls.
#include <iostream.h>
void swapval(int x, int y); /* Function Prototype */
void main()
{ cout<<“x= “<<x<<“y= “<<y<<endl;
int a = 10, b = 20; }
t = x;
x = y;
y = t;
CALL BY ADDRESS
In this method, both the actual and formal With this method, using addresses we would have
parameters refer to same locations, so any an access to the actual variables and hence we
changes made inside the function are actually would be able to manipulate them.
reflected in actual parameters of caller.
In call by address we can alter the values of
While calling a function, instead of passing the variables through function calls.
values of variables, we pass address of
variables(location of variables) to the function Pointer variables are necessary to define to store
known as Call By address. the address values of variables.
C++ allows us to call a function with out specifying all its A subsequent function call like
arguments. value=amount(5000,7); //one argument missing
In such cases, the function assigns a default value to the passes the value of 5000 to principle and 7 to
parameter which does not have a matching arguments in the period and then lets the function, use default
function call. value of 0.15 for rate.
Default values are specified when the function is declared . The call:-