Showing posts with label learn programming in 45 days. Show all posts
Showing posts with label learn programming in 45 days. Show all posts

Use of Operators

Sunday, July 1, 2012
Here are sample programs which will further explain the use of operators in programming.

Problem Statement:

Write a program that takes a four digits integer from user and shows the digits on the screen separately i.e. if user enters 7531, it displays 1,3,5,7 separately.

Solution:

Let’s first analyze the problem and find out the way how to program it.

Analysis:
First of all, we will sort the problem and find out how we can find digits of an integer. We know that when we divide a number by 10, we get the last digit of the number as remainder. For example when we divide 2415 by 10 we get 5 as remainder. Similarly 3476 divided by 10 gives the remainder 6. We will use this logic in our problem to get the digits of the number. First of all, we declare two variables for storing number and the digit. Let’s say that we have a number 1234 to show its digits separately. In our program we will use modulus operator ( % ) to get the remainder. So we get the first digit of the number 1234 by taking its modulus with 10 (i.e. 1234 % 10). This will give us the digit 4. We will show this digit on the screen by using cout statement. After this we have to find the next digit. For this we will divide the number by 10 to remove its last digit. Here for example the answer of 1234 divided by 10 is 123.4, we need only three digits and not the decimal part. In C we know that the integer division truncates the decimal part to give the result in whole number only. We will use integer division in our program and declare our variable for storing the number as int data type. We will divide the number 1234 by 10 (i.e. 1234 / 10). Thus we will get the number with remaining three digits i.e. 123. Here is a point to be noted that how can we deal with this new number (123)? There are two ways, one is that we declare a new variable of type int and assign the value of this new number to it. In this way we have to declare more variables that means more memory will be used. The second way is to reuse the same variable (where number was already stored). As we have seen earlier that we can reassign values to variables like in the statement x = x + 1, which means, add 1 to the value of x and assign this resultant value again to x. In this way we are reusing the variable x. We will do the same but use the division operator instead of addition operator according to our need. For this purpose we will write number = number / 10. After this statement we have value 123 in the variable number.

Again we will get the remainder of this number with the use of modulus operator, dividing the number by 10 (i.e. 123 % 10). Now we will get 3 and display it on the screen. To get the new number with two digits, divide the number by 10. Once again, we get the next digit of the number (i.e. 12) by using the modulus operator with 10, get the digit 2 and display it on the screen. Again get the new number by dividing it by 10 (i.e. 1). We can show it directly, as it is the last digit, or take remainder by using modulus operator with 10. In this way, we get all the digits of the number.
Now let’s write the program in C by following the analysis we have made. The complete C program for the above problem is given below. It is easy to understand as we are already familiar with the statements used in it.


The output of the program will be as following.

Problem Statement:
Write a program that takes radius of a circle from the user and calculates the diameter, circumference and area of the circle and display the result.

Solution:
In this problem we take the input (radius of a circle) from the user. So that we can use cin statement to prompt the user to enter the radius of a circle. We store this radius in a variable. We also need other variables to store diameter, circumference and area of the circle. To obtain the correct result, we declare these variables of type float, instead of int data type, as we know that the int data type stores the whole numbers only. Here in our problem the area or circumference of the circle can be in decimal values. After getting the radius we use the formulae to find the diameter, circumference and area of the circle and then display these results on the screen.

The solution of this program in coding form is given below.

A sample output of the above program is given below.

Tips:
  • Use descriptive names for variables
  • Indent the code for better readability and understanding
  • Use parenthesis for clarity and to force the order of evaluation in an expression
  • Reuse the variables for better usage of memory
  • Take care of division by zero
  • Analyze the problem properly, and then start coding (i.e. first think and then write)

For previous lesson click here: Examples of Expressions
For next lesson click here: Conditional Statements


the easiest way to learn programming
introduction to programming
Use of Operators

do-while Statement

Saturday, June 16, 2012
We have seen that there may be certain situations when the body of while loop does not execute even a single time. This occurs when the condition in while is false. In while loop, the condition is tested first and the statements in the body are executed only when this condition is true. If the condition is false, then the control goes directly to the statement after the closed brace of the while loop. So we can say that in while structure, the loop can execute zero or more times. There may be situations where we may need that some task must be performed at least once.
For example, a computer program has a character stored from a-z. It gives to user five chances or tries to guess the character. In this case, the task of guessing the character must be performed at least once. To ensure that a block of statements is executed at least once, C provides a do-while structure. The syntax of do-while structure is as under:



Here we see that the condition is tested after executing the statements of the loop body. Thus, the loop body is executed at least once and then the condition in do while statement is tested. If it is true, the execution of the loop body is repeated. In case, it proves otherwise (i.e. false), then the control goes to the statement next to the do while statement. This structure describes ‘execute the statements enclosed in braces in do clause when the condition in while clause is true.
Broadly speaking, in while loop, the condition is tested at the beginning of the loop before the body of the loop is performed. Whereas in do-while loop, the condition is tested after the loop body is performed. Therefore, in do-while loop, the body of the loop is executed at least once.

