Deicision Making and Branching

We have seen that programs are some set of statements written in a specific order. Processor will executed the programs in the order in which it was written. We may come to a situation where we need to alter the sequential execution of the statements to achieve some results. We may need to take some decisions based on the needs of the context for which the program was written and will branch or alter the execution of statements accordingly.  For example, if we are preparing a students results publishing program, then we may need to take decision on whether a student is passed or not.  If a student gets a specified minimum mark or more he is passed otherwise he is failed, this is a simple kind of decision making, we will implement this in C programs using the some decision making/branching control structures and conditions.

Conditions are tested for its truth values and if the condition is true then it will execute some statements, if the condition is false it will execute some other statements or will check another condition for its truth values.  C supports 4 different decision making statements and are commonly used in all other programming languages.

Decision making statements in C

  1. If statement
  2. Switch statement
  3. Conditional Operators
  4. Goto statement

Among the 4 decision making statements, If, Switch and Conditional operators are supported by most of the programming languages.  Goto statement is a branching statement and is not commonly used in many programming languages and in C itself usage of goto statement is not recommended.  Goto statements where the constructs used in the unstructured programming languages for branching and present languages like C, C++, Java etc. possesses structured feature and it follows Sequential, Conditional and Iteration statements in its programs.

Previous
Next

Special Operators and Operator Precedence in C

In the last posts we've discussed about C's all 7 type of operators, now we'll see which all are the Special operators in C.

Special Operators
Operator
Description
Example
,
Used to separate a pair of expressions. 
In this example two initialization expressions
are separated using a comma operator.
for(i=1,j=n;i++,j--)

.
Dot (.) operator is used in C to refer structure
members.
struct student s;
s.id=1021;
s.mark=86;
sizeof( )
Size of operator is used to compute the size of
any variable or any type. It will return the size in bytes.
sizeof(int);
char grade;
sizeof(grade);
->
Arrow operator is used to access structure
members using a structure pointer variable.
struct student p*;
p=&s;
p->id;

