Help me out in C :)

Started by Zexion, November 20, 2012, 03:05:10 pm

Previous topic - Next topic

Zexion

Okay I'm going to cut straight to the point. I need to do an assignment by 7pm, but really by 5pm because I need to attend a chem session later.

I need to write a c program that takes an input from a file (input.dat) calculates sum and average of rows and columns and displays it on screen and in an output file (result.out).

The thing is I know how to read the files and i know how to write them, but I don't know how to read columns and rows much less use them for calculations.

here's the way the output should look
Quote#1        #2        #2       Sum   Average
     --------- --------- --------- --------- ---------
1   ###### ###### ###### ###### ######
2   ###### ###### ###### ###### ######
3   ###### ###### ###### ###### ######
4   ###### ###### ###### ###### ######
5   ###### ###### ###### ###### ######
6   ###### ###### ###### ###### ######
7   ###### ###### ###### ###### ######
8   ###### ###### ###### ###### ######
9   ###### ###### ###### ###### ######
     --------- --------- --------- --------- ---------
Sum###### ###### ###### ###### ######
     --------- --------- --------- --------- ---------
Avg.###### ###### ###### ###### ######



here are the inputs:
-0.043200 -0.003471 0.000000
-0.040326 -0.004246 -0.000737
-0.018204 -0.004246 -0.001530
0.022249 0.008801 0.004870
0.074892 0.044237 0.032171
0.129600 0.100233 0.089016
0.174747 0.160100 0.161792
0.200242 0.199106 0.214417
0.174747 0.160100 0.161792

Blizzard

November 20, 2012, 03:31:23 pm #1 Last Edit: November 20, 2012, 03:38:01 pm by Blizzard
Hm, those are all floats so you can use fscanf for that.

Here's some pseudo code combined with C code that should help you. I have omitted simple variable declaration and used C++ style variable declaration on the spot for clarity so you will have to modify it.

find first \n character or EOF;
count how many space characters there are from the beginning of the file;
column_count = space_count + 1;
float** matrix = (float**)malloc(1 * sizeof(float*)); // actual C code, whole matrix
matrix[0] = NULL; // actual C code
row = 0;
while (there is still data in file)
{
   float* temp = (float*)malloc(column_count * sizeof(float)); // actual C code, temp buffer for current line
   for (i = 0; i < column_count; i++) // actual C code
   {
       fscanf("%f", &temp[i]);  // actual C code, you have to read float by float
   }
   // you may have to do a getc here or something to skip the \n character
   matrix = (float**)realloc((row + 1) * sizeof(float*)); // actual C code, resizes matrix
   matrix[row] = temp; // actual C code
   row++; // actual C code
}
// now just iterate with a dual for loop through all rows and columns, sum them up and calculate the average


This should give you a general idea what you need to do in order to read all data without knowing beforehand how much data there is in the file (assuming the format is "float, space, float" for rows).
Check out Daygames and our games:

King of Booze 2      King of Booze: Never Ever
Drinking Game for Android      Never have I ever for Android
Drinking Game for iOS      Never have I ever for iOS


Quote from: winkioI do not speak to bricks, either as individuals or in wall form.

Quote from: Barney StinsonWhen I get sad, I stop being sad and be awesome instead. True story.

Zexion

November 20, 2012, 03:44:49 pm #2 Last Edit: November 20, 2012, 03:46:06 pm by Zexion
See that's the thing that actually confused the tutors as well. I don't think we are supposed to use matrix yet, because we haven't covered it.
for example I have no idea what this:

float** matrix = (float**)malloc(1 * sizeof(float*)); // actual C code, whole matrix
matrix[0] = NULL; // actual C code


even does :\ your comments of course tell me what it is, but we haven't covered it in class at this point

edit:she said it could be done with array's though because we covered it after she assigned this

Apidcloud

Did you even cover pointers yet? That line creates a bi-dimensional array (dynamically)
Instead of wanting to be somebody else, rather become somebody else



"I will treasure the knowledge like a squirrel treasures acorns."