The flow chart of do-while structure is as follow:


Example

Let’s consider the example of guessing a character. We have a character in the program to be guessed by the user. Let’s call it ‘z’. The program allows five tries (chances) to the user to guess the character. We declare a variable tryNum to store the number of tries. The program prompts the user to enter a character for guessing. We store this character in a variable c.
We declare the variable c of type char. The data type char is used to store a single character. We assign a character to a variable of char type by putting the character in single quotes. Thus the assignment statement to assign a value to a char variable will be as c = ‘a’. Note that there should be a single character in single quotes. The statement like c = ‘gh’ will be a syntax error.

Here we use the do-while construct. In the do clause we prompt the user to enter a character. After getting character in variable c from user, we compare it with our character i.e ‘z’. We use if\else structure for this comparison. If the character is the same as ours then we display a message to congratulate the user else we add 1 to tryNum variable. And then in while clause, we test the condition whether tryNum is less than or equal to 5 (tryNum <= 5). If this condition is true, then the body of the do clause is repeated again. We do this only when the condition (tryNum <= 5) remains true. If it is otherwise, the control goes to the first statement after the do-while loop. If guess is matched in first or second try, then we should exit the loop. We know that the loop is terminated when the condition tryNum <= 5 becomes false, so we assign a value which is greater than 5 to tryNum after displaying the message. Now the condition in the while statement is checked. It proves false (as tryNum is greater than 5). So the control goes out of the loop. First look here the flow chart for the program.

The code of the program is given below.


There is an elegant way to exit the loop when the correct number is guessed. We change the condition in while statement to a compound condition. This condition will check whether the number of tries is less than or equal to 5 and the variable c is not equal to ‘z’. So we will write the while clause as while (tryNum <= 5 && c != ‘z’ ); Thus when a single condition in this compound condition becomes false, then the control will exit the loop. Thus we need not to assign a value greater than 5 to variable tryNum. Thus the code of the program will be as:

The output of the program is given below.


Here is another out put of the same program


For previous lesson click here: while exercises
For next lesson click here: coming soon


the easiest way to learn programming
introduction to programming
do-while Statement

while exercises

Exercise
1) Calculate the sum of odd integers for a given upper limit. Also draw flow chart of the program.
2) Calculate the sum of even and odd integers separately for a given upper limit using only one loop structure. Also draw flow chart of the program.

tips:

  • Always use the self explanatory variable names
  • Practice a lot. Practice makes a man perfect
  • While loop may execute zero or more time
  • Make sure that loop test (condition) has an adequate exit.

For previous lesson click here: While Sample Program
For next lesson click here: do-while Statement


the easiest way to learn programming
introduction to programming
while exercises

While Sample Program

Problem statement:
Calculate the factorial of a given number.

Solution:
The factorial of a number N is defined as:


By looking at the problem, we can see that there is a repetition of multiplication of numbers. A loop is needed to write a program to solve a factorial of a number. Let's think in terms of writing a generic program to calculate the factorial so that we can get the factorial of any number. We have to multiply the number with the next decremented number until the number becomes 1. So the value of number will decrease by 1 in each repetition.
Here is the flow chart for the factorial.



Here is the code of the program.



The output of the program is as follows:


Exercise
1) Calculate the sum of odd integers for a given upper limit. Also draw flow chart of the program.
2) Calculate the sum of even and odd integers separately for a given upper limit using only one loop structure. Also draw flow chart of the program.

tips:
  • Always use the self explanatory variable names
  • Practice a lot. Practice makes a man perfect
  • While loop may execute zero or more time
  • Make sure that loop test (condition) has an adequate exit.

For previous lesson click here: While Flow Chart
For next lesson click here: while exercises


the easiest way to learn programming
introduction to programming
While Sample Program

While Flow Chart

The basic structure of while loop in structured flow chart is:


At first, we will draw a rectangle and write while in it. Then draw a line to its right and use the decision symbol i.e. diamond diagram. Write the loop condition in the diamond and draw a line down to diamond which represents the flow when the decision is true. All the repeated processes are drawn here using rectangles. Then a line is drawn from the last process going back to the while and decision connection line. We have a line on the right side of diamond which is the exit of while loop. The while loop terminates, when the loop condition evaluates to false and the control gets out of while structure.

So far, we have been drawing flow charts after coding the program but actually we have to draw the flow chart first and then start coding.

For previous lesson click here: Properties of while loop
For next lesson click here: While Sample Program


the easiest way to learn programming
introduction to programming
While Flow Chart

Properties of while loop