Notes
  • Comma operator is used to separate a pair of instructions, its commonly used in for loop to initialize or update more than one variable.  For example : for(i=0,j=n;i
  • If we defined a user defined structure data type, then its members are accessed its variable by a dot (.) operator.
  • sizeof( ) operator is a special operator, which will take a variable or a type as argument and will return the size of its argument in bytes.  For example, sizeof(int) will return 2. char ch; sizeof(ch) will return 1.
  • -> operator is used with structure pointers to access the structure members.

Operator Precedence and Associativity


When a combination of operators are used in an expression, then that mixed expression will be evaluated in the order of precedence of the operator used in that operation.  BODMAS theoram is applicable to the precedence  for arithmetic operators.  The following is the precedence of the C operators :

1.  ( )
2.  ++, --, !, sizeof( )
3.  /, %, *
4.  +, -
5.  <, <=, >, >=
6.  !=, ==
7.  &&
8.  ||
9.  ? :
10. All assignment and shorthand operators.
11. ,

If more than one same operator used in an expression then it will be evaluated in the order of its associativity rule.  !, ++, --, ? :, =,  +=, -=, *=, /= are evaluated from Right to left and rest of all operators discussed above are evaluated from Left to right.

Previous
Next

Conditional Operators, Increment/Decrement and Bitwise perators

Conditional Operators
OperatorUsageDescription
? :(Condition)?(Expr 1):(Expr 2);
Condition will be tested and if it is true then expression 1 will be evaluated, if the the condition is false then expression 2 will be executed.

Notes
  • Conditional operator is a ternary operator as because it takes 3 operands.
  • Conditional operator is used for making decisions. A test condition is evaluted and if it is true then the expression or value immediately follows the ? will get executed, and if the condition is false, then expression or value after the : will get executed.

Increment/Decrement Operators
OperatorUseDescription
++ (Increment)i++ or ++iIncrement the value of i by 1. If the value of i is 1, then
after execution of i++, value of i will be 2.
-- (Decrement)i-- or --iDecrement value of i by 1.

Notes
  • Increment and Decrement operators are unary operators and which takes only one operand
  • Increment/Decrement operator can be used in place where we need to increment the value of an operand by one. For example i=i+1 can be replaced with i++, similary i-- can be used instead of i=i-1
  • These operators can take two forms : Post increment/Post decrement and Pre increment/Pre decrement. If an increment/decrement operator is used before the variable then it is pre increment/pre decrement operator and if it is written after the variable then it is called post increment/post decrement.
  • The difference between the pre and post operator occurs when it is used in an expression. In pre incrementing/pre decrementing the value of the variable is incremented/decremented first and then new value is taken with the expression. In post incrementing/decrementing, the value of the variable is incremented/decremented only after evaluation of execution. So the current value of variable will be used with the expression and after its execution the value will be incremented or decremented

Assignment/Short hand Operators
OperatorUsageDescription
= (Assignment)a=5; b=i+10;Used to assign the value to a variable. Value 5 will be assigned to a and likewise resultant value of the expression i+10 will be assigned to b.
+=a+=2;Short hand assignment operation. Value 2 will be added with a and the result stored in a and is similar to the expression a=a+2.
-=a-=b;
Subtract b from a and store the result in a, similar to a=a-b.
*=a*=a;
Square the value of a and store it in a (a=a*a).
/=a/=2;
Divide a by 2 and store the quotient in a (a=a*2).
%=a%=b;
Find the remainder of the operation a/b and store the remainder in a (a=a%b).

Notes
  • +=,-=, *=, /=, %= is also known as short hand operators.

Bitwise Operators
OperatorMeaningDescription
& (Bitwise AND)A & B
It will check the binary values of A and B, and result will be 1 corresponding bit positions of both the binary values are 1 otherwise it will be 0. For example : 01011 & 11010 => 01010
| (Bitwise inclusive OR)A | BBit value is set to 1 if either binary bit values are 1 or if any one bit is 1, otherwise it will be set to 0. For example : 01011 | 11010 => 11011
^ (Bitwise exclusive OR)A ^ BBitwise exclusive OR operator sets a 1 in each bit positions where its operands have different bits, if the bit values are same then it will set a 0. For example : 01011 ^ 11010 => 10001
~ (1's complement)~AProduces 1's complement of an integer, this operator Will invert bit values. 1' complement operator will change the bits 0 to 1 and 1 to 0. For example : ~01011 => 10100
<< (Left shift)A << B Shift bits of A by B distance to the left, shifted bits will be lost and vaccated least significant bits will be filled with 0's .
>> (Right shift)A >> BShift bits of A by B distance to the right, shifted bits will be lost and vaccated most significant bits will be filled with 0's .

Notes
  • Bitwise operators make C unique in high level languages, and this is because C is known as high level language with low level features.

Previous
Next

Operators in C

Arithmetic Operators
OperatorDescriptionExample
+To add two numeric valuesa+b
-Used for subtractiona-b
*To multiply two numeric valuesa*b
/Used for divisiona/b
% (Modulo operator)To compute the remainder of a division operationa%b

Notes
  • An arithmetic operation on two integer values always yields an integer result.
  • Operation between float and float yields a float result.
  • Operation on integer and a float value will results a float result
  • % operator cannot be used with float or double values

Relational Operators
OperatorUseDescription
>a>bExpression return true if a is greater than b
>=a>=bTrue if a is greater than or equal to b
<a
True if a is less than b
<=a<=bTrue if a is less than or equal to b
==a==bTrue if a is equal to b
!=a==bTrue if a and b are not equal

Notes
  • Relational operators are comparison operators which will compare two values and will return true or false.
  • Relational operators are used in conditional expressions.
  • == is an relational operator to check the equality of two values, but a single = operator is assignment operator.

Logical Operators
OperatorMeaningDescription
&&Logical ANDCombine to conditional expressions, and will return true if both conditional expressions are true otherwise it will return false.
||Logical ORCombine to conditional expressions, and will return false if both conditional expressions are false otherwise it will return true.
!Logical NOT
Negate a conditional expression

Notes
  • Logical AND operator is used to combine two conditions, and the whole expression that is connected by the AND (&&) operator will return only true if both conditions are true, otherwise it will return false.
  • Logical OR operator is used to combine two conditions, and the whole expression that is connected by the OR (||) operator will return true if any one condition is true, otherwise it will return false.
  • Logical NOT operator is used to negate the conditional value, if a condition 'CON' yields a true then !CON will return false, if condition CON is false then !CON will return true.

Previous
Next

Operators and Expressions

All processes are done at the Arithmetic & Logic Unit of the computer - ALU. All operations or processes are performed as arithmetic & Logic operations in ALU. C is rich with its efficient operators, using which we can easily write efficient programs.

Operator is nothing but a symbol which instructs the computer what operation it has to perform.

In machine languages, an operator may be a combination of binary 0's and 1's, i.e. there will be a unique 0's and 1's combination for each operations, say for addition, subtraction, comparison etc. In Assembly language we uses the instruction set to perform the operations, for addition operation we may use ADD instruction, similarly CMP instruction can be used for comparison. In modern high level languages, we can use symbols similar to those used in maths or real life to instruct the computer for a particular operation. For example '+' symbol can be used to instruct the computer for an addition operation, similarly '-','*','/' symbols can be used to perform the other 3 arithmetic operations.

An operator tells the computer what to do with the associated operands. Operands are the memory values that we need to manipulate to get the results. So our instructions would be a combination of operators and operands, and such a combination is known as an expression. For example sum=a+b is an expression and contain 3 operands - sum, a, b and two operators '+' and '='. Here + operator directly deal with two operands (a and b) and is used to add two values, so '+' (Addition) operator is a binary operator. An operator is a binary operator if it deal with or uses two operands for operations. '-' (subtraction) operator is a binary operator and uses two operands - minuend and subtrahend, '-' operator can also be used to represent a negative value, say -10, here '-' is associated with only one operand is a 'unary minus'/ unary operator.

Operators are one of the striking feature of C. C supports different types of operators.

Operators in C

1. Arithmetic Operators [ + , - , *, /, % ]

2. Relational Operators [ > , < , >=, <=, ==,!= ]

3. Logic Operators [ &&, ||, ! ]

4. Assignment Operators [ =, +=, -=, *=, /= ]

5. Conditional Operators [ ?, : ]

6. Increment/Decrement Operators [ ++, --]

7. Bitwise Operators [ &, ^, ~, >>, << ]

8. Special Operators [ ,  .  sizeof() -> ]

Previous
Next

Sample C Programs

Sailing through Programs

Here we will do some sample programs from the knowledge of what we have learned so far.

/* Program to do all arithmetic operations */

#include<stdio.h>
#include<conio.h>
main( )
{
int a,b,sum,pro,diff,quo;
clrscr( );
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);

sum=a+b;
pro=a*b;
diff=a-b;
quo=a/b;

printf("Sum=%d\n",sum);
printf("Difference=%d\n",diff);
printf("Product=%d\n",pro);
printf("Quotient=%d\n",quo);
getch( );
}

In this program we need to do all arithmetic operations on two numbers, so there have to be two variables to store two numbers, and to store the result of four arithmetic operations we need 4 variables. So we have declared all 6 variables, 'a' and 'b' for storing two numbers and sum, pro, diff, and quo to store the arithmetical operation's results. Whenever you use a variable in your program try to give some meaningful name.

After Declaring two numbers, we are prompting for the user to enter two numbers, and the values thus enter by the user are stored in to 'a' and 'b'. So we got that two numbers to perform the arithmetical calculations, then we added all those code to find the sum, product, quotient, and division. Then print the result we've calculated.

/*Program to Interchange two values without using any other variables*/

#include<stdio.h>
#include<conio.h>
main( )
{
int a,b;
clrscr( );
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);

printf("\nBefore Swapping the Values\n");
printf("a=%d\tb=%d\n",a,b);

a=a+b;
b=a-b;
a=a-b;

printf("\nAfter Swapping the Values\n");
printf("a=%d\tb=%d\n",a,b);

getch( );
}

