We stored several pieces of information about a person. We can store information about several people if we use both "struct" and arrays. For example, if we want to keep data from 100 people, we could do:
/*---------------------------*/
/* C# Example #40: */
/* example40.cs */
/* */
/* Array of struct */
/* */
/* Intro to C#, */
/* Nacho Cabanes */
/*---------------------------*/
using System;
public class Example40
{
struct personType
{
public string name;
public char initial;
public int age;
public float mark;
}
public static void Main()
{
personType[] person = new personType[100];
person[0].name = "John";
person[0].initial = 'J';
person[0].age = 20;
person[0].mark = 7.5f;
Console.WriteLine("{0} is {1} years old",
person[0].name, person[0].age);
person[1].name = "Peter";
Console.WriteLine("{0} is {1} years old",
person[1].name, person[1].age);
}
}
The initial of the first person would be "person[0].initial", and age of the last one would be "person[99]. age."
When we test this program, we would get
John is 20 years old
Peter is 0 years old
Because when we reserve space for the elements of an "array" using "new", their values are left "empty" (empty strings, 0 for numbers).
Suggested exercises:
· Expand the program of section 4.3.1 to store data up to 100 songs. You must create a menu to allow: add a new song, display the title of every song, find the song that contains some text (the artist or title).
· A program to store data about "images" (computer files containing photographs or other graphic information). For each image, must be stored: name (text), width in pixels (eg 2000), height in pixels (eg 3000), size in Kbytes (eg 145.6). The program should be able to store up to 700 pictures (and the user should be notified when it is full). It should allow the following options: add a new record, see all the records (number and name of each image), find the record that has a certain name.
No comments:
Post a Comment