In the above example, if the user enters 0, as the value for upper limit. In the while condition we test (number <= upperLimit) i.e. number is less than or equal to upperLimit ( 0 ), this test return false. The control of the program will go to the next statement after the while block. The statements in while structure will not be executed even for a single time. So the property of while loop is that it may execute zero or more time. The while loop is terminated, when the condition is tested as false. Make sure that the loop test has an adequate exit. Always use braces for the loop structure. If you forget to put the braces, only one statement after the while statement is considered in the while block. Infinite Loop: Consider the condition in the while structure that is (number <= upperLimit) and in the while block the value of number is changing (number = number + 1) to ensure that the condition is tested again next time. If it is true, the while block is executed and so on. So in the while block statements, the variable used in condition must change its value so that we have some definite number of repetitions. What will happen if we do not write the statement number = number + 1; in our program? The value of number will not change, so the condition in the while loop will be true always and the loop will be executed forever. Such loops in which the condition is always true are known as infinite loops as there are infinite repetitions in it. For previous lesson click here: sum of even numbers with while
For next lesson click here: While Flow Chart


the easiest way to learn programming
introduction to programming
Properties of while loop

sum of even numbers with while

Problem statement:
Calculate the sum of even numbers for a given upper limit of integers.

Solution:
We analyze the problem and know that while statement will be used. We need to sum even numbers only. How can we decide that a number is even or not? We know that the number that is divisible by 2 is an even number. How can we do this in C language? We can say that if a number is divisible by 2, it means its remainder is zero, when divided by 2. To get a remainder we can use C’s modulus operator i.e. %. We can say that for a number if the expression (number % 2) results in zero, the number is even. Putting this in a conditional statement:


The above conditional statement becomes true, when the number is even and false when the number is odd (A number is either even or odd).

The complete code of the program is as follows:



The output of the program is:


Suppose if we don’t have modulus operator in the C language. Is there any other way to find out the even numbers? We know that in C integer division gives the integer result and the decimal portion is truncated. So the expression (2 * (number / 2)) gives the number as a result, if the number is even only. So we can change our condition in if statement as:




So far, we have been drawing flow charts after coding the program but actually we have to draw the flow chart first and then start coding.


Properties of while loop:

In the above example, if the user enters 0, as the value for upper limit. In the while condition we test (number <= upperLimit) i.e. number is less than or equal to upperLimit ( 0 ), this test return false. The control of the program will go to the next statement after the while block. The statements in while structure will not be executed even for a single time. So the property of while loop is that it may execute zero or more time. The while loop is terminated, when the condition is tested as false. Make sure that the loop test has an adequate exit. Always use braces for the loop structure. If you forget to put the braces, only one statement after the while statement is considered in the while block. Infinite Loop: Consider the condition in the while structure that is (number <= upperLimit) and in the while block the value of number is changing (number = number + 1) to ensure that the condition is tested again next time. If it is true, the while block is executed and so on. So in the while block statements, the variable used in condition must change its value so that we have some definite number of repetitions. What will happen if we do not write the statement number = number + 1; in our program? The value of number will not change, so the condition in the while loop will be true always and the loop will be executed forever. Such loops in which the condition is always true are known as infinite loops as there are infinite repetitions in it. For previous lesson click here: While Sample Program
For next lesson click here: Properties of while loop


the easiest way to learn programming
introduction to programming
sum of even numbers with while

While Sample Program

To calculate the sum of 2000 integers, we will change the program (i.e. the while condition) in the editor and compile it and run it again. If we need to calculate the sum of first 5000 integers, we will change the program again in the editor and compile and run it again. We are doing this work again in a loop. Change the program in the editor, compile, execute it, again change the program, compile and execute it and so on. Are we doing this in a loop? We can make our program more intelligent so that we don’t need to change the condition every time. We can modify the condition as:


where upperLimit is a variable of data type int. When the value of upperLimit is 1000, the program will calculate the sum of first 1000 integers. When the value of upperLimit is 5000, the program will calculate the sum of first 5000 integers. Now we can make it re-usable and more effective by requesting the user to enter the value for upper limit:


We don’t have to change our program every time when the limit changes. For the sum of integers, this program has become generic. We can calculate the sum of any number of integers without changing the program. To make the display statement more understandable, we can change our cout statement as:



Try to write the program.


For previous lesson click here: Repetition Structure (Loop)
For next lesson click here: sum of even numbers with while


the easiest way to learn programming
introduction to programming
While Sample Program

if/else Sample Program

Problem Statement
A shopkeeper announces a package for customers that he will give 10 % discount on all bills and if a bill amount is greater than 5000 then a discount of 15 %. Write a C program which takes amount of the bill from user and calculates the payable amount by applying the above discount criteria and display it on the screen.

Solution
In this problem we are going to make decision on the basis of the bill amount, so we will be using if statement. We declare three variables amount, discount and netPayable and initialize them. Next we prompt the user to enter the amount of the bill. After this we implement the if statement to test the amount entered by the user. As we see in the problem statement that if the amount is greater than 5000 then the discount rate is 15 % otherwise (i.e. the amount is less than or equal to 5000) the discount rate is 10 %. So we check the amount in if statement. If it is greater than 5000 then the condition is true then the if block is executed otherwise if amount is not greater than 5000 then the else block is executed.
The analysis and the flow of the program is shown by the following flow chart.


The complete program code is given below :


