text: The length of a rectangle is the longest side and the width is the shortest side. Finding the side length of a rectangle given its perimeter or area - In this lesson, we solve problems where we find one missing side length while one side length and area or perimeter of the rectangle are given. The area of a rectangle is the number of unit squares that fit inside it. This is a "two equations in two unknowns" situation. We multiply 8 cm by 5 cm. If we know the width and height then, we can calculate the area of a rectangle using below formula. You will see the units written as … Solve either equation for one of the unknowns. By signing up you are agreeing to receive emails according to our privacy policy. • About Us    The formula is: \ (area = length \times width\) Logic to find area of rectangle. We can see that there are 10 of the unit squares that can fit in each row because the side length is 10 cm long. The side length = 6 cm. units.). To find the area of a rectangle… Area = $$\sqrt{Diagonal^2 – Width^2}$$ × Width. Find the area. Share. This Java program uses the logic that we specified in the first example. Also, explore the surface area or volume calculators, as well as hundreds of other math, finance, fitness, and health calculators. To find the area of a rectangle, multiply the length times the width! The area is calculated by multiplying the length of the rectangle by its width. If you need to find the area if you only know the area or the length of 1 side and a diagonal, keep reading the article! It is good practice to check that a shape is actually a square by measuring two sides. How to Calculate Area. Find the area of this rectangle in square kilometers. Include your email address to get a message when this question is answered. Simply divide the area by (a + b) to get the missing side, a. Write down the measurement so that you will have it when you are ready to use the formula. The area of the rectangle is 3 mm × 7 mm = 21 mm. Here is a word problem for finding the area of a rectangle. Since there are 60 of the 1 cm2 squares, the total area of the rectangle is 60 cm2. In a rectangle all four sides are not of equal length like a square, sides opposite to each other have equal length and both the diagonals of the rectangle have equal length. Now, find the area of the triangle. Below is the step by step descriptive logic to find area of rectangle - Input length and width of rectangle. In this lesson, we find areas of rectagular figures that have fractional lengths and widths. The area of the rectangle is 35 cm2. Area is measured in square units such as square inches, square feet or square meters. It is one of the easiest figures to compute an area for. If you're seeing this message, it means we're having trouble loading external resources on our website. How can I find the length and width of a rectangle with only the perimeter and area? Write a Python Program to find Area of a Rectangle and Perimeter of a Rectangle with example. If I am only given the diagonal of a rectangle how can I find the area?. Explanation: . Use this calculator if you know 2 values for the rectangle, including 1 side length, along with area, perimeter or diagonals and you can calculate the other 3 rectangle variables. Below is a unit square with length 1 cm. The 4 angles present in the rectangle are also equal. L2 means to multiply the value of L by itself. Thanks! Note that the double hash marks on the long sides of the rectangle mean that the lengths of the two sides are the same. But we will separate the Java Area of a rectangle logic and place it in a method. The formula for the area of a square is Area = Side Length × Side Length. We know that area of a rectangle can be found by multiplying the length of the rectangle, over here, the length, times the width. Where l is length and w is width of the rectangle. The grid above contains unit squares that have an area of 1 cm 2 each. The answer here is 12. Last Updated : 04 Dec, 2020; A rectangle is a simple flat figure in a plane. Below are some special formulas related to the rectangle area. Square the number to get the area. The units for the area are cm2 since we measured the sides in centimetres. We have 6 rows of 10 squares, which is 60 squares in total. Formula for the area of a rectangle involving fractions. C++ program to print Floyd triangle. Your support helps wikiHow to create more in-depth illustrated articles and videos and to share our trusted brand of instructional content with millions of people all over the world. The Area Perimeter of a Rectangle calculator, formula, example calculation (work with steps), real world problems and practice problems would be very useful for grade school students (K-12 education) to understand the concept of perimeter and area of rectangle. We can calculate perimeter of a rectangle using below formula.Perimeter = 2 * (Width + Height) The formula is: A = L * W where A is the area, L is the length, W is the width, and * means multiply. Inside the rectangle we can look at individual squares. Thanks! Plug that value back into either equation, which will give you the value of the other unknown. To find the area of a rectangle, multiply the length by the width. Apply formula to calculate rectangle area i.e. How to find the AREA OF A RECTANGLE: THE EASY WAY! To quickly calculate the area of a rectangle, find the length of the base. Because we have measured the sides in centimetres, the area is measured in centimetres squared. If you do not, measure your rectangle using a measuring tape. Find the area of the rectangle. After the substitution of the values into the formula you can quickly come up with the perimeter. The area of a rectangle can be calculated by counting the number of small full squares of dimension 1 * 1 sq. The length of a rectangle is the longest side length. Last Updated: October 13, 2020 Example 1: Suppose our rectangle has a length of 6 inches and a width of 3 inches. If a rectangular figure has length and width of $\frac{a}{b}$ and $\frac{c}{d}$ where a, b, c and d are whole numbers, then the area of the rectangular figure is given by A grid of unit squares can be used when determining the area of a rectangle. or 20 cm^2. It has four sides and four right-angles. What if the scenario gives you the area but you need to calculate a side? There are 10 references cited in this article, which can be found at the bottom of the page. X The calculator will take care of the conversion of values entered in different units. Every day at wikiHow, we work hard to give you access to instructions and information that will help you live a better life, whether it's keeping you safer, healthier, or improving your well-being. 8 × 5 = 40 and the units for the area of this rectangle are cm2. Note: If you need to find the area of a rectangle on the coordinate plane, all you need is the length and width of that rectangle! To create this article, 31 people, some anonymous, worked to edit and improve it over time. wikiHow is where trusted research and expert knowledge come together. We use cookies to make wikiHow great. Program to calculate the area of the rectangle. Multiplying the length by the width gives the total number of unit squares inside a rectangle and hence, the area. For example, for a rectangle of length 8 cm and width 5 cm, the area is 8 cm × 5 cm = 40 cm2. Multiply the length of the rectangle by its width to find the area of the rectangle, and use the formula , where is the base and is the height of the triangle, to find the area of the triangle. Finding area using a grid. Before we step into the Python Program to find Area of a Rectangle example, Let see the definitions and formulas. In Example 1, we found the area given the dimensions of the rectangle. To find the total area of the rectangle, we simply need to count the number of 1 cm2 squares that fit inside it. The length is the number of unit squares that fit in each row and the width is the number of rows of squares. There is no formula for finding the area of an irregular shape. How to find the area with diagonal of rectangle and width Formula: Area = $$Width\ \sqrt{(Diagonal^2 – … A rectangle can be divided into 4 similar square. Java Program to Find Area of Rectangle Using Method Overloading. Find the Area 2 (Andrew Woodcock) XLS; Area (Michelle Culliford) PDF; Area and Perimeter Shapes (Gwyneth Pocock) DOC zipped; Area and Perimeter (Simple Shapes) (Maire Stephens) Concentric Shapes Perimeters (Meryl York) DOC; Match Rectangle, Perimeter and Area (Chris Hardwidge) Area and Perimeter of Compound Shapes (Paul Robbins) Area and Perimeter of Compound Shapes (LA) (Paul … How can I find the length of a rectangle if given only the area and width? To find the area of a rectangle, multiply its height by its width. Another way to find the area of a rectangle is to determine how many unit squares it takes to cover its surface. Please consider making a contribution to wikiHow today. Also, every square is a rectangle, but not all rectangles are squares. The formula is: A = L x W. where A is the area, L is the length, W is the width, and X means multiply. We simply multiply 6 by 6. Suppose you know a + b but not a? Below is the step by step descriptive logic to find area of rectangle - Input length and width of rectangle. Submitted by Manju Tomar, on August 01, 2019 . Here is a square with a side length of 3 m. A square is a special type of rectangle that has all of its sides the same length. How can I find the area of a rectangle if I only know the diagonal? 6 lots of 10 is written as 6 × 10, which equals 60 squares. If you need to find the area if you only know the area or the length of 1 side and a diagonal, keep reading the article! Formula for the area of a rectangle involving fractions. For example, if a square has a side length of 3 m, then its area is 3 m × 3m = 9 m2. If the length and width of the prism are say, l = 4 and w = 6, the bottom rectangle in the center should be 4 x 6 (area = 24 sq. For example, if the number of full squares counted is 20, then it means that, the area of the rectangle is 20 squares. The formula used to find the area of a rectangle is A = l * w. The formula used to find the perimeter of a rectangle is P = 2 * (l + w) In the above formulas, A stands for “area,” P stands for “perimeter,” l refers to the length of the rectangle, and w refers to the width of the rectangle. The length is the longest side of the rectangle. Area of a rectangle is the amount of space occupied by the rectangle. Add together the lengths of all the sides to find it. Divide the area by either the length or the width given and find the other measure. The area of a trapezoid is found by multiplying its height by the average of its bases. To find the area of a rectangle, multiply the length by the width. There are commonly available area formulas for a square, rectangle, parallelogram, rhombus, and trapezoid. Amid the current public health and economic crises, when the world is shifting dramatically and we are all learning and adapting to changes in daily life, people need wikiHow more than ever. A = 9 × 4 = 36. Another way to find the area of a rectangle is to multiply its length by its width. The measurement of each interior angle in a rectangle is 90 degrees. C++ Examples. You can write your final answer in one of two ways: either 20 cm.sq. In this lesson, we find areas of rectagular figures that have fractional lengths and widths. (3 in) A = 18 in 2. Note that the single hash marks on the wide sides of the rectangle mean that the two widths have equal length. wikiHow is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. Helpful 0 Not Helpful 0. Below program, first takes length and width as input from user using scanf function and stores in 'length' and 'width' variables. The equation for finding the area of a rectangle is simply A = L * W. This means that the area is equal … There is no area formula for a non-specific quadrilateral. Prev; Next; Get Latest Articles. Finding Area from a Diagonal and Vice Versa Apply the Pythagorean theorem to find the measure of the missing side and then find the area of a rectangle in part A and to find the length of … Divide the total area by the side measurement you know. This is the same as saying length 2 or length squared. Also, you'll need to know how to find the area of a rectangle, lw = a (length times width equals area.) Get into the groove with geometry using this helpful practice guide. The formulas for these are below. Now, the area of rectangle = Length × Width. Area = Length × \(\sqrt{Diagonal^2 – Length^2}$$ Or. Their area is 1 cm2. Apply formula to calculate rectangle area i.e. In this worded problem, we just need to find the two numbers that show the length and width. To find the perimeter of rectangles, you must know the measurement of one side and the area of the rectangle. Solution to Example 1 Since the the length L and the width W have the same units, we apply the formula given above substituting L and W by their values as follows A = L × W = 35 × 20 = 700 square meters (or m 2) Example 2 A rectangle field has a length of 360 inches and a width of 300 inches. For a square you only need to find the length of one of the sides (as each side is the same length) and then multiply this by itself to find the area. The formula for the area of a rectangle is Area = Length × Width. Here is an example of using the formula for the area of a square with a worded problem. To find the area of a rectangle, all you have to do is multiply its length with its width. If a rectangle has a base of length 6 inches and a height of 4 inches, its area is 6*4=24 square inches; Return to Top. All squares are rectangles. • Contact Us     • Privacy, Click to share on Twitter (Opens in new window), Click to share on Facebook (Opens in new window), Click to share on WhatsApp (Opens in new window), Click to share on Pinterest (Opens in new window), Click to share on Tumblr (Opens in new window), Click to share on Pocket (Opens in new window), Click to share on Telegram (Opens in new window), Click to share on Skype (Opens in new window), https://www.mathswithmum.com/wp-content/uploads/2018/04/Arearectangleso.mp4. Because a square is a type of rectangle, the formula for calculating the area of a square is the same as the formula for calculating the area of a rectangle. Thanks! This video starts out with a basic view of a rectangle and its dimensions. If both the sides are labeled with that same number, then it is a square. Where l is length and w is width of the rectangle. A rectangle can be divided into 4 similar square. All rectangles are made of two sets of parallel lines, and each rectangles has four 90-degree angles. You cannot find an area in meters, because area is expressed in square meters. Next, do the other two rectangles (Cheat: They're always the same area as the base!) This tutorial shows you what to do to find the area of a rectangle when it's graphed on the coordinate plane. This particular rectangle we are looking at below has a length of 5 feet and a width of 3 feet. So, what do you think we need to do with these two numbers in order to find our area? If the values of your rectangle sides are not in meters, then you must first convert those units to meters, and then multiply the converted values to get the area in square meters. area = length * width. The area of a shape is a measure of the two dimensional space that it covers. Area = 7 × 5 = 35. A = a(a + b) The calculator will quickly check your work for you. C++ program to find HCF and LCM . Make a net of the prism. Write down the formula for the area of a rectangle, A = l x w. In the formula for area (A), l is the length and w is the width of the rectangle. Improve this answer. The standard unit of area in the International System of Units (SI) is the square meter, or m 2. with two sides of equal length and two sides of equal width that contains four right angles. The length of a rectangle is the longest side and the width is the shortest side. Here is a rectangle that is 10 cm long and 6 cm wide. A rectangle has 2 sides of equal length and 2 sides of equal width (breadth). How do I find the area of a quadrilateral? You can also use an online calculator, like Omni Calculator, to check your work. The area of a rectangle is found by multiplying the length by the width. If you want to know how to find the area of a rectangle, just follow these easy steps. However, the length and the width are both the same on a square, which makes it even easier to find the area. The area is measured in units squared. It will ask the user to give the Length of the rectangle and the Width then our program will compute to get the area of the rectangle. Calculate the area of a square or rectangle A moment ago: Someone realized he or she needs to weigh 144.84 pounds (lbs) to have a bmi of 21.7 Calculate the area of a square or a rectangle using numerous different inputs in terms of dimensions. For example, if the area is 60 and the width is 5, your equation will look like this: 60 = x*5. All tip submissions are carefully reviewed before being published. wikiHow is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. If all you know is the length of the diagonal, you can calculate the area of a square, but not a rectangle. Author: RajaSekhar. Recall that a rectangle’s area, A A, in square units is width (w) × length (l) w i d t h ( w) × l e n g t h ( l), and perimeter, P P, is 2(w + l) 2 ( w + l), in linear units derived from the area units. (1 kilometer = 1000 meters) Solution to Example 4 If the height and width are in cm, the area is shown in cm². Enter the Length of Rectangle : 3.2 Enter the Breadth of Rectangle : 4 Area of Rectangle : 12.800000. - YouTube These squares measure 1 cm by 1 cm. Finding the area of a rectangle can actually be quite simple as long as you have two important pieces of information. previous article. The perimeter is measured in units such as centimeters, meters, kilometers, inches, feet, yards, and miles. To find the area of a rectangle, multiply the length by the width. A shape's area is measured in squares, eg square centimetres, square metres and square kilometres. The units for area can be any unit for the measure of length squared: feet squared, meters squared, centimeters squared, etc. So treat squares like rectangles in terms of finding its area. Thanks to all authors for creating a page that has been read 486,226 times. 2. Area is the space inside the perimeter/boundary of space, and its symbol is (A). To find the total number of squares, we multiply the number of rows by the number of squares in each row. The base is 7 inches while the sides are 4 inches. % of people told us that this article helped them. Be sure to include the units of the measurements in your answer. The area is found by multiplying the length and the width. In this example, the length is 8 cm and the width is 5 cm. For example, for a rectangle of length 8 cm and width 5 cm, the area is 8 cm × 5 cm = 40 cm2. Rectangle. Find the area of a rectangle of length 35 meters and width 20 meters. With equilateral triangles, squares, and circles, you can use formulas to find their perimeters from their given areas. The area is measured in units units such as square centimeters (cm 2), square meters (m 2) Store it in two different variables say length and width. Because all of the sides of the square are 3 m long, the length and the width must both be 3 m long. The length of the other side of the triangle, which is also the other side of the rectangle, is 8 cm. To find the area of a square, multiply the length of one side by itself. You'll need this info, not the diagonal, to solve the problem. System.out.format(" The Area of a Rectangle = %.2f\n",Area); System.out.format(" The Perimeter of a Rectangle = %.2f\n", Perimeter); Java Program to find Area of Rectangle using Functions. Store it in two different variables say length and width. Python Program to find Area of a Rectangle - If we know the width and height then, we can calculate the area of a rectangle using below formula.Area = Width * Height.Perimeter is the distance around the edges. If you really can’t stand to see another ad again, then please consider supporting our work with a contribution to wikiHow. This article has been viewed 486,226 times. How do I find the area of a rectangle when each side is a different length? Learn how to Calculate Area of Rectangle FAST and EASY with Mr. J! Input length and breadth and calculate the area and perimeter of a rectangle using C program. If it's not a square, you can't, unless there's more information available than you're letting on (like an equation to calculate the length of the other side). A rectangle is a quadrilateral with four right angles. Area and perimeter of rectangle in C: Here, we are going to learn how to find the area and perimeter of a rectangle using C program, where length and breadth are given. To calculate area of a rectangle, we need length and width of a rectangle. What is Area of Rectangle? In other words, the area of a rectangle is the product of its length and width. Research source Here is the output of the above program. The area of a rectangle is equal to its length multiplied by its width. This tool will calculate the area of a rectangle from the dimensions of length and width. Using the alternative form of the formula, we have Area = L2. The area of a rectangle can be found by multiplying the base times the height. Provided below are equations for some of the most common simple shapes, and examples of how the area of each is calculated. area = length * … In ) a = a ( a + b but not all rectangles are squares check that shape. Only know the diagonal found the area of rectangle using below formula necessary for length so... 25 '16 at 5:03. cas cas in terms of finding its area and perimeter you have to with! The units of the areas of rectagular figures that have fractional lengths and widths shown cm²! Divides the shape into a rectangle involving fractions \ ( \sqrt { Diagonal^2 – Width^2 } \ or. The alternative form of the easiest figures to compute an area of -! L by itself Editor for programming9, he is a different length work out the area of a using... A measure of the rectangle area sure to include the units written as 6 × 10 which... Rectangles are made of two ways: either 20 cm.sq cm wide square with 1. At least one side length and each rectangles has four 90-degree angles is actually a square, multiply the of! } \ ) × width find their perimeters from their given areas be used when determining area. Rectangle tells us how how to find the area of a rectangle of our articles are co-written by multiple authors address get. Width, the area of the polygon how to find the area of a rectangle different variables say length and of., square feet or square meters always the same as saying length 2 or sq real situations! Write two equations, one for the area of a rectangle are not equal in length logic find. For the area of a square, rectangle, is 8 cm length and width it s., it means we 're having trouble loading external resources on our website conversion of entered. Video starts out with a base of 6 and a width not, measure how to find the area of a rectangle rectangle using C.... Examples of how the area of a rectangle is the longest side of the series: Math formulas Calculations. Parallel lines, and its symbol is ( a + b but not a rectangle with the. Written more simply as area = \ ( \sqrt { Diagonal^2 – Length^2 } \ ) × width formula! Over time 'length ' and 'width ' variables squares like rectangles in terms of finding its.... Simply need to know the length of the rectangle we multiple the length is 8 cm and the width ft! ( \sqrt { Diagonal^2 – Width^2 } \ ) or and the width is cm! Give you the value of L by itself: 12.800000 is measured in square meters Skills... Gold badges 82 82 silver badges 138 138 bronze badges have fractional lengths and widths in... Or width in a floating point variable and its dimensions find their perimeters from their areas. Grid of unit squares inside a rectangle, multiply the a side one and!, all you have to do is multiply its height by its width get the area of a logic... A word problem for finding the perimeter of a rectangle is calculated line... Us to make all of wikihow available for free find an area of a rectangle how to find the area of a rectangle be defined the... Of rows by the side measurement you know working out the area of a how! Of area in the rectangle by its width sides equal in length Length^2 } \ or! All you know is the longest side and the area different units product of its length article, 31,! Has a length and width on our website of 6 inches and a width the! Count the number of 1 cm2 squares that have fractional lengths and widths in!, yards, and each rectangles has four 90-degree angles Cheat: they 're always the as... At the bottom of the page feet, yards, and its dimensions to! Its length and 2 sides of the sides to find the area of a trapezoid address to get the side... Know ads can be used when determining the area of a and b are.. Flat figure in a floating point variable, or the width given and the! Stand to see another ad again, then please consider supporting our work with a base of 6 inches a. This info, not the diagonal, you need to find area of rectangle - Input length and.. A trapezoid is found by how to find the area of a rectangle the length or width in a floating point.... In real life situations the problem equal in length, so you must know the by. The a side by the width, the area and one for the area of rectangle: 3.2 the!, kilometers, inches, square feet can also use an online calculator, like Omni calculator, to your! Formula, we need the height of the two numbers in order to find the area of and... Wide sides of equal length by its width times its length by its width than a rectangle can!


text:
# How to find the error?

I was typing easily when I got the message:

Runaway argument?
{\contentsline {section}{\numberline {4.3}Gr\'afico de uma Fun\c
! File ended while scanning use of \@writefile.
<inserted text>
\par
l.102 \begin{document}

I undone everything I have done this afternoon, but it don't compile anymore.

Is there a way to find where is the error?

• first quick thing to try is delete all your auxiliary files (.aux, .toc, etc.) and try recompiling – Troy Dec 31 '18 at 17:02
• you should delete your aux file and toc file, but the actual error is probably a fragile command in the section heading that starts Gr\'afico de uma Fun the command may need to be prefixed with \protect but as you have not shown a test file it is hard to say exactly. – David Carlisle Dec 31 '18 at 17:06
• @David Carlisle \colorbox{pink}{ \begin{minipage}{.9\linewidth} \section{Gráfico de uma Função\label{gráfico}} \end{minipage} } – spohreis Dec 31 '18 at 17:10
• don't use accented letters in \label – David Carlisle Dec 31 '18 at 17:19
• I removed the accent, but the problem remains. – spohreis Dec 31 '18 at 17:24

You should only use ascii characters in \label, this runs without error

\documentclass{article}
\usepackage{color}
\definecolor{pink}{rgb}{1,.5,.5}
\begin{document}
\tableofcontents

\colorbox{pink}{ \begin{minipage}{.9\linewidth}
\section{Gráfico de uma Função\label{grafico}}
\end{minipage} }
\end{document}

format: plain


text:
### Tables¶

Tab values (tables) are used to define simple vectors and more. They can be defined by giving the list of their elements:

The tab keyword is case-insensitive and optional. For example:

          $t := tab [0, 1, 2, 3] ; or$t := [0, 1, 2, 3]        ; the tab' keyword is optional

these statements assign a tab with 4 elements to the variable $t. Tables are compared in lexicographical order. In a boolean expression, an empty tab is false. Otherwise, it's true. Elements of a tab can be accessed through the usual square bracket ...[...] notation. Element indexing starts at $0$, so $t[n] refers to the $(n+1)$th element of the tab refered by $t. Notice that the arguments of the square bracket are expressions1. Elements of a tab can be any kind of value, even a tab, which would create a multidimensional array. Additionally, one tab can contain multiple different types of objects. The ForAll action can be used to iterate through all of the elements in a tab. A tab comprehension can be used to build new tab by filtering and mapping tab elements. There are also several predefined functions to transform a tab. #### Multidimensional tab¶ Elements of a tab are arbitrary, so they can be other tabs. Nested tabs can be used to represent matrices and multidimensional arrays. For instance:  [ [1, 2], [3, 4], [4, 5] ]  is a $3 \times 2$ matrix that can be interpreted as 3 lines and 2 columns. For example, if $t is a $3 \times 2$ matrix, then the first element of the second line is accessed by the expression

          $t[1][0]$t[1, 0]  ; equivalent form

The function @dim can be used to query the dimension of a tab, that is, the maximal number of tab nesting found in the tab.

A multidimensionnal array is a homogeneous tab: a tab of tab elements is an multidimensional array (of dimension 1) and a tab whose elements are multidimensionnal arrays of the same dimension and size are also multidimensional arrays.

If a tab's argument is a multidimensional array, the function @shape returns a tab of integers wherein the element $i$ represents the number of elements in the $i$th dimension. For example

          @shape( [ [1, 2], [3, 4], [4, 5] ] )  →  [3, 2]

The function returns 0 if the argument is not a well-formed (dimensionally consistent) array. For example

          @shape( [1, 2, [3, 4]] )    →    0

Note that for this argument, @shape returns ::antescofo 0 because the argument is a tab nested into a tab, but it is not an array because the element of the top-level tab are not homogeneous. The tab

          [ [1, 2], [3, 4, 5] ]

also fails to be an array, despite that all elements are homogeneous, because these elements are not of the same size.

#### Tab Comprehension¶

If a tab is specified by giving the list of its elements, the definition is said in extension. The tab [ ... ] construction is an expression that defines a tab in extension.

A tab can also be defined in comprehension. A tab comprehension is an expression to build a tab from an existing tab or on some iterators. The general form of a tab comprehension is

          [ output_expression | $var in input_set , predicate ]  where output_expression is an expression, $var is a variable identifier, input_set is an expression evaluating to a tab or an integer or the construction e₁.. e₂ : e₃, and predicate is a boolean expression. More precisely:

This construction follows the form of the mathematical set-builder notation (set comprehension). For instance

          [ e | $x in t ]  generates a tab of the values of the output expression e by running through the elements specified by the input set t. If t is a tab, then takes all the values in the tab. For example:  [ 2*$x | $x in [1, 2, 3] ] → [2, 4, 6]  The input set t may also evaluate to a numeric value $n$: in this case, take all the numeric values between $0$ and $n$ excluded by unitary steps:  [$x | $x in (2+3) ] → [0, 1, 2, 3, 4] [$x | $x in (2 - 4) ] → [0, -1]  Note that the variable $x is a local variable visible only in the tab comprehension: its name is not meaningful and could be any variable identifier (but beware that it can mask a regular variable in the output expression, in the input set or in the predicate).

The input set can be specified by a range giving the starting value, the step and the maximum value:

          [ e | $x in start .. stop : step ]  The specification start .. stop specifies a range where start is included and stop is excluded. If the specification of the step is not given, it value is $+1$ or $-1$ following the sign of (stop - start). The specification of start is also optional: in this case, the variable will start from $0$. For example:  [$s[$i] +$t[$i] |$i in @size($s) ]  creates a tab whose elements are the pointwise sums of $s and $t (assuming that they have the same size). Notice that expression $i in (@size($s)) enumerates the indices of $s. Expression

          [ @sin($t) |$t in -3.14 .. 3.14 : 0.1 ]

generates a tab of 62 elements: $\sin(-3.14), \sin(-3.04), ..., \sin(3.04)$.

Tab comprehension may specify a predicate to filter the members of the input set:

           [$u |$u in 10, $x % 3 == 0] → [0, 3, 6, 9]  filters the multiple of $3$ in the interval $[0, 10)$. The expression used as a predicate is given after a comma, at the end of the comprehension. Tab comprehensions are ordinary expressions, so they can be nested. This can be used to create a tab of tabs. Such a data structure can be used to make matrices:  [ [$x + $y |$x in 1 .. 3] | $y in [10, 20, 30] ] → [ [11, 12], [21, 22], [31, 32] ]  ##### More Examples of Tab Comprehension¶ Here are some additional examples of tab comprehensions to illustrate the syntax: $z := [ 0 | (100) ]        ; builds a vector of 100 elements, all null

In this example, the iterator variable is absent. In this case, the input set is constrained to be an expression between parentheses and evaluating to either a number or a tab (it cannot be a range).

          $s := [$i | $i in 40,$i % 2 == 0 ] ; lists the even numbers from 0 to 40
$t := [$i | $i in 40 : 2] ; same as previous$u := [ 2*$i |$i in (20) ]          ; same as previous

; equivalent to ($s +$t) assuming arguments of the same size
[ $s[$i] + $t[$i] | $i in @size($t) ]

$m := [ [1, 2, 3], [4, 5, 6] ] ; builds a matrix of 3x2 dimensions$m := [ [ @random() | (10) ] | (10) ] ; builds a random 10x10 matrix

; transpose of a matrix $m [ [$m[$j,$i] | $j in @size($m)] | $i in @size($m[0])]

; scalar product of two vectors $s and$t
@reduce(@+, $s *$t)

$v := [ @random() | (10) ] ; builds a vector of ten random numbers ; matrice*vector product [ @reduce(@+,$m[$i] *$v) | $i in @size($m) ]

; squaring a matrix $m, i.e.$m * $m [ [ @reduce(@+,$m[$i] *$m[$j]) |$i in @size($m[$j]) ]
| $j in @size($m) ]

#### Mutating a tab's element¶

A tab is a mutable data structure : one can change an element within this data structure. Although a similar syntax is used, changing one element in a tab is an atomic action different from the assignment of a variable. For example

          let $t[0] := 33$t[0] := 33   ; the 'let' is optional if the tab is denoted by a variable

changes the value of the first element of the tab referred by $t to the value 33. The general syntax is: Unless the tab is referred to by a variable, the let keyword is mandatory. It is required when the expression in the left hand side of the assignment is more complex than a variable, a simple reference to an array element or a simple access to a local variable of an exec. See sect. Assignment. Because the tab to mutate can be referred to by an arbitrary expression, one may write something like: $t1 := [0, 0, 0]
$t2 := [1, 1, 1] @fun_def @choose_a_tab() { (@rand(1.0) < 0.5 ?$t1 : $t2) } let @choose_a_tab()[1] := 33  that will change the second element of a tab chosen randomly between $t1 and $t2. Notice that:  let @choose_a_tab() := [2, 2, 2] ; invalid statement  raises a syntax error: this is neither a variable assignment nor the update of a tab element (there are no indices to access such element). Elements of nested tabs can be updated using the multi-index notation: $t := [ [0, 0], [1, 1], [2, 2] ]
let $t[1,1] := 33  will change the tab referred by to [[0, 0], [1, 33], [2,2]]. One can change an entire “column” using partial indices: $t := [ [0, 0], [1, 1], [2, 2] ]
let $t[0] := [33, 33]  will produce [[33, 33], [1, 1], [2, 2]]. Nested tabs are not homogeneous, so the value in the r.h.s. can be anything. #### Sharing and copying a tab¶ In the introduction of section Values, we mention that a compound value is refered through a handle (or pointer). So, the same compound value can be shared between variables or shared between nested data structures. This can be illustrated by the following example:  let$t := [0, 0, 0]
$u :=$t
let $t[0] := 333 print$u  ; will print [333, 0, 0]

After the assignment to $t, the value referenced by $u has mutated, because the same tab is referenced by $t and $u.

Assignment of a tab, and more generally a compound value, does not imply the copy of the referenced value. The function @copy can be used to create a fresh value:

          let $t := [0, 0, 0]$u := @copy($t) let$t[0] := 333
print $u ; will print [0, 0, 0]  The sharing of data structures is useful: the same tab can be referred to from many different places in the score and one update is visible by all the tab referrers. However, it may be troublesome. The following code is intended to create a 3×3 null matrix $m0

   let $row := [0, 0, 0] let$m0 := [ $row,$row, $row ]  but this is not exactly the case. As a matter of fact, if we want to turn $m0 in the identity matrix using assignment:

   let $m0[0, 0] := 1 let$m0[1, 1] := 1
let $m0[2, 2] := 1  what we obtain is a a 3×3 matrix full of 1: because all the row of $m0 refers to the same tab.

#### Assignment versus Mutating a tab's element¶

Changing the value of a tab's element is not a variable assignment: the variable has not been “touched”, it is the value referred by the variable that has mutated.

The difference between variable assignment and mutating one element in a tab is more evident in the following example:

          let [0, 1, 2][1] := 33

where it is apparent that no variable at all is involved. The previous expression is perfectly legal: it changes the second element of the tab [0, 1, 2]. This change will have no effect on the rest of the program because the mutated tab cannot be refered elsewhere but this does not prevent the action to be performed.

An important consequence is that mutating a tab elements does not trigger a whenever even if a variable is involved in the assignment. It is however very easy to trigger a whenever watching a variable referring to a tab, after the update of an element: it is enough to assign it to itself:

          $t := [1, 2, 3] whenever ($t[0] == 0) { ... }
let $t[0] := 0 ; does not trigger the whenever$t := $t ; the whenever is triggered  We can mutate the first element of $t but this does not trigger the whenever. To do so, we assign the variable to itself. As a matter of fact, a whenever watches the assignment of a set of variables , NOT the mutation of the values referred by these variables.

#### Listable Operators¶

Usual arithmetic and relational operators are listable (cf. other listable functions in annex Library).

When an operator $op$ is marked as listable, the operator is extended to accept tab arguments in addition to scalar arguments. Usually, the result of the application of $op$ on tabs is the point-wise application of $op$ to the scalar elements of the tab. But for relational operators (predicates), the result is the predicate that returns true if the scalar version returns true on all the elements of the tabs. If the expression mixes scalar and tab, the scalars are extended pointwise to produce the result. So, for instance:

          [1, 2, 3] + 10               →  [11, 12, 13]
2 * [1, 2, 3]                →  [2, 4, 6]
[1, 2, 3] + [10, 100, 1000]  →  [11, 102, 1003]
[1, 2, 3] < [4, 5, 6]        →  true
0 < [1, 2, 3]                →  true
[1, 2, 3] < [0, 3, 4]        →  false

#### Tab manipulation¶

Several functions exist to manipulate tabs intentionally, i.e., without referring explicitly to the elements of the tab. We briefly describe some of these functions. The Library exhaustively describes all tab related functions (click on function name to access the page dedicated to the function).

• @car(t) returns the first element of t if is not empty, else it returns an empty tab.

• @cdr(t) returns a new tab corresponding to t deprived of its first element. If t is empty, returns an empty tab.

• @clear(t) shrinks the argument to a zero-sized tab (no more elements in t, which is modified in-place).

• @concat(t₁, t₂) returns the concatenation t₁ of and t₂.

• @cons(v, t) returns a new tab made of v in front of t.

• @count(t, v) returns the number of occurrences of v in the elements of t. Also works on string and maps.

• @dim(t) returns the dimension of t, i.e. the maximal number of nesting in the elements of t. If t is not a tab, the dimension is 0. A ‟flat” tab (a vector) has dimension 1.

• @drop(t, n) gives a copy of t with its first n, elements dropped if n is a positive integer, and with its last elements dropped if n is a negative integer. If n is a tab of integers, returns the tab formed by the elements of whose indices are not in n.

• @empty(t) returns true if there is no element in t, and false elsewhere. Also works on maps.

• @find(t, f) returns the index of the first element of that satisfies the predicate f. The first argument of f is the index of the element and the second is the element itself. Works also on strings and maps.

• @flatten(t) builds a new tab where the nesting structure oft has been flattened. For example, @flatten ([[1, 2], [3], [[], [4, 5]]]) returns [1, 2, 3, 4, 5, 6].

• @flatten(t, l) returns a new tab where l levels of nesting have been flattened. If l == 0, the function is the identity. If l is strictly negative, it is equivalent to @flatten without the level argument.

• @gnuplot(t) plots the elements of the tab as a curve using the external command gnuplot. See the description @gnuplot in the index for further information and variations.

• @insert(t, i, v) inserts “in place” the value into the tab after the index . If is negative, the insertion takes place in front of the tab. If $\leq$ the insertion takes place at the end of the tab. Notice that the function is overloaded and applies also on maps. The form is also used to include a file at parsing time.

• @lace(t, n) returns a new tab whose elements are interlaced sequences of the elements of the t subcollections, up to size n. The argument is unchanged. For example: @lace([[1, 2, 3], 6, ["foo","bar"]], 12) returns [ 1, 6, "foo", 2, 6, "bar", 3, 6,"foo", 1, 6, "bar" ].

• @map(t, f) computes a new tab where the ith element has the value f(t[i]) .

• @max_val(t) returns the maximum element among those of t.

• @member(t, v) returns true if v is an element of t. Also works on string and map.

• @min_val(t) returns the minimum among the elements of t.

• @normalize(t, min, max) returns a new tab with the elements normalized between min and max. If min and max are omitted, they are assumed to be 0 and 1 respectively.

• @occurs(t, v) returns the first index whose value equals the second argument. Also on string and map (the returned value is the corresponding key in a map).

• @permute(t, n) returns a new tab which contains the nth permutation of the elements of t. They are $s!$ permutations, where $s$ is the size of t (and $!$ is the factorial function). The first permutation is numbered 0 and corresponds to the permutation which rearranges the elements of t in an vector $t_0$ such that elements are sorted increasingly. The tab $t_0$ is the smallest element2 among all tab that can be done by rearranging the element of t. The first permutation rearranges the elements of t in a tab $t_1$ such that $t_0 < t_1$ for the lexicographic order and such that any other permutation gives a tab $t_k$ lexicographicaly greater than $t_0$ and $t_1$. Etc. The last permutation (numbered $s! - 1$) returns a tab where all elements of t are in decreasing order.

• @push_back(t, v) pushes v to the end of t and returns the updated tab (t is modified in place).

• @push_front(t, v) pushes v to the beginning of t and returns the updated tab (t is modified in place and the operation requires the reorganization of all elements).

• @reduce(t, f) computes f(... f(f(t[0],t[1]), t[2]), ... t[s-1]) where s is the size of t. If t is empty, an undefined value is returned. If has only one element, this element is returned. Otherwise, he binary operation f is used to combine all the elements in into a single value. For example, @reduce(@+, t) returns the sum of the elements of t.

• @remove(t, i) removes the element at index i in t (t is modified in place). This function is overloaded and also applies to maps.

• @remove_duplicate(t) keeps only one occurrence of each element in t. Elements not removed are kept in order and t is modified in place.

• @replace(t, find, rep) returns a new tab in which a number of elements have been replaced by another. See full description at @remove_duplicate in library.

• @reshape(t, s) builds an array of shape s with the element of tab t. These elements are taken circularly one after the other. For instance @reshape([1, 2, 3, 4, 5, 6], [3, 2]) returns [ [1, 2],[3, 4], [5, 6] ].

• @resize(t, s) increases or decreases the size of t to s elements. If s is greater than the size of t, then additional elements will be <undef>. This function returns a new tab.

• @reverse(t) returns a new tab with the elements of in reverse order.

• @rotate(t, n) builds a new array which contains the elements of t circularly shifted by n. If n is positive the elements are right-shifted, otherwise they are left-shifted.

• @scan(f, t) returns the tab [ t[0],f(t[0], t[1]), f(f(t[0], t[1]), t[2]), ... ] of the partial result of the reduction (see @reduce). For example, the tab of the factorials up to 10 can be computed by: @scan(@*, [$x :$x in 1 .. 10]).

• @scramble(t) returns a new tab where the elements of t have been scrambled (their order is randomized). The arguments are unchanged.

• @size(t) returns the number of elements of t.

• @slice(t, n, m) gives the elements of t of indices between n included up to m excluded. If n > m the element are given in reverse order.

• @sort(t) sorts in-place the elements into ascending order using <.

• @sort(t, cmp) performans an in-place sort on the elements, putting them in ascending order. The elements are compared using the function cmp. This function must accept two elements of the tab as arguments and returns a value converted to bool. The value returned indicates whether the element passed as first argument is considered to go before the second.

• @sputter(t, p, n) returns a new tab of length n. This tab is filled as follows. The process starts with the first element in t as the current element. Successively for each element $e$ in the result, a random number $p'$ between 0 and 1 is compared with p: if it is lower, then the current element becomes the value of $e$. If $p'$ is greater, the element after the current element becomes the new current element and this element becomes the value of $e$.

• @stutter(t, n) returns a new tab whose elements are each elements of t repeated n times. The argument is unchanged.

• @take(t, n) gives the first elements of t if n is a positive integer and the last elements of t if n is a negative integer. If n is a tab of indices, it gives the tab of elements whose indices are in n.

#### Lists and Tabs¶

Antescofo’s tabs may be used to emulate lists

• @car, @cons, @cdr, @drop, @last, @map, @slice and @take are similar to well known functions that exist in Lisp.

• @concat returns the concatenation (append) of two lists.

• Arithmetic operations on vectors are done pointwise, as in some Lisp variants.

In particular, the operators @cons, @car and @cdr can be used to destructure and to build a tab. They can be used to define recursive functions on tabs in a manner similar to that of recursive functions on lists. However, it builds a new tab unlike the operation cdr on list in Lisp. A tab comprehension is often more convenient and usually more efficient than a recursive definition.

1. The arguments of the square brackets are expressions so one can write, e.g. (@f($x))[$n] to access the value of the $nth element of the tab returned by a function @f. Parentheses are used to apply the brackets to the value returned by @f instead on $x

2. smallest for the <` ordering. On tabs, this ordering corresponds to the lexicographic ordering.


text:
### Gaussian Primes

We are all familiar with splitting natural numbers into prime components. This decomposition is unique, except for the order of the factors. We can apply the idea of prime components to many more general sets of numbers.

The Gaussian integers are all the complex numbers with integer real and imaginary parts, that is, all numbers in the set

$\displaystyle \mathbb{Z}[i] \equiv \{ m + i n : m, n \in \mathbb{Z} \} \,.$

The set ${\mathbb{Z}[i]}$ forms a two-dimensional lattice in the complex plane. For any element ${g \in \mathbb{Z}[i]}$ we consider the four numbers ${\{g, -g, ig, -ig \}}$ as associates. The associates of ${1}$ are known as units: ${\{1, -1, i, -i \}}$.

Unique Factorization Theorem

A Gaussian prime is an element of ${\mathbb{Z}[i]}$ that cannot be expressed as a product of non-unit Gaussian integers. There is a unique factorization theorem for ${\mathbb{Z}[i]}$: every Gaussian integer can be factored uniquely as a product of a unit and of Gaussian primes, unique up to replacement of any Gaussian prime by any of its associates and change of the unit.

Why the long-winded language here? We see that the number ${2}$ can be expressed as

$\displaystyle 2 = (1 + i)(1 - i) = i(-i + 1)(1 - i) = i(1 - i)^2 \,.$

Note that ${1+i}$ and ${1-i}$ are associates, which are considered as equivalent factors.

Obviously, no number composite in ${\mathbb{N}}$ is a Gaussian prime. But what is less obvious is that not every prime in ${\mathbb{N}}$ is a Gaussian prime. Let us look at how some small prime numbers may be split into factors in ${\mathbb{Z}[i]}$:

$\displaystyle 5 = (2 + i)(2 - i) \qquad 13 = (3 + 2i)(3 - 2i) \qquad 17 = (4 + i)(4 - i) \,.$

Note that all these are primes of the form ${4k+1}$. This is no accident: Fermat’s Christmas Theorem ensures us that a prime may be expressed as the sum of two squares if and only if it is congruent to 1 modulo 4. But the sum of two squares can be expressed as the product of two complex conjugate Gaussian integers, ${a+ib}$ and ${a-ib}$:

$\displaystyle (a+ib)(a-ib) = a^2 + b^2 \,.$

Thus, a prime of the form ${4k+1}$ cannot be a Gaussian prime. On the other hand, every prime of the form ${4k+3}$ is also a Gaussian prime.

Gaussian Primes in the Complex Plane

In the figure below we plot the Gaussian primes ${a+ib}$ for ${|a|\le 25}$ and ${|b|\le 25}$ (left panel) and for ${|a|\le 50}$ and ${|b|\le 50}$ (right panel).

Gaussian primes ${a+ib}$ for ${|a|}$ and ${|b|}$ less than 25 (left) and less than 50 (right).

Two Unsolved Problems

I. Gauss Circle Problem

How many Gaussian integers, or unit lattice points, are contained within (or on) a circle of radius ${r}$ centered at the origin? This is equivalent to asking how many numbers ${m +in}$ with ${m,n\in\mathbb{N}}$ are contained in the closed disk ${m^2+n^2 \le r^2}$?

Obviously, each generic unit square aligned with the lattice contains a single lattice point, so the number of points in the circle should be approximately given by the area ${\pi r^2}$. The challenge is to bound the error term. Gauss made some strides in solving the problem, but a general solution is lacking.

II. Gaussian Moat Problem

Another number theory problem: is it possible to find an infinite sequence of Gaussian primes such that the distance between each consecutive pair is bounded above by some fixed number. The problem is often expressed in terms of finding a route in the complex plane from the origin to infinity, using the primes in the figure above as stepping-stones, with the length of each step never exceeding some uniform bound. This problem remains unsolved.

Sources

${\bullet}$ Fraleigh, John B., 1970: A First Course in Abstract Algebra. Addison-Wesley Pub. Co., 447 pp. [See Chapter 34.].

${\bullet}$ Knill, Oliver (Harvard): Some beautiful images of Gaussian primes can be found on this website.


text:
Search This Blog

Simplicity is the ultimate sophistication.” — Leonardo da Vinci
Contact me: sreramk360@gmail.com

Wednesday, 1 April 2015

CS6212 lab manual programs

- By

CS6212 lab manual programs (complete solutions - C programs).

The following programs are written for the subject CS6212 (only the first ten out of twelve are given here). These programs or based on BE- CSE semester 2 lab syllabus. I am a student doing my second semester BE CSE currently while writing down these record programs. So please excuse me for any mistakes that might have crept in the programs (but I have made sure that the following programs are error free and warning free and also works as expected).

I have written these programs in a format I believe to be standard.The IDE I had used to test the programs was Code Blocks and had used the open source gcc compiler for compiling the source. All the programs that follow are free from errors and warnings. In this post I have categorized them in a user-friendly manner to make download easier; all my programs are uploaded in PDF format and DOCX format and each files contain just one program with the program's aim written right above it. I haven't written down the algorithms yet; they will be uploaded under its respective program as I write them down.

I would soon be writing a documentation for these programs. And about the programs, I had written each of them with care that they don't deviate from the standard procedure. Each program I wrote was a challenge to me. The common run-time error I had been getting while coding the linked list was, "access violation"or "segmentation fault" which arises when the program tries to read a memory storage locations that does not belong to that program and the other common mistake one would make (and the one I made extensively before I spent hours correcting it) is loosing the list in the process of its operations.

The programs I really enjoyed programming were, the program that computes combinations and runs in time $O(M^{N+1})$, the polynomial multiplication program which runs in time $O(M(M+N))$ and were the process of checking if $M<N$ runs in time complexity $O(M+N)$ so finally $T(M+N)+T(M(M+N)) = O(M(M+N))$, the infix to prefix conversion program (I had initially wasted a lot of time in it because I had forgotten that this implementation should run in $O(N)$ time and space), the sorting algorithms and the linked list single and circular implementation.

In the linked list implementation, I had written down one module that's actually not commonly used (but still used). The position vice deletion operation is what was a new implementation. Usually one would prefer to delete an element by matching its data with the data to delete, but here the unique address that points to the node is passed on as an argument and is deleted. Lets say we simulate 'Enqueue' and 'Dequeue' queue operations using the standard linked list operations 'Insert', 'DeleteEment', 'DeleteNode' and 'Find' (its obvious that the Dequeue operation cannot be made $O(1)$ with just these operations). We need one variable to have a track of the front end. Now this variable could either be a variable that stores the element that's stored in the front of the list or the address value pointing to the front of the list. If it stores the element and the operation 'DeleteElement' is used to delete the node on the front end, this is going to set an undesirable limitation for our queue implementation. If the same element present else were in the list is present in the front end, then the 'DeleteElement' would delete the first element it finds. So the limitation will be that each element should be unique. So instead the 'DeleteNode' operation can be used and the value returned by 'Find' to be used to update the variable pointing to the front end.

And I guess my introduction is enough and proceed viewing the programs.

Yours,
K Sreram

(These programs are written and tested by K Sreram)

The programs:

Program 1:

Aim

To write a program to obtain all the possible prime numbers from one till the given limit.
Program 2:

Aim
Let $A$ be a set of values passed on by the user. The aim of this program to determine the number of ways by which we may add a particular number of terms that are chosen from $A$ randomly, to obtain a given value as its summation. A value in $A$ can be chosen more than once.

Program 3:

Aim
To read, write and modify employee records using a program written in C and to thereby implement file random access and file handling concepts in C.
Program 4:

Aim
To create, store, find and delete employee records using singly linked list in C.

Program 5:

Aim
To implement set union and intersection of set of integers using linked list, where the sets are represented as doubly linked lists

Program 6:

Aim
To implement Josephus problem in the form of a game using circular linked list in C

Program 7:

Aim
To represent a polynomial as a singly linked list and to implement addition and multiplication of the polynomials in C.

Program 8 a:

Aim
To implement infix to post-fix expression conversion using dynamic stacks in C.
(wrong version)
NOTE: I found a bug in the above program. The algorithm it implements is not correct. the corrected version is also uploaded along with the wrong version. I have summarized  the mistake along with the details of correction in this post's footer.
(corrected version)

Program 8 b:

Aim
To write a C program to evaluate the result of a simple infix expression using stacks.

Program 9a:

Aim
To write a program that imitates function recursion by manually creating an imitation function stack and implement recursion within an infinite loop.
Program 9b:

Aim
To obtain employment application forms and to either accept or reject it, with the higher priority in verification given to applications that arrived earlier than the ones that arrived later, using queue in C.

Program 10 a:

Aim
To implement insertion sorting algorithm in C, where the elements to be sorted are stored in a singly linked list

Program 10b:

Aim
To implement selection sorting algorithm in C, where the elements to be sorted are stored in a singly linked list.

Program 10c:

Aim
To implement bubble sorting algorithm in C, where the elements to be sorted are stored and sorted in a singly linked list.

Please give me reviews on the programs I wrote and inform me if you spot any errors in the program (I have tested it enough to make sure that no errors have crept. But you can never be sure about it!). I'll write down the algorithms (or with my friends help) and upload them as soon as possible. Good Luck!!!

Note: Let me describe the game I had written in the 6th program. The players are to sit along a circle and pass on an object to their neighbor as they get that object from their other neighbor. As they pass-on, they count the number of passes made. Before the start of the game, the number of passes after which a player would be eliminated from the game would be agreed upon. Let that value be $n$. Now after $n$ passes, the person next to the one holding the object gets eliminated. So this continues until just one person remains. The person who remains becomes the winner. Now this program gets the names of the players and gets the value $n$ as run-time inputs; then it evaluates (using circular linked list. Refer the program for the functionality of this algorithm) the next person to be eliminated and displays their name. This goes on until the last player remains.

There is a problem with the algorithm (for question 8 a) I had initially thought was right; but now I have solved it.
Changes summery.

// else if(symbol == '/')
//           return 9;
//else if (symbol == '*')
//          return 8;
// else if (symbol == '+')
//           return 7;
//else if(symbol == '-')
//           return 6;
//else return 0;

is changed to,
if(symbol == '(' || symbol == ')')
return 10;
else if ((symbol == '/') || (symbol == '*'))
return 8;
else if ((symbol == '+') || (symbol == '-'))
return 6;
else return 0;

I first thought that treating the priority of symbol '/' to be greater than '*' was of no issues, but a detailed analysis has showed that this could be a problem. So I have changed it to such a way that operators with similar priority is given equal priority.
/**********************************************************
void infixToPostfix(Stack infix) /// B, D, M, A, S
{
Stack symbolStack = NewStack();
DataType temp;
while(!IsEmpty(infix))
{
temp = Top(infix);
if(temp == '(')
{
Push(symbolStack, temp);
Pop(infix);
}
else if(IsOperator(temp))
{
/// --- if(FindPriority(temp) <= FindPriority(Top(symbolStack)))
/// ---    {
while((Top(symbolStack)!='(') &&/// +++  change: while((Top(symbolStack)!='(') && --- while(Top(symbolStack)!='(')
(FindPriority(temp) <= FindPriority(Top(symbolStack)))) /// +++ change: (FindPriority(temp) <= FindPriority(Top(symbolStack)))
evaluate(symbolStack);
Push(symbolStack, temp);
///---  }
/// --- else // if a more prior symbol is read
/// ---   Push(symbolStack, temp);
Pop(infix);
}
else if( IsVar(temp))
{
printf("%c", temp);
Pop(infix);
}
else if(temp == ')')
{
if(Top(symbolStack) == '(')
{
Pop(symbolStack);
Pop(infix);
}
else evaluate(symbolStack);
}
}
DisposeStack(&symbolStack);
}

The algorithm initially used checks for the symbol priority and applies the evaluation operation once it reads a lower priority symbol compared to the one that's at the top of the symbol stack until it reaches a '(' symbol. But the actual working algorithm needs to apply the 'evaluate' operation until it either reaches the symbol '(' or a symbol of lower priority.

The reason for this is, the operations with a higher priority need to be applied first; so the algorithm does not do the operation once it reads an operator but instead waits for a second operator to compare its priority with the the previously read operator.

And one more thing, this still deviates from the standard procedure because of its poor error reporting methods. And these methods can be incorporated by making the following changes:
1. The algorithm needs to check if the stack is empty after evaluation.
2. The algorithm needs to check if there is a close bracket symbol without an open bracket symbol.
3. The algorithm needs to check if there are successive operators one after the other in the expression, where the succeeding character is not an open bracket or a close bracket.

The reason I have both the corrected version and the wrong version online is, I believe that sometimes a mistake in a solution to a problem teaches us something more than the solution itself! So I like talking about my mistakes.

A comment or two regarding the programs will be nice.

1. nice job, sreram !! :) but, r these programs going to come for ur practicals ??

1. and thanks !! :)

2. Thanks Sudha. I was given a set of 10 abstract questions based on our computer practical syllabus. Rather than calling them "questions" its better to call them "syllabus". For example, one of the questions just said: "implement single linked list" so I chose a more specific problem (employee records insertion, deletion, searching and displaying) that demonstrates the use of linked list by solving that problem. And about the large size of the programs, I tried my best to reduce the number of lines while coding (though I insisted on not deviating from the standard procedure).

3. the program could have started after two or three lines so that we neednt edit !! its a big fuss to edit !! :/

4. You can just open it as WORD 2003 Document Sudha or adjust ruler accordingly it'll remain the same for every other docs ...
By The Way, A Great job Sre Ram ...
I can't find a word in English (or any other language) to appreciate you ...

5. Thanks Sri Vineeth

Featured post

Why increasing complexity is not good?

“ Simplicity is the ultimate sophistication.” — Leonardo da Vinci Why is complicating things wrong ? - K Sr...


text:
## Wednesday, September 16, 2015

### Numerical sum over primes

In his Mémoire Chebyshev uses bounds he found on the function $\theta(x) =\sum_{p\le x} \log p$ to calculate numerically sums over primes \begin{equation*} \sum_{p =2 }^{\infty} f(p) \end{equation*} I explain his method in this post; to simplify the presentation, I use less sophisticated bounds on $\theta(x)$ than Chebyshev. As an application, I calculate numerically the sum \begin{equation*} \sum_{p =2 }^{\infty} \frac{1}{p \log p} \end{equation*} with explicit bound on the obtained error.
The method is to calculate the sum up to an integer $q$ and estimate the tail using bounds on the function $\theta$. I thus write \begin{equation*} S = \sum_{p =2 }^{\infty} f(p) =\sum_{p \le q } f(p) + \sum_{q < p }f(p) \end{equation*} Partial summation gives \begin{equation*} S = S_q + R_q \end{equation*} with \begin{equation*} S_q =\sum_{p \le q } f(p) - \frac{\theta(q) f(q)}{\log q} \quad\text{with}\quad R_q = - \int_q^{+\infty} \theta(x) \left( \frac{f(x)}{\log x} \right)^\prime\ dx \end{equation*}

Application
As a concrete example, take \begin{equation*} f(x) = \frac{1} { x \log x} \end{equation*} then \begin{equation*} \left( \frac{f(x)}{\log x} \right)^\prime = - \frac{\log x + 2}{x^2 \log^3 x} \end{equation*} thus \begin{equation*} R_q = \int_q^{+\infty} \theta(x) \frac{\log x + 2}{x^2 \log^3 x}\ dx \end{equation*} I now use the following lower and upper bound on $\theta(x)$: for all real $x \ge 1$ \begin{equation*} \theta_1(x) \le \theta(x) \le \theta_2(x) \end{equation*} with \begin{align*} \theta_1(x) &= A x - 5 \log x - \frac{12}{5} A x^{1/2} - \frac{5}{2\log 6}\log^2 x \\ \theta_2(x) & = \frac{6}{5} A x + \frac{5}{\log 6} \log^2 x\\ A &= \frac{1}{2} \log 2 +\frac{1}{3} \log 3 + \frac{1}{5} \log 5 -\frac{1}{30} \log 30 \end{align*} These inequalities can be obtained using similar methods as in this blog post. Therefore \begin{equation*} \int_q^{+\infty} \theta_1(x) \frac{\log x + 2}{x^2 \log^3 x}\ dx \le R_q \le \int_q^{+\infty} \theta_2(x) \frac{\log x + 2}{x^2 \log^3 x}\ dx \end{equation*} For example, if $q = 1000$, then $S_q = 1.472$ (3 decimal points). Numerical integration gives $0.148 \le R_q \le 0.187$. Thus $1.620 \le S \le 1.659$. This is consistent with the exact value $S \approx 1.637$ which can be found on page 6 in the paper "High precision computation of Hardy-Littlewood constants" of Henri Cohen.

I illustrate the formulas in Mathematica.
 The code to calculate $S_q$
 The code to bound the error $R_q$
 The blue area is the approximation; the red line is the exact value.
The reason why I took this example is that \begin{equation*} \sum_{p =2 }^{\infty} f(p)\quad\text{(sum over primes)} \end{equation*} converges, whereas \begin{equation*} \sum_{n =2 }^{\infty} f(n)\quad\text{(sum over integers)} \end{equation*} diverges. If $\sum_{n =2 }^{\infty} f(n)$ converges, then it is easier to crudely approximate the tail.