How to Write a C Program That Reads an Integer and Converts It to Binary
1.2 Congenital-in Types of Data
A data type is a set of values and a set of operations divers on them. For example, we are familiar with numbers and with operations defined on them such every bit add-on and multiplication. There are 8 different built-in types of data in Coffee, mostly dissimilar kinds of numbers. We utilise the system type for strings of characters so frequently that we also consider it here.
Terminology. We use the following code fragment to introduce some terminology:
int a, b, c; a = 1234; b = 99; c = a + b;
The first line is a declaration statement that declares the names of three variables using the identifiers a, b, and c and their type to be int. The next three lines are assignment statements that change the values of the variables, using the literals 1234 and 99, and the expression a + b, with the end result that c has the value 1333.
Characters and strings. A char is an alphanumeric grapheme or symbol, similar the ones that you type. We usually exercise not perform any operations on characters other than assigning values to variables. A String is a sequence of characters. The most common operation that we perform on strings is known as chain: given two strings, chain them together to brand a new string. For example, consider the following Coffee program fragment:
String a, b, c; a = "Hi,"; b = " Bob"; c = a + b;
The showtime statement declares 3 variables to be of type Cord. The adjacent three statements assign values to them, with the cease outcome that c has the value "Hello, Bob". Using string concatenation, Ruler.java prints the relative lengths of the subdivisions on a ruler.
Integers. An int is an integer (whole number) between −231 and 231 − 1 (−2,147,483,648 to two,147,483,647). We use ints frequently not just because they occur frequently in the existent world, but as well they naturally arise when expressing algorithms. Standard arithmetics operators for improver, multiplication, and partitioning, for integers are built into Java, every bit illustrated in IntOps.java and the following table:
Floating-point numbers. The double type is for representing floating-point numbers, eastward.g., for apply in scientific applications. The internal representation is like scientific notation, and then that we can compute with existent numbers in a huge range. We can specify a floating signal number using either a string of digits with a decimal point, eastward.g., 3.14159 for a six-digit approximation to the mathematical abiding pi, or with a annotation like scientific notation, due east.1000., 6.022E23 for Avogadro's constant 6.022 × 1023. Standard arithmetics operators for add-on, multiplication, and division, for doubles are built in to Coffee, as illustrated in DoubleOps.java and the following table:
Quadratic.coffee shows the use of doubles in computing the two roots of a quadratic equation using the quadratic formula.
Booleans. The boolean type has just two values: true or imitation. The apparent simplicity is deceiving—booleans lie at the foundation of computer science. The about important operators divers for the boolean are for and, or, and not.
- and: a && b is truthful if both a and b are true, and fake otherwise.
- or: a || b is true if either a or b is true (or both are true), and false otherwise
- not: !a is true if a is simulated, and false otherwise.
Although these definitions are intuitive and easy to sympathize, it is worthwhile to fully specify each possibility for each operation in a truth table.
Comparisons. The comparison operators are mixed-type operations that take operands of one type (e.chiliad., int or double) and produce a result of type boolean. These operations play a critical role in the process of developing more sophisticated programs.
LeapYear.coffee tests whether an integer corresponds to a leap twelvemonth in the Gregorian calendar.
Library methods and APIs.
Many programming tasks involve using Java library methods in addition to the built-in operators. An application programming interface is a table summarizing the methods in a library.
You tin call a method past typing its name followed by arguments, enclosed in parentheses and separated past commas. Here are some examples:
We oft find ourselves converting data from i type to some other using one of the post-obit approaches.
Type conversion.
Nosotros frequently detect ourselves converting data from one type to another using 1 of the following approaches.
- Explicit blazon conversion. Call methods such every bit Math.round(), Integer.parseInt(), and Double.parseDouble().
- Automatic type conversion. For archaic numeric types, the system automatically performs type conversion when nosotros use a value whose type has a larger range of values than expected.
- Explicit casts. Java also has some born type conversion methods for primitive types that you can use when you are aware that you might lose data, but you accept to make your intention using something called a cast. RandomInt.java reads an integer command-line argument n and prints a "random" integer betwixt 0 and n−one.
- Automatic conversions for strings. The built-in blazon Cord obeys special rules. I of these special rules is that you tin easily convert whatever type of data to a String past using the + operator.
Exercises
- Suppose that a and b are int values. What does the following sequence of statements do?
Solution: sets a, b, and t equal to the original value of a.
- Suppose that a and b are int values. Simplify the following expression: (!(a < b) && !(a > b))
Solution: (a == b)
- The exclusive or operator ^ for boolean operands is defined to exist true if they are different, false if they are the same. Requite a truth table for this office.
- Why does 10/3 give 3 and not three.33333333?
Solution: Since both 10 and iii are integer literals, Java sees no need for type conversion and uses integer partition. You should write 10.0/3.0 if you hateful the numbers to exist double literals. If yous write x/3.0 or 10.0/3, Coffee does implicit conversion to get the same result.
- What do each of the post-obit print?
- Organisation.out.println(2 + "bc"); prints: 2bc
- System.out.println(2 + 3 + "bc"); prints: 5bc
- System.out.println((2+3) + "bc"); prints: 5bc
- System.out.println("bc" + (2+3)); prints: bc5
- Organization.out.println("bc" + two + 3); prints: bc23
Explicate each outcome.
- Explain how to use Quadratic.java to find the foursquare root of a number.
Solution: to find the square root of c, find the roots of x^2 + 0x - c.
- A physics student gets unexpected results when using the code
double strength = Grand * mass1 * mass2 / r * r;
Solution: It divides by r, then multiplies past r (instead of dividing by r *r). Employ parentheses:
double strength = G * mass1 * mass2 / (r * r);
- Write a programme Distance.coffee that takes two integer command-line arguments x and y and prints the Euclidean distance from the indicate (ten, y) to the origin (0, 0).
- Write a program SumOfTwoDice.coffee that prints the sum of two random integers between 1 and half dozen (such every bit you might go when rolling dice).
- Write a programme SumOfSines.java that takes a double command-line statement t (in degrees) and prints the value of sin(2t) + sin(3t).
- Write a program SpringSeason.java that takes two int values chiliad and d from the command line and prints truthful if mean solar day d of calendar month 1000 is between March 20 (m = 3, d =20) and June xx (m = 6, d = 20), simulated otherwise.
Creative Exercises
- Air current chill. Given the temperature t (in Fahrenheit) and the wind speed v (in miles per hour), the National Weather Service defines the wind chill to be:
w = 35.74 + 0.6215 t + (0.4275 t - 35.75) v0.xvi
Write a program WindChill.java that takes 2 double command-line arguments t and v and prints the wind chill. Apply Math.pow(a, b) to compute ab. Note: the formula is not valid if t is larger than 50 in absolute value or if five is larger than 120 or less than 3 (y'all may assume that the values you get are in that range). - Polar coordinates. Write a programme CartesianToPolar.java that converts from Cartesian to polar coordinates. Your program should take 2 real numbers x and y on the command line and print the polar coordinates r and θ. Use the Java method Math.atan2(y, 10), which computes the arctangent value of y/x that is in the range from -π to π.
- 24-hour interval of the week. Write a program DayOfWeek.java that takes a date as input and prints the day of the week that appointment falls on. Your program should take three command-line arguments: 1000 (calendar month), d (day), and y (year). For m use one for January, 2 for February, and so forth. For output print 0 for Lord's day, 1 for Monday, 2 for Tuesday, and so forth. Apply the following formulas, for the Gregorian calendar (where / denotes integer segmentation):
y 0 = y − (14 − 1000) / 12
For instance, on which 24-hour interval of the week did February 14, 2000 fall?
x = y 0 + y 0 / 4 − y 0 / 100 + y 0 / 400
yard 0 = m + 12 × ((14 − m) / 12) − 2
d 0 = (d + x + 31m 0 / 12) mod viiy0 = 2000 - 0 = 1999 x = 1999 + 1999/4 - 1999/100 + 1999/400 = 2483 m0 = 2 + 12*1 - 2 = 12 d0 = (13 + 2483 + (31*12) / 12) modern 7 = 2528 mod 7 = i (Monday)
- Uniform random numbers. Write a program Stats5.java that prints five uniform random values betwixt 0 and 1, their boilerplate value, and their minimum and maximum value. Apply Math.random(), Math.min(), and Math.max().
- Iii-sort. Write a programme ThreeSort.coffee that takes three
int values from the command line and prints them in ascending order. Use Math.min() and Math.max(). - Dragon curves. Write a programme Dragon.coffee to print the instructions for drawing the dragon curves of order 0 through 5. The instructions are strings of the characters F, L, and R, where F means "draw line while moving 1 unit forward", L means "turn left", and R means plow right. A dragon bend of lodge northward is formed when you fold a strip of paper in half n times, so unfold to right angles. The key to solving this problem is to note that a bend of order northward is a bend of order northward−i followed by an 50 followed by a curve of order northward−one traversed in reverse social club, and so to figure out a similar clarification of the reverse curve.
Web Exercises
- Write a programme Swap.java that takes two integer control-line arguments a and b and swaps their values using the swapping idiom described on p. 17. After each consignment statement, employ System.out.println() to impress a trace of the variables.
- What does the following statement do where grade is a variable of type int?
boolean isA = (ninety <= form <= 100);
Solution: Syntax fault since <= is a binary operator. Yous can rewrite the expression as (90 <= grade && course <= 100).
- RGB to YIQ color converter. Write a program RGBtoYIQ.coffeethat takes an RGB colour (3 integers between 0 and 255) and transforms it to a YIQ color (iii dissimilar existent numbers Y, I, and Q, with 0 ≤ Y ≤ ane, –0.5957 ≤ I ≤ 0.5957, and –0.5226 ≤ Q ≤ 0.5226). Write a plan YIQtoRGB.java that applies the changed transformation.
- CMYK to RGB color matching. Write a program CMYKtoRGB that reads in four control line inputs C, Thou, Y, and K between 0 and ane, and prints the respective RGB parameters. Devise the appropriate formula by "inverting" the RGB to CMYK conversion formula.
- What does the following code fragment print?
double x = (double) (iii/v); System.out.println(x);
Solution: It prints 0.0 since the integer sectionalisation is done before the bandage.
- Why doesn't the following program print 4294967296 = 2^32?
int x = 65536; long y = ten * x; System.out.println(y);
- What is the value of (Math.sqrt(2) * Math.sqrt(2) == two)?
- Write a programme DivideByZero.java to see what happens when yous split up an int or double by zip.
Solution:
- (17 / 0) and (17 % 0) result in a partitioning by zip exception;
- (17.0 / 0.0) results in a value Infinity;
- (17.0 % 0.0) results in a value NaN that stands for "non a number."
- Gauge the biggest number. Consider the following game. Alice writes downwards ii integers between 0 and 100 on two cards. Bob gets to select i of the 2 cards and see its value. After looking at the value, Bob commits to one of the two cards. If he chooses a card with the largest value, he wins; otherwise he loses. Devise a strategy (and corresponding computer programme) for Bob and so that he guarantees to win strictly more half the time.
- Fibonacci word. Write a programme FibonacciWord.java that prints the Fibonacci discussion of order 0 through 10. f(0) = "a", f(1) = "b", f(ii) = "ba", f(iii) = "bab", f(4) = "babba", and in general f(northward) = f(n-ane) followed by f(due north-2). Use string chain.
- Standard deviation. Modify Do 1.2.xxx so that it prints the sample standard divergence in addition to the boilerplate.
- Write a plan that reads in three parameters and prints true if all iii are equal, and fake otherwise.
- What happens if you compile LeapYear.java and execute it with
- java LeapYear
- java LeapYear 1975.5
- java LeapYear -1975
- java LeapYear 1975 1976 1977
- What does the compiler do if you try to write the following expression:
- What does the compiler practise if you lot try to write the post-obit expression:
double x; System.out.println(x);
Solution: The compiler complains that the variable x might non have been initialized. Variables inside main are non automatically initialized.
- What does the post-obit lawmaking fragment print.
int threeInt = 3; int fourInt = 4; double threeDouble = iii.0; double fourDouble = 4.0; Organisation.out.println(threeInt / fourInt); Organisation.out.println(threeInt / fourDouble); Arrangement.out.println(threeDouble / fourInt); Arrangement.out.println(threeDouble / fourDouble);
- Write a program that takes four real-valued command line parameters x1, y1, x2, and y2 and prints the Euclidean distance between the points (x1, y1) and (x2, y2). Use Math.sqrt().
- Write a plan Ordered.java that reads in three integer command line arguments, x, y, and z. Create a boolean variable b that is truthful if the three values are either in ascending or in descending order, and false otherwise. Impress the variable b.
- Write a plan Divisibility.java that reads in two command line inputs and prints true if both are divisible by 7, and simulated otherwise.
- Area of a triangle. Write a program TriangleArea.java that takes three command line inputs a, b, and c, representing the side lengths of a triangle, and prints the area of the triangle using Heron'due south formula: area = sqrt(s(s-a)(s-b)(due south-c)), where southward = (a + b + c) / two.
- Equatorial to horizontal coordinates. The equatorial coordinate organisation is widely used by astronomers to indicate the position of a star on the angelic sphere. The position is specified by its declination δ, its hr angle H, and its latitude φ. The horizontal coordinate system (a.k.a. Alt/Az coordinate system) is useful for determining the setting/rising time of celestial objects. The position is specified by its altitude (vertical angle from the horizon) and and its azimuth (horizontal angle). Given a star'southward position using equatorial coordinates, detect its position in horizontal coordinates using the formulas below.
Altitude = asin (sin φ sin δ + cos φ cos δ cos H) Azimuth = acos ((cos φ sin δ - sin φ cos δ cos H) / cos (Altitude) )
- Body mass index. The torso mass index (BMI) is the ratio of the weight of a person (in kilograms) to the square of the tiptop (in meters). Write a program BMI.coffee that takes two command-line arguments, weight and height, and prints the BMI.
- Temperature conversion. What is wrong with the following code fragment to convert from Fahrenheit (F) to Celsius (C)?
double C = (F - 32) * (5 / ix);
- Exponentiation. What is wrong with the following code fragment to compute a2, where a is of type double?
Solution: In Coffee, ^ does not mean exponentiation (it'due south the exclusive or function from logic). Utilize a*a instead. To compute ax, utilize Math.pow(a, 10). Note that Math.prisoner of war() returns a double then that you would need an explicit cast if a and b in the to a higher place example were integers.
- What of the following statements is legal?
boolean b = 1; boolean b = true; boolean b = "truthful"; boolean b = True;
Solution: Simply the second one.
- Disallowment overflow, requite a code fragment to compute the maximum of two integers a and b without using Math.max() or if.
int max = (a + b + Math.abs(a - b)) / two;
- Discriminant of cubic polynomial. Given the coefficients b, c, and d of the cubic polynomial 10^3 + bx^ii + cx + d, write an expression to compute the discriminant b^2c^2 - 4c^three - 4b^3d - 27d^two + 18bcd.
- Barycenter. In a two-body system, the barycenter is the center of gravity about which the two celestial bodies orbit each other. Given the masses chiliad 1 and m two of two bodies, and the shortest distance a between the two bodies, write a program to compute the distance from the eye of the offset (more massive) trunk to the barycenter: r 1 = a one thousand two / (grand 1 + m ii).
Hither are a few examples. Masses are in globe-mass units, distances are in kilometers.
World-moon: thousand ane = ane, m 2 = .0123, a = 384,000, r 1 = 4,670, R 1 = 6,380.
Pluto-Charon: m i = .0021, m two = .000254, a = 19,600, r i = 2,110, R one = 1,150.
Sunday-Earth: 1000 ane = 333,000, m ii = 1, a = 150,000,000, r i = 449, R i = 696,000.
Annotation that if r 1 is less than the radius of the start trunk R ane, then the barycenter lies within the first body.
- Poisonous substance parentheses. Find a legal Java expression that leads to a compile-fourth dimension error when y'all add parentheses around a subexpression to to document the order of evaluation that would take place in their absence.
Solution: The literal value 2147483648 (two^31) is permitted only as an operand of the unary minus operator, i.e., -2147483648. Enclosing it in parentheses, i.eastward., -(2147483648), leads to a compile-time mistake. Similar ideas with the literal value 9223372036854775808L (2^63).
- Machine loan payments. Write a program CarLoan.java that reads in 3 command-line arguments P, Y, and R and calculates the monthly payments yous would have to make over Y years to pay off a P dollar loan at R per cent interest compounded monthly. The formula is The formula is
P r payment = ---------------, where n = 12 * Y, r = (R / 100) / 12 1 - (1 + r)^(-n)
Caveat: in Chapter 9, nosotros will consider more accurate ways to compute this quantity, so before you go off to run an online bank, exist sure to learn virtually roundoff error.
- Write a program Trig.coffee to illustrate various trigonometric functions in the Math library, such as Math.sin(), Math.cos(), and Math.toRadians().
Source: https://introcs.cs.princeton.edu/java/12types/
0 Response to "How to Write a C Program That Reads an Integer and Converts It to Binary"
Post a Comment