In the program we declared the variables as double. We do this to get the correct results (results may be in decimal points) of the calculations. Look at the statement which calculates the discount. The statement is
discount = amount * (15.0 / 100) ;
Here in the above statement we write 15.0 instead of 15. If we write here 15 then the division 15 / 100 will be evaluated as integer division and the result of division (0.15) will be truncated and we get 0 and this will result the whole calculation to zero. So it is necessary to write at least one operand in decimal form to get the correct result by division and we should also declare the variables as float or double. We do the same in the line discount = amount * (10.0 / 100);

A sample execution of the program is given below



Tips:
  • Always put the braces in an if/else structure
  • Type the beginning and ending braces before starting typing inside them
  • Indent both body statements of an if and else structure
  • Be careful while combining the conditions with logical operators
  • Use if/else structure instead of a number of single selection if statements

For previous lesson click here: Logical Operators
For next lesson click here: Repetition Structure (Loop)


the easiest way to learn programming
introduction to programming
if/else Sample Program

Logical Operators

There are many occasions when we face complex conditions to make a decision. This means that a decision depends upon more than one condition in different ways. Here we combine the conditions with AND or OR. For example, a boy can be selected in basket ball team only if he is more than 18 years old and has a height of 6 feet. In this statement a boy who wants to be selected in the basket ball team must have both the conditions fulfilled. This means that AND forces both the conditions to be true. Similarly we say that a person can be admitted to the university if he has a BCS degree OR BSC degree. In this statement, it is clear that a person will be admitted to the university if he has any one of the two degrees.
In programming we use logical operators ( && and || ) for AND and OR respectively with relational operators. These are binary operators and take two operands. These operators use logical expressions as operands, which return TRUE or FALSE.
The following table (called truth table) can be used to get the result of the && operator and || operator with possible values of their operands. It is used to explain the result obtained by the && and || operators.

Expression 1Expression 2Expression 1 && Expression 2Expression 1 || Expression 2
TrueFalsefalseTrue
TrueTruetrueTrue
FalseFalsefalseFalse
FalseTruefalseTrue

The && operator has a higher precedence than the || operator. Both operators associate from left to right. An expressions containing && or || is evaluated only until truth or falsehood is known. Thus evaluation of the expression (age > 18) && (height > 6) will stop immediately if age > 18 is false (i.e. the entire expression is false) and continue if age > 18 is true (i.e. the entire expression could still be true if the condition height > 6 is true ).

There is another logical operator that is called logical negation. The sign ! is used for this operator. This operand enables a programmer to ‘reverse’ the meaning of a condition. This is a unary operator that has only a single condition as an operand. The operator ! is placed before a condition. If the original condition (without the ! operator) is false then the ! operator before it converts it to true and the statements attached to this are executed.
Look at the following expression



Here the cout statement will be executed if the original condition (age > 18) is false because the ! operator before it reverses this false to true.

The truth table for the logical negation operator ( ! ) is given below.
Expression! Expression
truefalse
falsetrue

For previous lesson click here: If/else Structure
For next lesson click here: if/else Sample Program


the easiest way to learn programming
introduction to programming
Logical Operators

If/else Structure

We have seen that the if structure executes its block of statement(s) only when the condition is true, otherwise the statements are skipped. The if/else structure allows the programmer to specify that a different block of statement(s) is to be executed when the condition is false. The structure of if/else selection is as follows.



Thus using this structure we can write the construct of our program as:



In this construct, the program checks the condition in if statement .If the condition is true, then the line "Amer is greater than Amara" is printed. Otherwise (if condition is not true), the statement related to else is executed and the message "Amer is younger than Amara" is printed. Here in if/else structure an important thing is that the else part is executed for all the cases (conditions) other than the case which is stated in the if condition.
And in the comparison, we know that there are three conditions i.e. first value is greater than the second value, first value is less than the second value and first value is equal to the second value. Here in the above program construct the else part competes the greater than conditions and covers both less than and equal to conditions.
Thus in the above program construct, the message "Amer is younger than Amara" is displayed even if Amer’s age is the same as Amara’s age. This is logically incorrect and so to make this correct, we should display the message "Amer is younger than or is of the same age as Amara". Now this statement describes both the cases other than the one ‘Amer is greater than Amara'.
The use of else saves us from writing different if statements to compare different conditions, in this way it cover the range of checks to complete the comparison.
If we want to state the condition "Amer is greater than or is of the same age as Amara’s" then we use the greater than or equal to operator (i.e. >=) in the if statement and less than operator ( < ) in the else statement to complete the comparison. It is very important to check all the conditions while making decisions for good, complete and logical results. Make sure that all cases are covered and there is no such case in which the program does not respond. The flow chart of our program with if/else structure will be as follow.



For previous lesson click here: IF Sample Program 1
For next lesson click here: Logical Operators


the easiest way to learn programming
introduction to programming
If/else Structure

IF Sample Program 1