A simple logic is applied to swap the values.

Before-> a=10 and b=20
a=a+b; /* a=30 and b=20 */
b=a-b; /* a=30 and b=10 */
a=a-b; /* a=20 and b=10 */
After-> a=20 and b=10

Multiplication and Division technique can also be used to swap the values. Use the following logic:-

Before-> a=10 and b=2
a=a*b; /* a=20 and b=2 */
b=a/b; /* a=20 and b=10 */
a=a/b; /* a=2 and b=10*/
After-> a=2 and b=10

Previous
Next

Reading Data from the Keyboard

A program is nothing if it is not accepting any data from the user or outputs some data to the user. A program is interactive only if it accepts data's from the user at run time. It should accepts data needed for the program and output the result based on the user input. For example a user may want to input basic salary of an employee to calculate his net salary, he can use the same program to calculate the net salary of another employee by inputting different values upon his requirement.

C provides a library function scanf( ) that accepts data's from the keyboard. It uses the following syntax :

scanf("control string",&variable_name");

control string uses the control string for the type of variable_name, i.e. if we are reading an integer value then control string will be %d, if we are reading a character value then the control string is %c. Variable name preceded by an ampersand (&) symbol. Ampersand (&) is also known as "address of operator", address of operator instructs the computer where to store the data read from the keyboard. Ampersand operator provides the memory address of the variable we specified, and the value just inputted stored to that memory location, we can access the value using the variable name.

scanf("%d",&age); //reading an integer value;
scanf("%f",&avg);//reading a float value;
scanf("%c%d",&grade,&roll); //reading a character and an integer.
scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5);//reading 5 integers.

