CS 201 Lecture No 4



  Lecture Handout 
  Introduction to programming
  Lecture No. 4
  Reading Material
  Deitel & Deitel – C++ How to Program    chapter 1 
  1.22 
  Sample Program
  Problem statement:
  Calculate the average age of a class of ten student
s. 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 variable 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:
  /*  This program calculates the average age of a class of ten students after prompting the
  user to enter the age of each student. */
  #include <iostream.h>
  main ()
  {
              // declaration of variables, the age will be in whole numbers
              int age1, age2, age3, age4, age5, age6, age7, age8, age9, age10;
  int TotalAge, AverageAge;
  // take ages of the students from the user
              cout << “Please enter the age of student 1: ”;
  cin >> age1;
              cout << “Please enter the age of student 2: ”;
  cin >> age2;
              cout << “Please enter the age of student 3: ”;
  cin >> age3;
              cout << “Please enter the age of student 4: ”;
  cin >> age4;
              cout << “Please enter the age of student 5: ”;
  cin >> age5;
              cout << “Please enter the age of student 6: ”;
  cin >> age6;
              cout << “Please enter the age of student 7: ”;
  cin >> age7;
              cout << “Please enter the age of student 8: ”;
  cin >> age8;
              cout << “Please enter the age of student 9: ”;
  cin >> age9;
              cout << “Please enter the age of student 10: ”;
  cin >> age10;
              // calculate the total age and average age
  TotalAge = age1 + age2 + age3 + age4 + age5 + age6 + age7 + age8 + age9 +
  age10;
  AverageAge = TotalAge / 10;
              // Display the result ( average age )
  cout << “Average age of class is: “ << AverageAge;
  }
  A sample output of the above program is given below.
  Please enter the age of student 1:  12
  Please enter the age of student 2:  13
  Please enter the age of student 3:  11
  Please enter the age of student 4:  14
  Please enter the age of student 5:  13
  Please enter the age of student 6:  15
  Please enter the age of student 7:  12
  Please enter the age of student 8:  13
  Please enter the age of student 9:  14
  Please enter the age of student 10:  11
  Average age of class is: 12
  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.
  Examples of Expressions
  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 force 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 (b2 – 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 b2 – 4ac/2a (i.e. 4ac is divided by 2a instead of (b2-4ac)).
  Use of Operators
  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 7,5,3,1 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 mean 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. 
  /* 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 7,5,3,1 separately. */
  #include <iostream.h>
  main()
  {
              // declare variables
              int number, digit; 
              // prompt the user for input
  cout << "Please enter 4-digit number:";
  cin >> number;
  // get the first digit and display it on screen
             digit = number % 10;
  cout << "The digits are: ";
  cout << digit << ", ";
  // get the remaining three digits number
  number = number / 10;
              // get the next digit and display it 
  digit = number % 10;
  cout << digit << ", ";
  // get the remaining two digits number
  number = number / 10;
              // get the next digit and display it 
             digit = number % 10;
  cout << digit << ", ";
  // get the remaining one digit number
  number = number / 10;
  // get the next digit and display it 
  digit = number % 10;
  cout << digit; 
  }
  A sample output of the above program is given below.
  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. For 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.
  /* Following program takes the radius of a circle from the user and calculates the
  diameter, circumference and area of the circle and displays the result. */
  #include <iostream.h>
  main ()
  {
      // declare variables
      float radius, diameter, circumference, area;
      // prompt the user for radius of a circle
      cout << "Please enter the radius of the circle  " ; 
      cin >> radius ;
      // calculate the diameter, circumference and area of the circle
      // implementing formula i.e. diameter = 2 r circumference = 2 ×— r and area = ×— r2
      diameter = radius * 2 ;
      circumference = 2 * 3.14 * radius ; // 3.14 is the value of ×— (Pi)
      area = 3.14 * radius * radius ;     
      // display the results
      cout << "The diameter of the circle is :   " << diameter ;
      cout << "The circumference of the circle is :   " << circumference ;
      cout << "The area of the circle is :   " << area ;
   }
  A sample output of the above program is given below.
  Please enter the radius of the circle 5
  The diameter of the circle is :  10
  The circumference of the circle is :   31.4
  The area of the circle is :   78.5
  Tips
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)


Post a Comment

Don't Forget To Join My FB Group VU Vicky
THANK YOU :)

Previous Post Next Post