Now let’s see the usage of relational operators by an example. There are two students Amer and Amara. We take their ages from the user, compare them and tell who is older?
As there are two students to be compared in terms of age, we need to declare two variables to store their ages. We declare two variables AmerAge and AmaraAge of type int. The variable names are one continuous word as we can’t use spaces in a variable name.
Here is an important point about variables declaration. We should assign an initial value (preferably 0 for integers) to variables when we declare them. This is called initialization of variables.
We can do this in one line while declaring a variable like int x = 0; This statement will declare a variable of name x with data type int and will assign a value 0 to this variable. Initializing a variable in this way is just a matter of style. You can initialize a variable on a separate line after declaring it. It is a good programming practice to initialize a variable.
Now we prompt the user to enter Amer’s age and store it into variable AmerAge. Then similarly we get Amara’s age from the user in the variable AmaraAge.
While comparing the ages, we will use the if statement to see whether Amer’s age is greater than Amara’s. We will use > (greater than) operator to compare the ages. This can be written as if ( AmerAge > AmaraAge) .
With this if statement, we write the statement cout << "Amer is greater than Amara" ; It’s a simple one line test i.e. ‘if Amer’s age is greater than Amara's’, then display the message ‘Amer is older than Amara’. Flow chart of the sample program:


The complete code of the program is given below.



In our program, we write a single statement with the if condition. This statement executes if the condition is true. If we want to execute more than one statements, then we have to enclose all these statements in curly brackets { }. This comprises a block of statements which will execute depending upon the condition. This block may contain a single statement just like in our problem. So we can write the if statement as follow.



A sample execution of the program results the following output.



Now think what happens if the condition in the if statement is not true i.e. Amer’s age is not greater than Amara’s. In this case, if the user enters Amer’s age less than Amara’s, then our program does nothing. So to check this condition, another if statement after the first if statement is required. Then our program will be as:



Now our program decides properly about the ages entered by the user.
After getting ages from the user, the if statements are tested and if statement will be executed if the condition evaluates to true.

For previous lesson click here: Flow Charting
For next lesson click here: If/else Structure


the easiest way to learn programming
introduction to programming
IF Sample Program 1

Flow Charting

There are different techniques that are used to analyze and design a program. We will use the flow chart technique. A flow chart is a pictorial representation of a program. There are labeled geometrical symbols, together with the arrows connecting one symbol with other.
A flow chart helps in correctly designing the program by visually showing the sequence of instructions to be executed. A programmer can trace and rectify the logical errors by first drawing a flow chart and then simulating it.

The flow chart for the if structure is shown in the figure below.



For previous lesson click here: Conditional Statements
For next lesson click here: IF Sample Program 1


the easiest way to learn programming
introduction to programming
Flow Charting

Examples of Expressions

Tuesday, May 29, 2012
We have already seen the precedence of arithmetic operators. We have expressions for different calculations in algebraic form, and in our programs we write them in the form of C statements. Let’s discuss some more examples to get a better understanding.

We know about the quadratic equation in algebra, that is y = ax2 + bx + c. The quadratic equation in C will be written as y = a * x * x + b * x + c. In C, it is not an equation but an assignment statement. We can use parentheses in this statement, this will make the expression statement easy to read and understand. Thus we can rewrite it as y = a * (x * x) + (b * y) + c.

Note that we have no power operator in C, just use * to multiply the same value.

Here is another expression in algebra: x = ax + by + cz2. In C the above expression will be as:

x = a * x + b * y + c * z * z

The * operator will be evaluated before the + operator. We can rewrite the above statement with the use of parentheses. The same expressions can be written as:

x = (a * x) + (b * y) + c * ( z * z)

Lets have an other expression in algebra as x = a(x + b(y + cz2)). The parentheses in this equation forces the order of evaluation. This expression will be written in C as:

x = a * (x + b * (y + c * z * z))

While writing expressions in C we should keep in mind the precedence of the operators and the order of evaluation of the expressions (expressions are evaluated from left to right). Parentheses are used in complicated expressions. In algebra, there may be curly brackets { } and square brackets [ ] in an expression but in C we have only parentheses ( ). Using parentheses, we can make a complex expression easy to read and understand and can force the order of evaluation. We have to be very careful while using parentheses, as parentheses at wrong place can cause an incorrect result. For example a statement x = 2 + 4 * 3 results x = 14. As * operator is of higher precedence, 4 * 3 is evaluated first and then result 12 is added to 4 which gives the result 14. We can rewrite this statement, with the use of parentheses to show it clearly, that multiplication is performed first. Thus we can write it as x = 2 + (4 * 3). But the same statement with different parentheses like x = (2 + 4) * 3 will give the result 18, so we have to be careful while using parenthesis and the evaluation order of the expression.

Similarly the equation (b^2 – 4ac)/2a can be written as ( b * b – 4 * a * c) / ( 2 * a ). The same statement without using parentheses will be as b * b – 4 * a * c / 2 * a. This is wrong as it evaluates to b^2 – 4ac/2a (i.e. 4ac is divided by 2a instead of (b^2-4ac)).

For previous lesson click here: Sample Program
For next lesson click here: Use of Operators


the easiest way to learn programming
introduction to programming
Examples of Expressions