Learning by Example 2

/* Program to read two numbers and find their sum */
#include<stdio.h>
#include<conio.h>
main( )
{
int a,b,sum; /* declare three integer variables */
clrscr( );
printf("Enter two numbers : "); /* Prompt the user to enter two numbers */
scanf("%d%d",&a,&b); /* Read two integers from keyboard values in a and b */
sum=a+b; /* add a and b, store result in sum */
printf("Sum=%d",sum); /* Print the value in sum */
/*printf("%d+%d=%d,a,b,sum); */ /* Try using this to print sum*/
getch( );
}
int a,b,sum; will declare three integer variables a,b,sum each variable will get 2 bytes memory space allocated, a,b and sum now may contain some garbage values.

Next we are prompting the user to enter two numbers using the printf( ), it is necessary in our programs to instruct the user what to do next, or what to do from his side for program execution.

While executing scanf("%d%d",&a,&b); the control will wait for two values from keyboard, input two numbers and that numbers will be stored in the variable a and b. Here first number will be stored in variable 'a' and second will be in variable 'b'.

sum=a+b; will add the values within 'a' and 'b' and assignment operator (=) will assign the value thus results to the variable 'sum'.

printf("Sum=%d",sum); will print the sum in the format Sum=250 (If we input two number 175 and 75).

Previous
Next

Variables, Constants, Keywords & Datatypes

All programs deal with some sort of data, a program accepts some data from the user and manipulates it and provide the manipulated/processed data - the information. We may use different kinds of data in our programs, it may be a constant value, or a varying type known as variable. The type of data's used may be different, for example in a mark list preparing program the datas may include student_name,subject,mark,roll_no,avg etc., student_name is a data which uses some characters to form a student name, roll_no represents student's roll number and it may be a number-an integer. Likewise avg may be a decimal value. So we are dealing with different kinds of data.

Constants are data value which is predefined before a program is used. Values remain unchanged during the program execution. For example "C Program" is a string constant.

Variables are identifiers which we used to represent or identify a data. Variables are varying type values. Here the data may change or be assigned different values as the program runs. For example

emp_salary=12000; (emp_salary is a variable which holds the value 12000)
emp_salary=12500; (now emp_salary contains the value 12500)

There are some rules when using variable names.

Rules of naming variables

1. Variable name should only contain alphabets (a-z,A-z), digits(0-9) and underscore(_).
2. Variable name must start with an alphabet or an underscore.
3. Variable name should not contain any blank space.
4. Pre defined words in C (known as Keywords) cannot be used as a variable name.

Care should be taken while program in C as keywords or variables used in C are case sensitive.

Keywords are the basic constructs used to write a program. Keywords have a predefined meaning in C. For example int is a keyword used to declare an integer variable. Keywords cannot be used as a variable/function name.

Variables are used to represent a data in a program, each data may be of different type, age data may be a numeric type(integer). Grade of a student can be a character. So all variables used in a C program must be declared to the appropriate type before we use those variables. Each variables thus declared possess some space of memory to hold the value it represents. In C data types can be divided as Primary and Secondary(Derived).

Primary Data types : int, char, float, double. int data type can be used to represent an integer value, char data type is used to represent a single character, float data type is used to store a decimal value, double data type is used to declare a double precision floating point. Each type have a range of values that it can hold, and each type allocates a specific byte of memory for the value.

1. int
Range : -32768 to +32767
Memory : 2 bytes
Control String : %d

2. char
Range : -128 to +127
Memory : 1 byte
Control String : %c

3. float
Range : 3.4e-38 to 3.4e+38
Memory : 4 bytes
Control String : %f

4. double
Range : 1.4e-308 to 1.4e+308
Memory : 8 bytes
Control String : %lf

