C# Practice Exercises 1

download C# Practice Exercises 1

of 2

Transcript of C# Practice Exercises 1

  • 7/22/2019 C# Practice Exercises 1

    1/2

    Practice Exercises Simple Programs, Functions, and Arrays

    1

    1. Write a program that declares an array of five doublevalues and then sums the values.

    Print the sum on screen.

    2. Write a program that declares two arrays: one in which you will store 10 integers andanother one that you will use for storing the squared values of the 10 integers (so, if your

    array is called numbersand numbers[0] stores the number 10, then the other array, that

    might be called squares, will store 100 in squares[0]). Dont, however, hardcode the

    squares, but calculate them using *, which is the multiplication operator.

    3. For taking user input in C#, we are using the function

    Console.ReadLine();

    This function reads what the user enters (until Enteris pressed) and stores the input as a

    string of characters. If we want to take an intor a doublevalue from the user, we have to

    convert the input like in the following examples:

    int.parse(Console.ReadLine());

    double.parse(Console.ReadLine());

    (Note: entering alphabetic or special characters instead of numbers will cause a failure in

    the conversion; well see how to address that problem later in the course). Knowing this,

    solve the last problem that you had on the quiz in C#: Imagine that we want to solve the

    quadratic equation

    for coefficients a, b, and centered by a user. Write a C# program solving the equation (first

    ask the user to enter the coefficients, then calculate the result, and print the result on

    screen).

    For calculating square root in C#, use the Math.Sqrt() function which takes a parameter of

    type double.

    Hint: for calculating the result, use a function which takes the coefficients as parameters

    and returns only one of the solutions of the equation.

  • 7/22/2019 C# Practice Exercises 1

    2/2

    Practice Exercises Simple Programs, Functions, and Arrays

    2

    4. In this problem, you will practice using multiple functions in a program. Write one

    function called TakeInputthat asks a user to enter an integer and returns the integer. Then,

    write another function called Calculatethat performs the following calculation

    (a * a) + (a / a)

    where a is the integer entered. Dont calculate (a * a) and (a / a) in one line of code, but use

    one function for multiplication, called Multiply, and one for division, called Divide; hence,

    Calculateshould call both Multiplyand Divide. Note that if ais 0, the program will fail, but

    we are ignoring that in this example.