/*---------------------------*/
/* C# Example #36: */
/* example36.cs */
/* */
/* Arrays example #4 */
/* */
/* Intro to C#, */
/* Nacho Cabanes */
/*---------------------------*/
using System;
public class Example36
{
public static void Main()
{
int[] number = new int[5]; /* An array for 5 integers */
int sum; /* An integer for the sum */
int i; /* To iterate through the elements */
for (i=0; i<=4; i++) /* We ask the user for data */
{
Console.Write("Enter data for position {0}: ", i+1);
number[i] = Convert.ToInt32(Console.ReadLine());
}
sum = 0; /* Starting value for the sum */
for (i=0; i<=4; i++) /* And we calculate it in an iterative way */
sum += number[i];
Console.WriteLine("Their sum is {0}", sum);
}
}
Suggested exercises:
- Using the program proposed in 4.1.2 as a starting point, which stored in a table the number of days in each month, create another program that asks the user for the current day and month, and displays the number of days remaining until then end of the year.
- Create a program that asks the user for 10 numbers and then displays them in reverse order (from the last entered number to the first one).
- A program that asks the user for 10 numbers and then calculates and displays what is the greatest of them all.
- A program that asks the user 10 numbers, calculates the average and then shows the number which are above the average.
- A program that asks for 10 names (hint: this time we need an array of "string"). Then the user will be asked to enter a name and the program will answer whether it is or not part of the 10 that have been typed before. Then it will ask for another name, and so on until the user enters "end".
- A program to prepare space for up to 100 names, and accepts one name at a time from the user, until he presses Enter not typing anything (just an empty string), and then the program will display the list of names that have been entered.
- A program to reserve space for a vector of 3 components, ask the user for values for these components (eg [2, -5, 7]) and show its module (square root of the sum of its components squared).
- A program to reserve space for two 3-component vectors, ask the user for their values and calculate the sum of two vectors (the first component will be x1+y1, the second is x2+y2 and so on).
- A program to reserve space for two 3-component vectors, ask the user for their values and display their dot product (x1·y1+ x2·y2+x3·y3).
No comments:
Post a Comment