int data type allocates 2 bytes to store an integer number. A variable declared as int can hold an integer value in the range of -32768 to +32767. If you want to store an integer above this range instead of int you may use long int, control string of long int is %ld. Control string is associated with C data types and you are required to use appropriate control string with each variable used in your program while you read a data to the variable or print a data in variable. Control string enables the format of data in the variable.

Secondary Data types can be created from the existing data types. It includes arrays, structures, unions, enums, linked lists, pointers etc.

Declaring a Variable : You can declare a variable by specifying the data type of that variable.

Syntax : <datatype> <variable_name>;

int age; /*Declare an integer variable age.*/

float avg,mark; /*2 variables are declared. 4 bytes allocated to each variable, and can store any values which falls in the float range.*/

float avg; /*variable avg is declared*/
avg=98.74;/*avg is initialized with value 98.74*/

char ch='A'; /*a character variable ch is declared with the value A.*/

So now have a look at the program with some variables

/*Program to print variable values */
#include<stdio.h>
#include<conio.h>
main( )
{
int num=850;
float avg=98.54;
double dblval;
char ch='S';
dblval=99745.5684;
clrscr( );
printf("Character ch=%c",ch);
printf("\nInteger num=%d",num);
printf("\nFloat avg=%c",avg);
printf("\nDouble dblval=%lf",dblval);
/*printf("ch=%c\nnum=%d\navg=%f\ndblval=%f",ch,num,avg,dblval);*/
getch( );
}

Previous
Next

Compiling and Running your program

So far we have discussed about C, features of C, structure of a C program, library function printf( ) and how to program in C language etc. So now we are moving into more detailed explanation. You can use Turbo C or Borland C compilers for your program. Both are providing you a way to code your program, compile it and execute the program. If you are using 'Borland C' then linking header files is necessary. Turbo C won't warn if you are not linked header files into your program. So now we can see a sample program as a step to explore the power of C language. So open your C editor (Turbo or Borland) and start coding.

Learning by Example I

Qn: A Program to print your Name on the Screen
/*Program to print name on the screen */
#include<stdio.h>
main( )
{
printf("Your Name");
}

So you've done! Now you can compile your program to convert it into object code. For that select Compile - > Compile; then a compiling box will be displayed on the screen showing file name, lines compiled, number of warnings & errors if any in the program. If your program has successfully compiled then you can turn into execute or run the program. If there are any errors in the program, number of errors will be displayed on the compiling window and when you hit 'Enter' key, details of the errors listed in the message window; select the error message using up/down arrow keys and hit 'Enter' key to locate the error instruction, correct the errors and compile it.

For executing the program select Run->Run from the menu. You r editor will suddenly blink and return back to the editor window where you've coded your program. So your program has been executed, you can view the output of the program by pressing Alt+F5 keys. You can now see 'Your name' (whatever given in printf) printed on the screen. Ok, now lets have a look at our code:

We have written a comment line on the first line. In link section we linked header file as we've used printf( ) function in our program. As we discussed already, printf( ) is a function which means which is already coded and stored in the C library. Instructions for printf( ) function is written in a header files ( having extension .h) 'stdio.h'. stdio means Standard Input and Output. So if you are using any of the library function in your program, you should link appropriate header file into your program.

If you again run your program, output will be displayed on the screen with the old program output. So you may be want to print your outputs on a clean window, you can clear your screen before you are printing any output. For this you can use a library function 'clrscr( )'. Just put this function in your program where you want to clear your screen. clrscr( ) function's header file is , so do link this header file into your program. In our program you can insert clrscr( ) just before that printf( ) function; Run your program again and you will see your name printed in a cleared screen.

It may be disturbing everytime pressing Alt+F5 keys to view the output. Why we are redirected to the editor window after program run? Because process control executes each line of instructions and when comes out of the closing brace, program terminates and get back to the coding window. You can pause the program termination by just putting getch( ) function just before the closing brace. getch( ) is actually a function which accepts a value from the keyboard. So if you insert a getch( ) function as your last instruction, the program control will wait for a value to be inputted to the getch( ); so till entering a value, you can view your program outputs on the screen. By this you can avoid the usage of hitting Alt+F5.

So from the above modification our program will be look as follows:

/*Program to print name on the screen */
#include<stdio.h>
#include<conio.h>
main( )
{
clrscr( );
printf("Your Name");
getch( );
}

