|
|
Summary
• Bitwise Manipulation and Assignment Operator
• Design Recipes
• Variables
• Data Types
• Operators
- Arithmetic operators
- Logical operators
- Bitwise operators
• Programming Constructs
• Decisions
- if statement
- Nested if statement
• Loops
- while loop
- do-while loop
- for loop
• switch, break and continue Statements
• Functions
- Function Calling
- Top-Down Methodology
• Arrays
• Pointers
• File I/O
Page 270
Bitwise Manipulation and Assignment Operator
Last time we discussed bitwise operators, we will continue with the elaboration
of bitwise
manipulation and assignment operator.
C/C++ are well constructed languages, at start we used to write:
a = a + 1;
This is used to increment the variable. Then we came to know of doing it in a different
manner:
a += 1;
This is addition and assignment operation using single operator +=.
The same thing applies to bitwise operators; we have compound assignment operators
for
& (bitwise AND), | (bitwise OR) and
^ (bitwise exclusive OR). It is written in the same
way as for the above mentioned arithmetic operators . Suppose we want to write:
a = a & b;
It can be written as:
a &= b;
Similarly for | and ^ operations we can
write the statement in the following fashion.
a |= b;
and
a ^= b;
Remember, the ~ (NOT) operator is unary as it requires only
one operand. Not of a
variable a is written as: ~a. There is
no compound assignment operator available for it.
Now we will recap topics covered in the previous lectures one by one.
Design Recipe
Our problems, typically, are of real world nature, e.g., Payroll of a company. These
problems are expressed in words. As a programmer we use those words to understand
the
problem and to come up with its possible solution.
To begin with the comprehension and resolution process, we analyze the problem and
express the problem in words in reduced and brief manner. Once we have reduced it
into
its essence, we put some examples to formulate it. For example, if the problem is
to
Page 271
calculate the annual net salary of employees, we can take an example for a particular
employee X. Later we will refine the problem, write program and test it. Finally
we
review it if it has met objectives. We have discussed all these steps in Design
Recipe.
There was a main heading in the topic, "Pay attention to the detail". Never forget
this as
our computers are very dump machines. They perform exactly whatever we tell them.
It is important to keep in mind that we are using C/C++ as a vehicle to understand
programming concepts.
Variables
The computer memory can be thought of as pigeon holes each with an address. To store
numbers or characters in computer memory, we need a mechanism to manipulate it and
data types are required for different types of data. Instead of using hard coded
memory
addresses with data types, symbolic names are used. These symbolic names are called
variables because they can contain different values at different times. For example,
int i;
double interest;
i and interest are symbolic names or variables
with types of int and double respectively.
Data Types
int type is used to store whole numbers. There are some varieties of
data types to store
whole numbers e.g., short and long.
unsigned qualifier is used for non-negative
numbers. To represent real numbers we use float data type.
For bigger-sized real
numbers double data type is used. char
data type is used to store one character.
Generally, the size of the int type on our machines is 4 bytes
and char is 1 byte. chars
are enclosed in single quotation mark. ASCII table contains the numeric values for
chars.
We further discussed a bit later stage about the aggregations or collections of
basic data
types (int, float and char
etc) called arrays. Arrays
are used to aggregate variables of
same data type.
Operators
We discussed three types of operators:
- Arithmetic Operators
- Logical Operators
- Bitwise Operators
Page 272
Arithmetic Operators
+ operator is used to add two numbers, - is used
to subtract one number from the other, *
is used to multiply two numbers, / is used to divide numbers.
We also have a modulus
operator % , used to get the remainder. For example, in the
following statement:
c = 7 % 2;
7 will be divided by 2 and the remainder 1 will be the stored
in the variable c. We also
used this operator in our programs where we wanted to determine evenness or oddness
of
a number. There are also compound arithmetic operators +=,
-=, *=, /= and also
%= for
our short hand. It is pertinent to note that there is no space between these compound
operators.
Logical Operators
The result for logical operators is always true or false. &&
(AND operator) and || (OR
operator). Logical Comparison operators are used to compare two numbers. These
operators are: <, <=, ==,
>, >=. Don't confuse the ==
operator of equality with = operator
of assignment.
It is important for us to remember the difference between these two operators of
equality
(==) and assignment (=) . However, C/C++ creates a little problem for us here. When
we
write a statement as:
a = b;
The assignment statement itself has a value, which is the same as that of the expression
on the right hand side of the assignment operator. We can recall from our last lecture
that
we only wrote a number inside the if statement. We also know that if the resultant
inside
the if statement is non-zero then its code block is executed. In case, the result
is zero, the
control is transferred to the else part.
If we want to compare two variables a and b
inside if statement but wrongly write as:
if ( a = b )
{ // if code block
// do something
}
else
{
// do something else
}
Page 273
In this case, if the value of the variable b is non-zero (and
hence value of the statement a
= b is non-zero) then if code block will be executed. But this was not
required, it is a
logical fault and compiler was unable to detect it. Our objective was to compare
two
variables. For that purpose, we should have used assignment operator ==
for that as:
if ( a == b )
One should be very careful while using comparison operators. You should not miss
any
case of it and be sure about what you want to do and what will be the output of
a
comparison statement.
You should keep in mind straight line of Calculus for the sake of completeness,
you
should always divide your domain into two regions. If we take >= as one region then
the
other region is <. Similarly if we say <
as a region, the other region is >=.
Depending on
the problem requirements, these regions should be very clear.
Bitwise Operators
& is bitwise AND operator, | is bitwise OR operator,
^ is bitwise Exclusive OR operator
and ~ is bitwise inversion or NOT operator. ~
(NOT operator) is unary operator as it
requires one operator and the remaining operators &, | and ^ are binary operators
because
they require two operands.
Programming Constructs
For us, it is not necessary to know who is the one to devise or decide about these
constructs to be part of the program logic. The important thing is the concept of
programming constructs, required to write a program. We have earlier discussed three
constructs.
1. The sequential execution of statements of a program. Execution
of statements begins
from very first statement and goes on to the last statement.
2. Secondly we need decisions that if something is true then
we need to do something
otherwise we will do something else. We use if statement for this.
3. The third construct is loops. Loops are employed for repetitive
structures.
Decisions
Normally, if statement is used where decisions are required.
Page 274
If statement
The syntax of if statement is fairly simple i.e.
if (condition)
{
// if code block
}
else
{
// else code block
}
The result of the condition can be either true or false. If
the condition is true, if code
block is executed. Braces of the if code block are mandatory but if there
is only one
statement in the if code block then the braces can be omitted or are optional. Now
if the
condition is false, the if code block is skipped and the control
is transferred to the else
part and else code block is executed. Else part is optional
to associate with the if part.
So without else the statement looks like the following:
if (condition)
{ // if code block
// Do something here
}
Use of braces is again mandatory. Again, however, if there is only statement inside
the
else part then brace is optional.
As a programming practice, use of braces all the time is recommended. It makes your
program more readable and logically sound.
What happens when the condition is complex?
Nested if statement
For complex conditions, we use logical connectives like &&,
||. For example:
if ( a > b && a < c)
If there are nested decisions structure that we want to do
something based on some
condition and further we want to do something more based on an additional condition.
Then we use nested if-statements as under:
if ( a > b && a < c )
{
// Do something
if ( a == 100 )
Page 275
{
// Do something more
}
else
{
// Do something else more
}
}
else
{
// Do something else
}
From stylistic and readability perspective, we properly indent the statements inside
ifstatements
as shown above.
We discussed pictorial representation of if-statement. By using flowchart of if
statement
that was a bit different than normally we see inside books, we introduced structured
flowcharting.
In structured flowcharting, we never go to the left of the
straight line that joins Start
and Stop buttons. There is a logical reason for it as while
writing code, we can’t move to
the left outside the left margin. Left margin is the boundary of the screen and
indentation
is made towards the right side. So we follow the construct that is equivalent to
the
program being written. The major advantage of this approach is achieved when we
draw
a flowchart of solution of a complex problem. The flowchart is the logical depiction
of
the solution to the problem. One can write code easily with the help of the flowchart.
There will be one to one correspondence between the segments of the flowcharts and
the
code.
Loops
Going on from the decision structures we discussed about loops. In our program if
we
have to do something repeatedly then we can think of applying loop structure there.
There are few variants of loops in C language. However, other languages might have
lesser number of loop variants but a programming language always has loops constructs.
While Loop
The syntax of the while loop is as follows:
while ( condition )
{ // while code block
// Do something
}
Page 276
The condition is a logical expression like a == b that returns true or false. Braces
are
mandatory to for while loop when there are multiple lines of code inside the while
code
block. If there is only single line inside the while code block, the braces become
optional.
It is good practice to use braces. The statements inside the while code block are
never
executed, if the while condition results in false for very first time it is entered.
In other
words, statements inside the while code block executes 0 to n times.
Page 277
The flowchart for the while loop is as follows:
Do-While Loop
Next loop variant is Do-while. It syntax is as under
do
{ // do-while code block
// Do something
}
while ( condition )
The important difference of this loop from the rest ones is that it is executed
once before
the condition is evaluated. That means the statements of do-while code block execute
at
least once.
False
condition
while
Process
Exit
True
Page 278
The flowchart for do-while loop is given below:
For Loop
The for loop becomes bread and butter for us as it gathers
three things together. The
syntax for the for loop is as follows:
for ( initialization statements; condition; incremental statements)
{ //for code block
// Do something
}
E.g.,
for ( int i = 0; i < 10; i ++)
{
}
The for loop is executed until the condition returns true otherwise
it is terminated.
do while
Exit
False
condition
True
Process
Page 279
The braces are not mandatory if there is single statement in the for code block.
But for
sake of good programming practice, the single statement is also enclosed in braces.
Some
people write the for loop in the following manner:
for ( initialization statements; condition; incremental statements){
//for code block
// Do something
}
Both the methods for writing of for loop are perfectly correct. You can use anyone
of
these. If you indent your code properly, the process will become easier.
The flowchart for for loop is as under:
Fals e
condition
for
Process
True
for
Initialization
Statements
for
Incre/Decre
Statements
Page 280
switch, break and continue Statements
For multi-way decisions, we can use nested if-statements or
separate if-statements or
switch statement. There are few limitations of switch statement but
it is necessary to use
break statements in every case inside the switch
statement. If a case results in true when
there is no break statement inside it, all the statements below
this case statement are
executed. break statement causes to jump out of the switch
statement. We use break at
the end of every case statement. By using break,
the jumping out from switch statement
is in a way bit different from the rules of structured programming. But
break statement is
so elegant and useful that you can use it inside switch statement
and inside loops. If we
use break inside a loop, it causes that loop to terminate. Similarly continue
statement is
very useful inside loops. continue statement is used, when
at a certain stage, you don’t
want to execute the remaining statements inside your loop and want to go to the
start of
the loop.
Functions
In C/C++, functions are a way of modularizing the code. A bigger problem is broken
down into smaller and more manageable parts. There is no rule of thumb for the length
of
each part but normally one function’s length is not more than one screen.
Page 281
Function Calling
We covered Functions Calling by value and by reference. The default of C language
is
call by value. Call by value means that when we call a function and pass some parameter
to it, the calling function gets the copy of the value and the original value remains
unchanged. On the other hand, sometimes, we want to call a function and want to
see the
changed value after the function call then call by reference mechanism is employed.
We
achieved call by reference by using Pointers. Remember while calling functions,
call by
value and call by reference are different techniques and default for ordinary variables
is
call by value.
Top-Down Methodology
We discussed top-down design methodology. How do we see a problem at a high level
and identify major portions of it. Then by looking at each portion we identify smaller
parts inside it to write them as functions.
Arrays
After discussing functions and playing little bit with function calling, we had
elaborated
the concept of Arrays. As discussed previously in this lecture, arrays are used
to
aggregate variables of same data type. We wrote little functions about it and did
some
exercises e.g., when we wanted to store age of students of our class. Then instead
of
using a separate variable for each student, an array was employed to store the ages
of the
students. Then to manipulate or to access individual array elements, a technique
array
indexing was used. One important point to remember is that array indexes
start from 0.
Let’s say our array name is a of 10 ints,
its first element will be a[0] while the last one
will be a[9]. Other languages like Fortran carry out 1-based indexing. Due to this
0 based
indexing for arrays in C language, programmers prefer to start loops from 0.
Arrays can also be multi-dimensional. In C language, arrays are stored in row major
order
that a row is stored at the end of the previous row. Because of this storage methodology,
if we want to access the first element of the second row then we have to jump as
many
numbers as the number of columns in the first row. This fact becomes important when
we
are passing arrays to functions. In the receiving function parameters, we have to
write all
the dimensions of the array except the extreme-left one. When passing arrays to
functions, it is always call by reference by default, it is not call by value as
in the default
behavior of ordinary variables. Therefore, if the called function changes something
in the
array, that change is actually made in the original array of the calling function.
When we
pass ordinary variables to functions, they are passed by value because of the default
behavior. But when an array is passed to a function, the default behavior changes
and
Page 282
array is passed by reference. We also did some examples of arrays by using Matrices
and
did some exercises by transposing and reversing a squared matrix. Arrays are not
just
used in Mathematics or Linear Algebra but are employed in a number of other problems
like when we store ages, names, and grades or want to calculate grade point of average.
This is very useful construct especially when used with loops. Normally it is very
rare
that you see an array in a program and loop is not being used to manipulate it.
Like nested if-statements, we have nested loops, used with multi-dimensional arrays.
A
while loop can have an inner while loop. Similarly a for loop can have a for loop
inside.
It is also not necessary that a while loop should have only
a while loop but it can be a for
loop also or any other construct like if-statement.
Pointers
It is very important topic of C/C++ . Pointers are different types of variables
that contain
memory address of a variable instead of a value.
The very first example we discussed for pointers was for implementing function calling
by reference. Suppose we want to interchange (swap) two numbers by making a function
call. If we pass two variables to the function, these will be passed as ordinary
variables by
value. Therefore, it will be ineffective as swapping of variables inside the function
will
only be on the copies and not on the original variables. So instead of passing variables
we
pass their addresses. In the called function, these addresses are taken into pointer
variables and pointers start pointing the original variables. Therefore, the swapping
operation done inside the function is actually carried out on the original variables.
We also saw that Pointers and Arrays are inter-linked. The array name itself is
a pointer
to the first element. It is a constant pointer that cannot be incremented like normal
pointer
variables. In case of two-dimensional arrays, it points to the first row and first
column. In
three-dimensional array, you can imagine it pointing to the front corner of the
cube.
File I/O
We discussed about Files and File I/O for sequential and random files. We used a
mixture
of C/C++ for file handling and how the sequential and random files are accessed.
We saw
Page 283
several modes of opening files. The important functions were seek
and tell functions.
Seek functions (seekg and seekp ) used to move into the file and tell functions
(tellg and
tellp) provided us the location inside the file.
You are required to go with very clear head, try to understand concepts and assess
how
much you have learned so far to prepare for the mid-term examination.
|
|
|
|