--%>

C programming assignment help

Strings, Pointers, Arrays, Structures, and File I/O in C

In this lab you will develop a few programs that will give you some practice with pointers, arrays, structures and file I/O.

Strings, char pointers and character arrays

A string in C is just an array of ASCII characters terminated with a zero byte, called the null character, '\0' (hex value is 0x00).

Typically a char pointer (char *) is used to refer to a string in C.

Here are some examples of string declarations:

char name[] = "Joe";// name is char array length 10 (including null)

char *name2 = "Joe"; // same thing

char name3[] = {'J', 'o', 'e', '\0'}; // same, but null must be added explicitly

char *pc = &name[1]; // pc now refers to the string "oe"

char *pc1 = name + 2; // pc now refers to the string "e" (not just the char 'e')

Elements of an array may be accessed by index or relative to a pointer.

For example, each of the following expressions would evaluate "true" (non-zero in C):

name[2] == *(name2 + 2) // compares characters

*pc1 == 'e' // compares characters

*(pc - 1) == name3[0]; // compares characters

(pc - 1) == name2 // compares pointers (addresses)

Note that in C, the == operator tests for value equality. This means that if pointers are compared with ==, they are equal if their values (the addresses they hold) are the same. Pointers are equal if they are of the same type and contain the same addresses (i.e. the point to the same object in memory).

Structures

C provides a way of creating aggregate data types called structures. A structure is made up of a collection of related data. For example, a display pixel consists of three color components, red, green and blue. A pixel structure in C might be declared:

struct pixel_struct {

unsigned char red;

unsigned char green;

unsigned char blue;

}

Variable of type pixel_struct can be declared as:

struct pixel_struct p1, p2, p3.

Accessing a member of a pixel_struct variable makes use of the "dot" operator:

p1.red = 255;

p1.green = 1;

p1.blue = 10;

A structure variable may be initialized when it is declared:

struct pixel_struct p4 = {100, 200, 300};

It is often convenient to declare a new type for a structure using typedef:

typedef struct pixel_struct {

unsigned char red;

unsigned char green;

unsigned char blue;

} PIXEL;

Now we declare variables of PIXEL type:

PIXEL p1, p2, p3;

Creating a pointer to a pixel:

struct pixel_struct *ppix1;

PIXEL *ppix2;

Initialize a pointer to a pixel:

PIXEL *ppix3 = & p3;

Access an element of the structure pointed to by ppix3 is done using the pointer operator "->", for example:

ppix3->red = 200; // changes the value of red in the p3 structure since ppix3 points to it.

Assignment

For this week's assignment you will write a program called bigcity that involves reading a text file in CSV format (comma-separated-variable), assigning records to structure elements and doing some processing on the data.

Part 1

In your program, make sure you include the files stdio.h and stdlib.h. You might also want to include strings.h. Write a function in your program called printargs that will print out all of the command line arguments, one per line (not including the name of the program). The signature of printargs is:

void printargs(int argc, char **argv);

An argument is preceeded by a '-' character, and everything after it up until the next - character is considered part of the argument.

For example, the command line: bigcity -a -b -c -d -e

will yield:

a

b

c

d

e

Save the source code for this version of your program in bigcity1.c.

Part 2

Create a file called bigcity2.c and copy your source code from bigcity1.c into it as a starting point. Modify your main function so that it uses the second argument (argv[1]) as the name of an input file. Open this file and pass the resulting file pointer to a function (that you must write) called readfile. This function simply reads the file line by line and prints it out to the display. The signature for readfile is:

void readfile(FILE *fp);

You might find it useful to use the function fgets() or fscanf() to read the input lines (you can look these up online).

Part 3 (to be continued...)

Copy your bigcity2.c file to a new file: bigcity3.c.

Modify your readfile function to have the following signature:

void readfile(FILE *fp, CITY *city);

where CITY is a type that is declared so that it represents one line of data from the 50cities.csv file. It has the declaration:

typedef struct city_struct {

char name[64];

int pop_2010;

int pop_2005;

int pop_2000;

int pop_1990;

int pop_change;

float percent_change;

int rank_1990;

int rank_2000;

int rank 2005;

int rank_2010;

} CITY;