Previous
Next

C PROGRAM BASICS

main( )
{ /* This is the beginning */
printf("Welcome to the world of C");
}

The first line informs the system that the name of the program is main( ) and the execution begins at this line. The main( ) is a special function used by the C system to tell the computer where the program starts. Every C program must have exactly one main( ) function. If we use more than one main( ), the compiler cannot tell wich one marks the begining of program. The empty parenthesis immediately following the main indicates that the function main has no arguments. The opening brace { in the second line marks the begining of the function main( ) and the closing brace } in the last line indicates the end of the function. All the statements between these two statements form the function body. The function body contains a set of instructions to perform a given task.

In this case the function body contains two statements out of which the printf line is an executable statement. The lines begin with /* and ends with */ is known as 'comment line'. Comment lines are non-executable statements and therefore anything between /* and */ is ignored by the compiler.

printf is a predefined standard function for printing output. Predefined means it is a function that has already been written and linked together with our program at the time of linking. The printf function causes every thing between the starting and ending quotation marks to be printed out.

printf("Hello Guest\nWelcome to Program Logic");

The argument in the printf contains a combination of two characters '\n'. This combination is collectively called the 'new line character'. It causes the computer to go to the next line. Hence the above printf statement will output :

Hello Guest
Welcome to Program Logic

Basic Structure of a C Program

Documentation section
Link section (Header File inclusion section)
Definition section
Global declaration section
main ( ) function section
{
Declaration part
Execution part
}
Subroutines

The documentation section consist of a set of comment lines giving the name of the program and other details.

The link section provides instruction to link functions from system library.

The definition section defines all symbolic constants.

There are some variables that are used in more than one function, such variables are called global variables and are declared in the global declaration section outside of all the functions.

Every C program must have one main( ) function. This section contains two parts, declaration part and execution part. Declaration part declares all the variables used in the executable part. These two parts must appear between the opening and the closing braces. The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main( ) is the logical end of the program.

The subroutine section contains all the user defined function that are called in the main( ) function.

Previous
Next

OVERVIEW OF C

The programming language C was an offspring of the Basic Combined Programming Language (BCPL) called 'B'. B language was modified by Dennies Ritchie and was implemented at AT & T Bell Laboratories in 1972. The new language was named C. Since it was developed along with the Unix Operating System it is strongly associated with Unix. This OS was coded almost entirely in C.

The increasing popularity of C is probably due to its many desirable qualities. It is a language whose rich set of built in functions and operators can be used to write any complex program. The C compilers combines the capabilities of an assembly language with the features of a high level language and therefore it is well suited for writing both system software and business packages.

Programs written in C are efficient and fast this is due to its variety of data types and powerful operators. There are only 32 keywords and a strength lies in its built in function. C is highly portable. This means that C programs written for one computer can be run on another with little or no modification.

Another important feature of C is its ability to extend itself. A 'C ' program is basically a collection of function that are supported by the C library. We continuously add our own functions to the C library.

Previous
Next

COMPUTER PROGRAM

A computer program is a set of instructions to be followed by the computer. These instructions are the steps to be followed sequentially in order to achieve the result.

CHARACTERISTICS OF A GOOD PROGRAM

1. Accuracy : The program must do what it is supposed to do and meet the critical laid down in its specification.

2. Reliability : The program must always do what it is supposed to do and never crash.

3. Efficiency : The program must use the available store space and resources in such a way that the system speed is not waste.

4. Robustness : The program should cope with invalid data without stopping with no indication to the cause and without creating errors.

5. Usability : The program must be easy to use and well documented.

6. Maintainability : The program must be easy to amend having good structuring and documentation.

7. Readability : The code in the program must be well laid out and explained with comments.

8. Portability : It should be seen that the program is easy to transfer to other machines as well.

TYPES OF DATA

Constants : This is the data which is predetermined before a program is used. Values remain unchanged during the execution of a program.

Variables : Here the data may change or be assigned different values as the program runs.

OP CODE & OPERAND

A Machine language instruction normally has a two part format. The first part is an instruction , is the operation code, that tells the computer what function to perform, and the second one is operand, that tells the computer where to find or store the data or other instructions that are to be manipulated.

All programming languages has its own syntax, rules or grammar. So we should follow the syntax of the programming language in which we are programming. Breaking any of these will cause bugs or Errors in our program.

Logic, Run time & Syntax Errors