Sample Program

Monday, May 28, 2012
Problem statement:

Calculate the average age of a class of ten students. Prompt the user to enter the age of each student.

Solution:

Lets first sort out the problem. In the problem we will take the ages of ten students from the user. To store these ages we will use ten variables, one for each student’s age. We will take the ages of students in whole numbers (in years only, like 10, 12, 15 etc), so we will use the variables of data type int. The variables declaration statement in our program will be as follow:

int age1, age2, age3, age4, age5, age6, age7, age8, age9, age10;

We have declared all the ten variables in a single line by using comma separator (,). This is a short method to declare a number of variables of the same data type.

After this we will add all the ages to get the total age and store this total age in a variable. Then we will get the average age of the ten students by dividing this total age by 10. For the storage of total and average ages we need variables. For this purpose we use variable TotalAge for the total of ages and AverageAge for average of ages respectively.

int TotalAge, AverageAge;

We have declared AverageAge as int data type so it can store only whole numbers. The average age of the class can be in real numbers with decimal point (for example if total age is 173 then average age will be 17.3). But the division of integers will produce integer result only and the decimal portion is truncated. If we need the actual result then we should use real numbers (float or double) in our program.

Now we have declared variables for storing different values. In the next step we prompt the user to enter the age of first student. We simply show a text line on the screen by using the statement:

cout << “Please enter the age of first student : “; So on the screen the sentence “Please enter the age of first student:” will appear. Whenever we are requesting user to enter some information we need to be very clear i.e. write such sentences that are self explanatory and user understands them thoroughly and correctly. Now with the above sentence everyone can understand that age would be entered for the first student. As we are expecting only whole numbers i.e. age in years only i.e. 10, 12 etc, our program is not to expect ages as 13.5 or 12.3 or 12 years and 3 months etc. We can refine our sentence such, that the user understands precisely that the age would be entered in whole number only. After this we allow the user to enter the age. To, get the age, entered by the user into a variable, we use the statement: cin >> age1;

Lets have a look on the statement cin >> age1; cin is the counter part of the cout. Here cin is the input stream that gets data from the user and assigns it to the variable on its right side. We know that the sign >> indicates the direction of the flow of data. In our statement it means that data comes from user and is assigned to the variable age1, where age1 is a variable used for storing the age entered for student1. Similarly we get the ages of all the ten students and store them into respective variables. That means the age of first student in age1, the age of second student in age2 and so on up to 10 students. When cin statement is reached in a program, the program stops execution and expects some input from the user. So when cin >> age1; is executed, the program expects from the user to type the age of the student1. After entering the age, the user has to press the 'enter key'. Pressing 'enter key' conveys to the program that user has finished entering the input and cin assigns the input value to the variable on the right hand side which is age1 in this case. As we have seen earlier that in an assignment statement, we can have only one variable on left hand side of the assignment operator and on right hand side we can have an expression that evaluates to a single value. If we have an expression on the left hand side of assignment operator we get an error i.e. x = 2 + 4; is a correct statement but x + y = 3+ 5; is an incorrect statement as we can not have an expression on the left hand side. Similarly we can not have an expression after the >> sign with cin. So we can have one and only one variable after >> sign i.e cin >> x; is a correct statement and cin >> x + y; is an incorrect statement.

Next, we add all these values and store the result to the variable TotalAge. We use assignment operator for this purpose. On the right hand side of the assignment operator, we write the expression to add the ages and store the result in the variable, TotalAge on left hand side. For this purpose we write the statement as follow:

TotalAge = age1 + age2 + age3 + age4 + age5 + age6 + age7 + age8 + age9 + age10 ;

The expression on the right hand side uses many addition operators ( + ). As these operators have the same precedence, the expression is evaluated from left to right. Thus first age1 is added to age2 and then the result of this is added to age3 and then this result is added to age4 and so on.

Now we divide this TotalAge by 10 and get the average age. We store this average age in the variable i.e. AverageAge by writing the statement:

AverageAge = TotalAge / 10;

And at the end we display this average age on the screen by using the following statement:

cout << “ The average age of the students is : “ << AverageAge; Here the string enclosed in the quotation marks, will be printed on the screen as it is and the value of AverageAge will be printed on the screen. The complete coding of the program is given below.


A snapshot of the execution of the above program:


In the above output the total age of the students is 123 and the actual average should be 12.3 but as we are using integer data types so the decimal part is truncated and the whole number 12 is assigned to the variable AverageAge.

For previous lesson click here: Precedence of Operators
For next lesson click here: Examples of Expressions


the easiest way to learn programming
introduction to programming
Sample Program

Precedence of Operators

The arithmetic operators in an expression are evaluated according to their precedence. The precedence means which operator will be evaluated first and which will be evaluated after that and so on. In an expression, the parentheses ( ) are used to force the evaluation order. The operators in the parentheses( ) are evaluated first. If there are nested parentheses then the inner most is evaluated first.