Declare a global array called USCity of type CITY above the main() function. (A global variable is a variable that is declared outside of any function and is not declared "static"). Your array should have 50 elements.

Write a function called parseLine() that is called by readfile for each line of the input file that it reads:

void parseLine(char *line, CITY *pcity);

'line' is a pointer to the buffer that contains the text line read from the file.

'pcity' is a pointer to one of the USCity array elements. Since readfile has a reference to the array, it can pass each element in turn using something like:

&pcity[i] where 'i' is an index that runs from 0 to 49.

Note that the first one or two lines of the input file might have to be discarded by readfile().

Your parseLine() function should break the line up into fields and convert them into the appropriate types. Some fields will require getting rid of commas, quotes, etc. but you should be able to separate the line into fields.

When the readfile() function returns, the USCIty array should be filled with all the data in the .csv file.

There is no submission for this part.

Part 4

Copy your bigcity3.c program to bigcity4.c

At this point your main function should be calling readfile() in order to read the .CSV file and populate the CITY array.

For those fields that do not contain valid numbers (either dashes or some other character), assume they contain 0.

For this part, your job is to write the following functions: 

  • void getTotalPopulation2010() - This function prints the total population of all 50 states in the array for the year 2010 in the format: "2010 Total Population of 50 Largest cities = xxxxxxxxxxxx", where xxxxx..x is the population total.
  • void printTopPopChange() - This function prints out the 10 cities whose population had the greatestpercentagechange from 1990 to 2010 (omittingthose cities that do not have population numbers for 1990 census). The output should have the format:

 %

%

:

:

%

Percent population change = (2010pop - 1990pop)/1990pop * 100

NOTE: You do not need to sort the 10 cities, but for extra credit, the 10 cities should be ordered from greatest to smallest percentage change.

Hint: It might be useful to create an array of CITY pointers that can be used to store the "top ten" cities. You can write additional functions that will allow you to sort this array of pointers either after finding them, or while you are scanning through the USCity[] array if you want to aim for the extra credit.

Add calls to these functions in your main() function so that the results are printed to the display.

Submission

Submit your four bigcity*.c files  (just the source files) at the ASULearn prompt below.

 

 

 

   Related Questions in Programming Languages

  • Q : What is Character set encoding

    Character set encoding: The set of values allocated to characters in a character set. Associated characters are frequently grouped with consecutive values, like the digits and alphabetic characters.

  • Q : Use of System Dynamic and System Runtime

    What is the use of System.Dynamic and System.Runtime.CompilerServices namespaces?

  • Q : Define Hexadecimal Hexadecimal : Number

    Hexadecimal: Number representation in hexadecimal is base 16. In base 16, the digits 0-9 and the letters A to F are utilized. A symbolizes 10 (base 10), B symbolizes 11 (base 10), and so forth. Digit positions symbolize successive pow

  • Q : Describe Method Method : The portion of

    Method: The portion of a class definition which implements some of the behavior of objects of the class. The body of the method includes declarations of local variables and statements to execute the behavior. The method receives input through its argu

  • Q : Describe IEEE 754 IEEE 754 : The

    IEEE 754: The standard 754-1985 issued by Institute of Electrical and Electronic Engineers for the binary floating point arithmetic. It is the standard to which Java's arithmetic matches.

  • Q : Illustrates database connection pooling

    Illustrates database connection pooling which is relative to MTS. Answer: This permits MTS to reuse database connections. Pooling of database connections are put to

  • Q : What is Syntax error Syntax error: It

    Syntax error: It is an error detected by the compiler throughout its parsing of a program. The syntax errors generally result from mis-ordering symbols in statements and expressions. Missing curly semicolons and brackets are general illustrations of s

  • Q : Common Language Infrastructure or CLI

    What is the Common Language Infrastructure (CLI)? What relation does .NET have with the CLI?

  • Q : Define several features of XQuery

    Define several features of XQuery?

  • Q : Persistent and non-persistent objects

    Illustrate the difference between persistent and non-persistent objects in the programming?