Syntax Errors arises due to the lack of knowledge in the programming language syntax. It arises because of the error in the syntax of programming instructions. Programs having syntax errors cannot be compiled or executed. Compilers will show syntax errors in the program specifying the line number and information about the error.

Logic Errors are another kind of error and causes because of the faulty or bad logic of the programmer. It may result in the programs functionality and often produce undesired output. For example instead of adding two numbers like a+b, programmer coded like a-b; Programmer used a-b instead of instruction a+b. This type of errors cannot be detected by compilers because instructions may be valid (both a+b and a-b are valid instructions) but it has some logic errors and the program will results undesired or unpredictable result.

Run time Errors are errors occur when a program executes. Compilers cannot predict the run time errors in the program. Its arises only when a program runs. eg. Division by Zero Error.

Previous
Next

ALGORITHMS

An Algorithm is a sequence of finite instructions or steps used to complete a task or a problem. There is no generally accepted rule for algorithms, its a sequence of steps carried out to complete a task. But if we are considering computer programs, we need somewhat a standardized format for Algorithms, that means Algorithms are an aid for programs, so there should be a definite start and an end for the algorithm.

Algorithms can be expressed in different notations, including natural languages, Pseudo codes, flow charts etc. Flow Charts and Pseudo Codes are widely used for Technical and Complex algorithms. and are used in the structured program designs. Natural language expressions cannot be used as its may make ambiguity.

FLOWCHARTS

 A Flowchart is a pictorial representation of an Algorithm or a Process, showing each steps in various kinds of boxes in order, and connecting these boxes with arrows.

Flowchart is the representation of the programming steps. It shows the various steps in sequence which are needed to run the program. Flowchart uses boxes of different shapes to denote different types of instructions. The instructions are written within these boxes using clear and concise statements. These boxes are connected by solid lines having arrow marks to indicate the flow of operations that is the exact sequence in which the instructions are to be executed. Flowchart helps in detecting errors in the program logic also. Once the flowchart is ready, the programmer can concentrate only on coding the operations in each box of the flowchart in terms of the statements of the programming language. This usually ensure an error-free program.

Flow Chart Symbols


Symbols

A typical flowchart from older Computer Science textbooks may have the following kinds of symbols:
Start and end symbols
Represented as lozenges, ovals or rounded rectangles, usually containing the word "Start" or "End", or another phrase signaling the start or end of a process, such as "submit enquiry" or "receive product".
Arrows
Showing what's called "flow of control" in computer science. An arrow coming from one symbol and ending at another symbol represents that control passes to the symbol the arrow points to.
Processing steps
Represented as rectangles. Examples: "Add 1 to X"; "replace identified part"; "save changes" or similar.
Input/Output
Represented as a parallelogram. Examples: Get X from the user; display X.
Conditional or decision
Represented as a diamond (rhombus). These typically contain a Yes/No question or True/False test. This symbol is unique in that it has two arrows coming out of it, usually from the bottom point and right point, one corresponding to Yes or True, and one corresponding to No or False. The arrows should always be labeled. More than two arrows can be used, but this is normally a clear indicator that a complex decision is being taken, in which case it may need to be broken-down further, or replaced with the "pre-defined process" symbol.

Connectors
There are instances when a flowchart becomes too large to fit in a single page and the use of flow lines becomes impossible. In such situations awe use the connector symbols as as substitute for flow lines.
Sample Flowchart to find the sum of first 50 natural numbers


Finding Largest among three input numbers

ADVANTAGES OF FLOWCHART

1. Conveys better meaning : Since a flowchart is a pictorial representation of a program, it is easier for a programmer to understand and explain the logic of the program to some other programmer.

2. Effective joining of a part of a system : A group of programmers are normally associated with the design of large software system. Each programmer is responsible for designing only a part of the entire system. If each programmers draws a flowchart for his part of design, the flowcharts of all the programmers can be placed together to visualize the overall system design.

3. Efficient Coding :
Once a flowchart is ready, programmers find it very easy to write the concerned program because the flowchart acts as a road map for them.

4. Systematic Debugging : A flowchart is very helpful in detecting, locating and removing mistakes in a program in a systematic manner.

5. Systematic Testing : Testing is the process of confirming whether a program will successfully do all the jobs for which it has been designed under the specified constraints. For testing a program different sets of data are fed as input to that program to test the different parts in the program logic.