The expressions are always evaluated from left to right. The operators *, / and % have the highest precedence after parentheses. These operators are evaluated before + and – operators. Thus + and – operators has the lowest precedence. It means that if there are * and + operators in an expression then first the * will be evaluated and then its result will be added to other operand. If there are * and / operators in an expression (both have the same precedence) then the operator which occurs first from left will be evaluated first and then the next, except you force any operator to evaluate by putting parentheses around it.

The following table explains the precedence of the arithmetic operators:

Operators Operations Precedence (Order of evaluation)
( ) Parentheses Evaluated first
*, /, or % Multiplication, Division, Modulus Evaluated second. If there are several, they are evaluated from left to right
+ or - Addition, Subtraction Evaluated last. If there are several, they are evaluated from left to right

Lets look some examples.

What is the result of 10 + 10 * 5 ?

The answer is 60 not 100. As * has higher precedence than + so 10 * 5 is evaluated first and then the answer 50 is added to 10 and we get the result 60. The answer will be 100 if we force the addition operation to be done first by putting 10 + 10 in parentheses. Thus the same expression rewritten as (10 + 10) * 5 will give the result 100. Note that how the parentheses affect the evaluation of an expression.

Similarly the expression 5 * 3 + 6 / 3 gives the answer 17, and not 7. The evaluation of this expression can be clarified by writing it with the use of parentheses as (5 * 3) + (6 / 3) which gives 15 + 2 = 17. Thus you should be careful while writing arithmetic expressions.

Tips
  • Use spaces in the coding to make it easy to read and understand
  • Reserved words can not be used as variable names
  • There is always a main( ) in a C program that is the starting point of execution
  • Write one statement per line
  • Type parentheses ’( )’ and braces ‘{ }’ in pairs
  • Use parentheses for clarification in arithmetic expressions
  • Don’t forget semicolon at the end of each statement
  • C Language is case sensitive so variable names x and X are two different variables

For previous lesson click here: Arithmetic Operators
For next lesson click here: Sample Program


the easiest way to learn programming
introduction to programming
Precedence of Operators

Arithmetic Operators

In C language we have the usual arithmetic operators for addition, subtraction, multiplication and division. C also provides a special arithmetic operator which is called modulus. All these operators are binary operators which means they operate on two operands. So we need two values for addition, subtraction, multiplication, division and modulus.

Arithmetic OperationArithmetic OperatorAlgebraic ExpressionC Expression
Addition+x + yx + y
Subtraction-x - yx - y
Multiplication*xyx * y
Division/x ÷ y, x / yx / y
Modulus%x mod yx % y

Addition, subtraction and multiplication are same as we use in algebra.
There is one thing to note in division that when we use integer division (i.e. both operands are integers) yields an integer result. This means that if, for example, you are dividing 5 by 2 (5 / 2) it will give integer result as 2 instead of actual result 2.5. Thus in integer division the result is truncated to the whole number, the fractional part (after decimal) is ignored. If we want to get the correct result, then we should use float data type.

The modulus operator returns the remainder after division. This operator can only be used with integer operands. The expression x % y returns the remainder after x is divided by y. For example, the result of 5 % 2 will be 1, 23 % 5 will be 3 and 107 % 10 will be 7.

Sample Program 2
This is a sample program that uses the arithmetic operators. It displays the result of arithmetic operations on the screen. To make the result more visible we have used end line character (endl) with cout. So the statement:

cout << endl;

Simply ends the current line on the screen and the next cout statement displayed at the next line on the screen.

Code of The Program(Operation with integers)

Output of the program

Code of The Program(Operation with decimal numbers)

Output of the program

see everything clearly
// A Sample Program that uses Arithmetic Operators.

#include