Gibbo Glast 2D Engine - The sky is no longer a limit

KK20

Does the assignment assume a certain number of rows and columns? Or can they be any size?

And if they just went over arrays, I'm guessing they don't know pointers.

Other Projects
RPG Maker XP Ace  Upgrade RMXP to RMVXA performance!
XPA Tilemap  Tilemap rewrite with many features, including custom resolution!

Nintendo Switch Friend Code: 8310-1917-5318
Discord: KK20 Tyler#8901

Join the CP Discord Server!

Apidcloud

Despite the fact that an array is a pointer to the first element of its collection xD
Instead of wanting to be somebody else, rather become somebody else



"I will treasure the knowledge like a squirrel treasures acorns."


Gibbo Glast 2D Engine - The sky is no longer a limit

KK20

I don't know C syntax, but I do know in C++ you don't even need to know what a pointer is to work with arrays.

Other Projects
RPG Maker XP Ace  Upgrade RMXP to RMVXA performance!
XPA Tilemap  Tilemap rewrite with many features, including custom resolution!

Nintendo Switch Friend Code: 8310-1917-5318
Discord: KK20 Tyler#8901

Join the CP Discord Server!

Zexion

November 20, 2012, 04:06:08 pm #7 Last Edit: November 20, 2012, 04:08:13 pm by Zexion
The assignment assumes 9 rows and 3 columns and of course the 2 extra rows&columns (sum and average)

Edit: here's what I have so far. The sum returns 0 because I haven't actually calculated it yet..
trying to make it work on screen before printing it to a file.

main()
{
      double stdio [9][3] = { {-0.043200, -0.003471, 0.000000},
                           {-0.040326, -0.004246, -0.000737},
                           {-0.018204, -0.004246, -0.001530},
                           {0.022249, 0.008801, 0.004870},
                           {0.074892, 0.044237, 0.032171},
                           {0.129600, 0.100233, 0.089016},
                           {0.174747, 0.160100, 0.161792},
                           {0.200242, 0.199106, 0.214417},
                           {0.174747, 0.160100, 0.161792} };
      int i,J;
      double sum,average;
     
      for (J=0; J<=8; J++)
      {
          for(i=0; i<=2; i++)
          {
            printf("%d  %9f %d",J+1,stdio[J][i],sum);
          }
          printf("\n");
      }
     
      system("PAUSE");
}   

KK20

So wouldn't that be something along the lines of
float data_table[9][3];


edit  :ninja:

Other Projects
RPG Maker XP Ace  Upgrade RMXP to RMVXA performance!
XPA Tilemap  Tilemap rewrite with many features, including custom resolution!

Nintendo Switch Friend Code: 8310-1917-5318
Discord: KK20 Tyler#8901

Join the CP Discord Server!

Apidcloud

Quote from: KK20 on November 20, 2012, 04:02:38 pm
I don't know C syntax, but I do know in C++ you don't even need to know what a pointer is to work with arrays.

true story though  :haha:

But if you want to allocate memory dynamically, you do need to know how to work with pointers(using malloc 'n stuff) (C)
C++ has the new keyword for that purpose but you still need to use pointers

@Zexion (you replied while I was typing this)
Blizzard shared the code to store those values that you're initializing directly...
After that, you just need to do the sum and average of each column and row right?
Do as Blizzard said, dual loop through the matrix
Instead of wanting to be somebody else, rather become somebody else



"I will treasure the knowledge like a squirrel treasures acorns."


Gibbo Glast 2D Engine - The sky is no longer a limit

Blizzard

Ooooh, that's easy. :D I'll put together the code, give me a few minutes.
Check out Daygames and our games:

King of Booze 2      King of Booze: Never Ever
Drinking Game for Android      Never have I ever for Android
Drinking Game for iOS      Never have I ever for iOS


Quote from: winkioI do not speak to bricks, either as individuals or in wall form.

Quote from: Barney StinsonWhen I get sad, I stop being sad and be awesome instead. True story.

KK20

KK20.
Digging up more information since 1996.

I knew it. Dynamic memory wasn't needed.

Other Projects
RPG Maker XP Ace  Upgrade RMXP to RMVXA performance!
XPA Tilemap  Tilemap rewrite with many features, including custom resolution!

Nintendo Switch Friend Code: 8310-1917-5318
Discord: KK20 Tyler#8901

Join the CP Discord Server!

Zexion

Yeah this is supposed to be a simple little thing. We haven't covered a lot of things mainly because this is an "into to programming" class. I'm kinda scared that I'm not learning as much as I should though o.o

and Lol @KK :P

KK20

Hell, RPG Maker 2003 taught me more programming than my intro course.

Other Projects
RPG Maker XP Ace  Upgrade RMXP to RMVXA performance!
XPA Tilemap  Tilemap rewrite with many features, including custom resolution!

Nintendo Switch Friend Code: 8310-1917-5318
Discord: KK20 Tyler#8901

Join the CP Discord Server!

Apidcloud

November 20, 2012, 04:27:09 pm #14 Last Edit: November 20, 2012, 04:31:01 pm by Apidcloud
Something like this would do

// initialize all elements to 0
float arrows[9];

float columns[3];

for(i = 0; i < 9; i++)
{
for(j = 0; j < 3; j++)
{
float v = stdio[i][j];
arrows[i] += v;
columns[j] += v;

}  
}
// Divide by the number of elements to have the average



Quote from: KK20 on November 20, 2012, 04:17:05 pm
KK20.
Digging up more information since 1996.

I knew it. Dynamic memory wasn't needed.


What do you mean?
Instead of wanting to be somebody else, rather become somebody else



"I will treasure the knowledge like a squirrel treasures acorns."


Gibbo Glast 2D Engine - The sky is no longer a limit

Blizzard

int main()
{
double input[9][3] =
{
{-0.043200, -0.003471, 0.000000},
{-0.040326, -0.004246, -0.000737},
{-0.018204, -0.004246, -0.001530},
{0.022249, 0.008801, 0.004870},
{0.074892, 0.044237, 0.032171},
{0.129600, 0.100233, 0.089016},
{0.174747, 0.160100, 0.161792},
{0.200242, 0.199106, 0.214417},
{0.174747, 0.160100, 0.161792}
};
int i, j;
double rowSums[9] = {0.0};
double columnSums[3] = {0.0};
double sum = 0.0;
printf("     ");
for (i = 0; i < 3; i++)
{
printf("     %d    ", i);
}
printf("    sum     average \n");
printf("     ");
for (i = 0; i < 5; i++) // 5 because of sum and average
{
printf(" ---------");
}
printf("\n");
for (i = 0; i < 9; i++)
{
printf("   %d.", i + 1);
for (j = 0; j < 3; j++)
{
rowSums[i] += input[i][j];
columnSums[j] += input[i][j];
printf(" %9f", input[i][j]);
}
printf(" %9f %9f", rowSums[i], rowSums[i] / 3);
sum += rowSums[i];
printf("\n");
}
printf("     ");
for (i = 0; i < 5; i++) // 5 because of sum and average
{
printf(" ---------");
}
printf("\n");
printf("sum   ");
for (i = 0; i < 3; i++) // 5 because of sum and average
{
printf(" %9f", columnSum[i]);
}
printf(" %9f", sum);
printf("\n");
printf("avg. ");
for (i = 0; i < 3; i++) // 5 because of sum and average
{
printf(" %9f", columnSum[i] / 9);
}
printf("         ");
printf(" %9f", sum / (9 * 3));
printf("\n");
}


I did this out of my head. It should work more or less. There may be a few simple mistakes, but you should be able to find and fix them quickly.
Check out Daygames and our games:

King of Booze 2      King of Booze: Never Ever
Drinking Game for Android      Never have I ever for Android
Drinking Game for iOS      Never have I ever for iOS


Quote from: winkioI do not speak to bricks, either as individuals or in wall form.

Quote from: Barney StinsonWhen I get sad, I stop being sad and be awesome instead. True story.

KK20

input needs to be loaded from a file.

Other Projects
RPG Maker XP Ace  Upgrade RMXP to RMVXA performance!
XPA Tilemap  Tilemap rewrite with many features, including custom resolution!

Nintendo Switch Friend Code: 8310-1917-5318
Discord: KK20 Tyler#8901

Join the CP Discord Server!

Apidcloud

Just insert a while loop like this:
while(fgetc(fp) != EOF)
{
  // read using a fscanf(pointer to file, [standard scanf here])
}


You need to create the pointer to a file and actually open it first - obviously:
FILE *fp;
fp = fopen("path",#read_mode("r","a","rw"....))


Don't forget to close the file when you're finished from reading it:
fclose(fp)
Instead of wanting to be somebody else, rather become somebody else



"I will treasure the knowledge like a squirrel treasures acorns."


Gibbo Glast 2D Engine - The sky is no longer a limit

Zexion

November 20, 2012, 04:44:20 pm #18 Last Edit: November 20, 2012, 04:47:05 pm by Zexion
Actually KK20 she said we could use an array instead of loading it from a file. Thanks blizz it looks like it will work, atm it shuts down my batch file imeadiately, but im sure that's an easy fix lol.

Thanks to all that helped!

And to blizzard
(•_•)
( •_•)>⌐■-■
(⌐■_■)
helping noobs, one code at a time

Edit: by the way it was just the left out system("PAUSE"); lol
Thanks again blizz :)

KK20

QuoteI need to write a c program that takes an input from a file (input.dat) calculates sum and average of rows and columns and displays it on screen and in an output file (result.out).

Well that's misleading ._.

Other Projects
RPG Maker XP Ace  Upgrade RMXP to RMVXA performance!
XPA Tilemap  Tilemap rewrite with many features, including custom resolution!

Nintendo Switch Friend Code: 8310-1917-5318
Discord: KK20 Tyler#8901

Join the CP Discord Server!

Zexion

Quote from: KK20 on November 20, 2012, 04:47:16 pm
QuoteI need to write a c program that takes an input from a file (input.dat) calculates sum and average of rows and columns and displays it on screen and in an output file (result.out).

Well that's misleading ._.


Yeah those were the original instructions she gave, but I think I mentioned somewhere in this thread that she said we could use arrays instead of reading a file.

Blizzard

That's why I gave that pseudo code in the beginning. If you're working with a dynamic array, it's much more complicated. But even a file with strictly 3x9 elements could be loaded easily.
Check out Daygames and our games:

King of Booze 2      King of Booze: Never Ever
Drinking Game for Android      Never have I ever for Android
Drinking Game for iOS      Never have I ever for iOS


Quote from: winkioI do not speak to bricks, either as individuals or in wall form.

Quote from: Barney StinsonWhen I get sad, I stop being sad and be awesome instead. True story.

Apidcloud

Quote from: Zexion on November 20, 2012, 05:02:11 pm
Yeah those were the original instructions she gave, but I think I mentioned somewhere in this thread that she said we could use arrays instead of reading a file.


Either way, the sum and average part works all the same, since it's still a matrix

Quote from: Blizzard on November 20, 2012, 05:40:25 pm
That's why I gave that pseudo code in the beginning. If you're working with a dynamic array, it's much more complicated. But even a file with strictly 3x9 elements could be loaded easily.

It's true that it's much more complicated but he wouldn't need to initialize the matrix in the code and specially wouldn't need to know its size beforehand. Your first code would do it nicely, and would work for any file - obviously following the given data's format - .
Instead of wanting to be somebody else, rather become somebody else



"I will treasure the knowledge like a squirrel treasures acorns."


Gibbo Glast 2D Engine - The sky is no longer a limit

Zexion

I was able to finish it, by the way. I had to rewrite somethings and dumb it down a bit so it can look like I did it lol. I think it looks pretty different though and also there were problems calculating the sum of the last 2 columns and the average of them as well, but over all it wasn't much to fix.

This was my final code incase anyone was interested.

#include <stdio.h>
/* Introduction to Computer Science CSEN 2304
* Assignment 3
* Due Tuesday, November 20
*/

main()
{
double input[9][3] ={ {-0.043200, -0.003471, 0.000000},
                  {-0.040326, -0.004851, -0.000737},
                  {-0.018204, -0.004246, -0.001530},
                  {0.022249, 0.008891, 0.004870},
                  {0.074892, 0.044237, 0.032171},
                  {0.129600, 0.100233, 0.089016},
                  {0.174747, 0.160100, 0.161792},
                  {0.200242, 0.199106, 0.214417},
                  {0.174747, 0.160100, 0.161792} };
           FILE *outp;
           int i, j;
       double rowSums[9] = {0.0};
       double columnSums[3] = {0.0};
           double sum,avg;
           outp = fopen("result.out", "w");
           
/* Draws the heading */
    printf("    ");
    fprintf(outp, "    ");
for (i = 0; i < 3; i++)
{
        printf("        ");
fprintf(outp, "        ");
printf("#%d  ", i);
fprintf(outp, "%d  ", i);
}
    printf("       Sum     Average\n");
    fprintf(outp, "       Sum     Average\n");
    lines();
   
/* Loop to calculate */
for (i = 0; i < 9; i++)
{
printf("%2d", i + 1);                 // Shows current row
fprintf(outp, "%2d", i + 1);
for (j = 0; j < 3; j++)
{
rowSums[i] += input[i][j];
columnSums[j] += input[i][j];
printf("   %9f", input[i][j]);    //Shows the inputs
fprintf(outp, "   %9f", input[i][j]);
}
printf("   %9f   %9f", rowSums[i], rowSums[i] / 3);
fprintf(outp, "   %9f   %9f", rowSums[i], rowSums[i] / 3);
sum += rowSums[i];
avg += rowSums[i] / 3;
printf("\n");
fprintf(outp, "\n");
}
        lines();
        printf("sum");
        fprintf(outp, "sum");
for (i = 0; i < 3; i++)
{
printf("  %9f ", columnSums[i]);
        fprintf(outp, "  %9f ", columnSums[i]);
}
/* Prints the sum row */
    printf("  %9f ", sum);
    fprintf(outp, "  %9f ", sum);
    printf("  %9f", avg);
    fprintf(outp, "  %9f", avg);
    printf("\n");
    fprintf(outp, "\n");
        lines();
    printf("avg.");
    fprintf(outp, "avg.");
   
    for (i = 0; i < 3; i++)
{
printf(" %9f  ", columnSums[i] / 9);
        fprintf(outp, " %9f  ", columnSums[i] / 9);
}   
    printf(" %9f  ", sum / 9);
    fprintf(outp, " %9f  ", sum / 9);
    printf(" %9f\n\n", avg / 9);
    fprintf(outp, " %9f\n\n", avg / 9);
   
        system("PAUSE");
}

lines(int i) {
           FILE *outp;
           outp = fopen("result.out", "w");
        printf("     ");
        fprintf(outp, "     ");
        for (i=0; i <=4; i++)
        {
        printf("---------   ");
        fprintf(outp, "---------   ");
        }
        printf("\n");
        fprintf(outp, "\n");
        }


If you actually run it, you'll notice that the .exe runs perfectly, but the file that is written doesn't. I'm not to sure why this happened, but it did. I wasn't able to fix it before I went to my chem study session for the night.

Blizzard

You forgot to call "fclose(outp);". If you don't call it, the last flush doesn't happen and the file is not closed.
Check out Daygames and our games:

King of Booze 2      King of Booze: Never Ever
Drinking Game for Android      Never have I ever for Android
Drinking Game for iOS      Never have I ever for iOS


Quote from: winkioI do not speak to bricks, either as individuals or in wall form.

Quote from: Barney StinsonWhen I get sad, I stop being sad and be awesome instead. True story.

Zexion

Ah yeah :( oh well, it's the best I could do last minute lol. I was really happy that everyone responded so quickly. Oh and by the way, the code isn't spaced weirdly  like that, but for some reason it came out like that in the code box.