DRAWBACKS OF FLOWCHARTS

  1. Flowcharts are something new and strange to work with for beginners.
  2. When modifications are made in the original program corresponding changes must be made in the flowcharts of the program in the documentation.
  3. Flowcharts may not reveal significant steps to be followed in actual coding.
  4. Flowcharts are often cumbersome to use and costly to produce.
  5. Flowchart don't constitutes a programming language. They are person to person means of communication, not person to computer. 

PSEUDO CODE [STRUCTURED ENGLISH]

PSEUDO CODE is another program analysis tool that is used for planning program logic 'pseudo' means imitation and code refers to the instructions written in a programming language. Pseudo code is therefore an imitation of actual computer instructions. These pseudo instructions are phrases written in ordinary natural language.

Instead of using symbols to describe the logic steps of a program as in a flow charting, pseudo code uses a structure that resembles computer instructions. Because it emphasizes the design of the program. Pseudo code is also called Program Design Language [ PDL]. Pseudo code is made up of the following basic logic structures.
  1. Sequence
  2. Selection [if....then....else, if...then]
  3. Iteration [ do...while,Repeat...until]
A sequence structure is a single step or action included in a process. It does not depend n the existence of any condition and when encountered it is always executed. Eg: To purchase a book in a book store you would probably follow a procedure similar to the one that follows

a. Pick out a desirable book
b. Take the book to the checkout counter
c. Pay for the book
d. Obtain receipt
e. Leave the store

Selection logic also known as decision logic, is used for making decisions. It is used for selecting the proper path out of the two or more alternative paths in the program logic. Selection logic is depicted as either an if.. then... else or if... then structure.

Iteration logic is used when one or more instructions may be executed several times depending on some conditions. It used two structures called the Do while and repeat until. Both these structures are used for looping.

Previous
Next

INTRODUCTION TO COMPUTER PROGRAMMING

A computer program is a collection of instructions that describe a task, or set of tasks, to be carried out by a computer. We can instruct a human being to do a particular task by speaking up or through any other media. As computers are bare machines we have to instruct them using some languages that are understood by the computer. For this purpose, communicating with the computer for instructing them to do a particular task we use special languages called 'Programming Languages'. The task of instructing the machines using programming languages is called 'Programming". Those persons who deals with the programming is known as 'Computer Programmers'.

We can classify the programming languages into two broad categories.
  1. Low Level Languages
  2. High Level Languages
1. Low Level Languages : Low Level languages are of two types :-
  • Machine Languages and  
  • Assembly Languages.
Machine Language: As computers are electronic devices, they internally represents all data as binary 1 and 0. a binary 0 may be used to represent power off or low voltage whereas 1 may represent high voltage or power on state. Using machine language, programmer programs in computer's own language, that is binary language. A programmer programming in machine language deals with binary 0's and 1's. In machine all instructions are represented as combination's of binary 0's and 1's. The memory addresses for the data also be specified in the program. Hence an instruction such as a+b, should be in binary language, there may be corresponding binary combination's for each operator and operands, addresses for operands should be specified in the program. Hence programming in machine language is not an easy task. The limitation of machine language programming are : -
  • Difficult to program
  • Difficult to modify
  • Error prone
  • Machine Dependent (No Portability) : Programs written in machine language are not portable, which means we cannot copy it into another machine and use.
The main advantage of machine language is that, programs written in machine language can be fastly executed, because there's no need to convert the program into machine's code, its already in binary language.

Assembly Language: Assembly Language is also known as Symbolic language. In assembly language, we can program using symbols and alphabets. The following are the limitations of Assembly Language : -
  • Machine Dependent.
  • Deep knowledge in hardware required by the programmer.
Assembly language programs can be written using symbols and digits, as computer internally represent all data in binary form, an assembly program must be translated into equivalent machine code before executing the program. This translation is done by a translation program known as Assembler.

2. High Level Languages are user friendly languages; using which anybody having a little knowledge of programming language can program without bothering about internal structure or memory addresses. Examples of high level languages are: COBOL, BASIC, C, C++, JAVA, PYTHON etc. Programs written in high level languages can be easily ported to any other system with a little or no modification.

Programs written in high level languages such as C, C++ etc. are cannot directly understand by the computer, so they have to translated into machine code, and this translation is done by Compilers or Interpreters.

Next

Design by The Blogger Templates The Blog Full of Games

© CourseZone
2008 - 2010 All Rights Reserved.