main ()
{
//declaration of variables
int a;
int b;
int c;

float x;
float y;
float z;

// assigning values to variables
a = 23;
b = 5;
x = 12.5;
y = 2.25;

// processing and display with integer values
cout << "Operations with integers" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; //addition c = a + b; cout << "a + b = " << c << endl; //subtraction c = a - b; cout << "a - b = " << c << endl; //multiplication c = a * b; cout << "a * b = " << c << endl; // division c = a / b; cout << "a / b = " << c << endl; //modulus c = a % b; cout << "a % b = " << c << endl; // processing and display with decimal values cout << "Operations with decimal numbers" << endl; cout << "x = " << x << endl; cout << "y = " << y << endl; //addition z = x + y; cout << "x + y = " << z << endl; //subtraction z = x - y; cout << "x - y = " << z << endl; //multiplication z = x * y; cout << "x * y = " << z << endl; //division z = x / y; cout << "x / y = " << z << endl; } Output of the program
Operations with integers

a = 23
b = 5
a + b = 28
a - b = 18
a * b = 115
a / b = 4
a % b = 3

Operations with decimal numbers

x = 12.5
y = 2.25
x + y = 14.75
x - y = 10.25
x * y = 28.125
x / y = 5.55556

For previous lesson click here: Data Types
For next lesson click here: Precedence of Operators


the easiest way to learn programming
introduction to programming
Arithmetic Operators

Assignment Operator

The equal-to-sign (=) is used as assignment operator in C language. Do not confuse the algebraic equal-to with the assignment operator. In Algebra X = 2 means the value of X is 2, whereas in C language X = 2 (where X is a variable name) means take the value 2 and put it in the memory location labeled as X, afterwards you can assign some other value to X, for example you can write X = 10, that means now the memory location X contains the value 10 and the previous value 2 is no more there.

Assignment operator is a binary operator (a binary operator has two operands). It must have variable on left hand side and expression (that evaluates to a single value) on right hand side. This operator takes the value on right hand side and stores it to the location labeled as the variable on left hand side, e.g. X = 5, X = 10 + 5, and X = X +1. In C language the statement X = X + 1 means that add 1 to the value of X and then store the result in X variable. If the value of X is 10 then after the execution of this statement the value of X becomes 11. This is a common practice for incrementing the value of the variable by one in C language. Similarly you can use the statement X = X - 1 for decrementing the value of the variable by one. The statement X = X + 1 in algebra is not valid except when X is infinity. So do not confuse assignment operator (=) with equal sign (=) in algebra. Remember that assignment operator must have a variable name on left hand side unlike algebra in which you can use expression on both sides of equal sign (=). For example, in algebra, X +5 = Y + 7 is correct but incorrect in C language. The compiler will not understand it and will give error.

For previous lesson click here: Variables
For next lesson click here: Data Types


the easiest way to learn programming
introduction to programming
Assignment Operator

Variables

We store every kind of data in variables. Variables are locations in memory for storing data. The memory is divided into blocks. It can be viewed as pigeon-holes. You can think of it as PO Boxes also. In post offices there are different boxes and each has an address. Similarly in memory, there is a numerical address for each location of memory (block). It is difficult for us to handle these numerical addresses in our programs. So we give a name to these locations. These names are variables. We call them variables because they can contain different values at different times.

The variable names in C may be started with a character or an underscore ( _ ). But avoid starting a name with underscore ( _ ). C has many libraries which contain variables and function names normally starting with underscore ( _ ). So your variable name starting with underscore ( _ ) may conflict with these variables or function names.

In a program every variable has:
  • Name
  • Type
  • Size
  • Value
The variables having a name, type and size (type and size will be discussed later) are just empty boxes. They are useless until we put some value in them. To put some value in these boxes is known as assigning values to variables. In C language, we use assignment operator for this purpose.

For previous lesson click here: Our First Program,c++ First program
For next lesson click here: Assignment Operator


the easiest way to learn programming
introduction to programming
Variables

Our First Program,c++ First program

Sunday, May 27, 2012
Let’s write our first program in C and understand the basics of C program by explaining it line by line.

# include

main()

{
cout << "hello!"; }


The first line is # include

This is preprocessor directive. The features of preprocessor will be discussed later. For the time being take this line on faith. You have to write this line. The sign # is known as HASH and also called SHARP.

The next line contains main().

There is a main() in every C program. It occurs once in a program. When we write a program and it compiles successfully, it converts into an executable program (file). Then we execute it by typing the command or by double clicking in graphical interface. The system then loads the program into memory. Now the question arises from where the execution should start. In C programs the execution always starts from the main(). In large programs there may be many modules. But the starting point of the program will always be the main function.

Notice that there are parentheses (“( )”, normal brackets) with main. Here the parentheses contain nothing. There may be something written inside the parentheses. It will be discussed in next lectures.

Next, there is a curly bracket also called braces("{ }"). Here is a thing to remember that brackets (parentheses ( ) and braces { }) always occur in pairs. The body of main is enclosed in braces. Braces are very important in C; they enclose the blocks of the program.

The next line in the program,

cout << “hello!”;

is a statement in C language. There are many things in this line to be discussed. Let’s see them one by one.

The word ‘cout’ is known as stream in C and C++. Stream is a complicated thing, you will learn about it later. Think a stream as a door. The data is transferred through stream, cout takes data from computer and sends it to the output that is the screen of the monitor. So we use cout for output.

The sign << indicates the direction of data. Here it is towards cout and the function of cout is to show data on the screen. The thing between the double quoutes (“ ”) is known as character string. In C programming character strings are written in double quotes. Whatever will be written in quotation marks the sign << will direct it towards cout which will show it on the screen. There is a semicolon (;) at the end of the statement. This is very important. All C statements end with semicolon (;). Missing of a semicolon (;) at the end of statement is a syntax error and compiler will report an error during compilation. The only semicolon (;) on a line is a null statement. It does nothing. The extra semicolons may be put at the end but are useless and aimless. Do not put semicolon (;) at a wrong place, it may cause a problem during the execution of the program or may cause a logical error. In this program we give a fixed character string to cout and the program prints it to the screen as: hello!

For previous lesson click here: IDE (Integrated Development Environment)
For next lesson click here: Variables


the easiest way to learn programming
introduction to programming
Our First Program,c++ First program

 

introduction to programming Copyright © 2011-2012 | Powered by Blogger