Min and Max of 2 of 2D array - c

#include <stdio.h>
#include <stdlib.h>
#define ROWS 15
#define COLS 10
void find_elements(int mtr[ROWS][COLS], int a, int b, int *p1, int *p2);
int main(void) {
int i, j;
int z, l;
int arr[ROWS][COLS];
int min;
int max;
FILE *fp;
fp = fopen("numbers2.txt", "r");
printf("------------------------------------------------------------------------------\n");
printf(" Loaded Array \n");
printf("------------------------------------------------------------------------------\n");
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
fscanf(fp, "%d", &arr[i][j]);
printf("%d\t", arr[i][j]);
}
printf("\n\n");
}
do {
printf("Enter row[1-15]:\n");
scanf("%d", &z);
} while ((z > 15) || (z < 1));
do {
printf("Enter column[1-10]:\n");
scanf("%d", &l);
} while ((l > 10 || (l < 1)));
printf("------------------------------------\n");
printf("The Max of Row %d is: %d\n", z, max);
printf("The min of Column %d id: %d\n", l, min);
find_elements(arr[ROWS][COLS], i, j, &min, &max);
fclose(fp);
return 0;
}
void find_elements(int mtr[ROWS][COLS], int a, int b, int *p1, int *p2) {
int k;
*p1 = mtr[a][0];
*p2 = mtr[0][b];
for (k = 1; k < COLS; k++) {
if (*p1 <= mtr[a][k])
*p1 = mtr[a][k];
}
for (k = 1; k < ROWS; k++) {
if (*p2 >= mtr[k][b])
*p2 = mtr[k][b];
}
}
When I compile this program the following message appears:
[Warning] passing argument 1 of 'find_elements'
makes pointer from integer without a cast
[Note] expected 'int (*)[10]' but argument is of type 'int'
I am programming for about 3 months in C without a previous experience on programming before, so I can't understand what I am doing wrong. I need some help.
Thank you

As the comments point out, in this line:
find_elements(arr[ROWS][COLS],i,j,&min,&max);
the first argument of the function call is a single int, and in fact an int that doesn't even exist, which invokes undefined behavior.
What you need to do is, pass the entire array to the function, like this:
find_elements(arr,i,j,&min,&max);
// ^^^ just the array name

There are at least 3 problems in your code:
you should just pass arr as the first argument to find_elements,
you should move the function call before the printf.
you should pass z and l instead of i and j.
why are row 0 and column 0 excluded from the search?
Here is a modified version:
#include <stdio.h>
#define ROWS 15
#define COLS 10
void find_elements(int mtr[ROWS][COLS], int a, int b, int *p1, int *p2);
int main(void) {
int i, j, z, l;
int arr[ROWS][COLS];
int min, max;
int c;
FILE *fp;
fp = fopen("numbers2.txt", "r");
if (fp == NULL) {
printf("cannot open numbers2.txt\n");
return 1;
}
printf("------------------------------------------------------------------------------\n");
printf(" Loaded Array \n");
printf("------------------------------------------------------------------------------\n");
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (fscanf(fp, "%d", &arr[i][j]) != 1) {
printf("invalid data\n");
return 1;
}
printf("%d\t", arr[i][j]);
}
printf("\n\n");
}
fclose(fp);
do {
printf("Enter row[1-%d]:\n", ROWS);
if (scanf("%d", &z) != 1) {
while ((c = getchar()) != EOF && c != '\n')
continue;
if (c == EOF) {
printf("end of file\n");
return 1;
}
printf("invalid entry\n");
continue;
}
} while (z > ROWS || z < 1);
do {
printf("Enter column[1-%d]:\n", COLS);
if (scanf("%d", &l) != 1) {
while ((c = getchar()) != EOF && c != '\n')
continue;
if (c == EOF) {
printf("end of file\n");
return 1;
}
printf("invalid entry\n");
continue;
}
} while (l > COLS || l < 1);
find_elements(arr, z, l, &min, &max);
printf("------------------------------------\n");
printf("The Max of Row %d is: %d\n", z, max);
printf("The min of Column %d id: %d\n", l, min);
return 0;
}
void find_elements(int mtr[ROWS][COLS], int a, int b, int *p1, int *p2) {
int k;
*p1 = mtr[a][0];
*p2 = mtr[0][b];
for (k = 1; k < COLS; k++) {
if (*p1 < mtr[a][k])
*p1 = mtr[a][k];
}
for (k = 1; k < ROWS; k++) {
if (*p2 > mtr[k][b])
*p2 = mtr[k][b];
}
}

Related

Last printed values in a loop from 2D-array are wrong in c

so I've got one program to generate random numbers (for ex. 100 lines, 5 number per line) to .txt file and then the second one reads from the .txt file, loads values into 2D integer array and then prints each line and it's min, max, sum, avg values under them.
My problem is, that if I generate for ex. 100 lines, int .txt file they are all correct, and in for loop while printing them and calculating min max sum avg they are correct, but last ~4 lines have values out of nowhere and it's just random numbers, not from the interval and they dont reflect values in .txt file.
I wonder if you would be able to find something, why's that like that. Thanks
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int maxArr(int array[], int arrayLength);
int minArr(int array[], int arrayLength);
int sumArr(int array[], int arrayLength);
float avgArr(int array[], int arrayLength);
int main() {
FILE *outputFile;
char path[100];
char character;
int numLines = 0;
int space = 0;
do{
printf("\nEnter the file path: ");
scanf("%s", path);
outputFile = fopen(path, "r");
if(outputFile == NULL){
printf("The path doesnt exist. Try again.\n");
}
}while(outputFile == NULL);
while(feof(outputFile) == 0){
character = fgetc(outputFile);
if(character == '\n'){
numLines += 1;
}
}
//terminator line eof
numLines += 1;
fclose(outputFile);
outputFile = fopen(path, "r");
do{
character = fgetc(outputFile);
if(character == ' '){
space += 1;
}
}while(character != '\n');
fclose(outputFile);
printf("numLines = %d || numSpace = %d\n", numLines, space);
outputFile = fopen(path, "r");
int i, j;
int array[numLines + 1][space];
for(i = 0; i < numLines; i++){
for(j = 0; j < space; j++){
character = fgetc(outputFile);
if(character != ' ' && character != '\n'){
fscanf(outputFile, "%d ", &array[i][j]);
}
}
}
i = 0;
j = 0;
int max, min, sum;
float avg;
for(i; i < numLines + 1; i++){
printf("Line [%d]: ", i);
j = 0;
for(j; j < space; j++){
printf("%d ", array[i][j]);
}
min = minArr(array[i], space);
max = maxArr(array[i], space);
sum = sumArr(array[i], space);
avg = avgArr(array[i], space);
printf("\n");
printf("Min: %d | Max: %d | Sum: %d | Avg: %.2f\n", min, max, sum, avg);
printf("\n");
// sleep(1);
}
fclose(outputFile);
return 0;
}
int maxArr(int array[], int arrayLength){
int max = array[0];
int i;
for(i = 1; i < arrayLength; i++){
if(max < array[i]){
max = array[i];
}
}
return max;
}
int minArr(int array[], int arrayLength){
int min = array[0];
int i;
for(i = 1; i < arrayLength; i++){
if(min > array[i]){
min = array[i];
}
}
return min;
}
int sumArr(int array[], int arrayLength){
int sum = 0;
int i;
for(i = 0; i < arrayLength; i++){
sum += array[i];
}
return sum;
}
float avgArr(int array[], int arrayLength){
float avg;
int sum = sumArr(array, arrayLength);
avg = (float)sum / arrayLength;
return avg;
}

Transfering data from a .csv to and struct array and then sorting it to save it on a different file

The code I've written so far goes as follows:
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define P 200
typedef struct Point{
char name[50], surname[50], email[50];
int donation;
} Point;
char SortMenu(void);
void PrintArray(Point A[]);
void CopyArray(Point Source[], Point Copy[]);
void BubbleSort(Point A[]);
void ShellSort(long int A[]);
void QuickSort(long int A[], int bottom, int top);
void InsertionSort(long int A[]);
void SelectionSort(long int A[]);
void MergeSort(long int A[], int l, int r);
void Merge(long int A[], int l, int m, int r);
//Global variables
clock_t start, end;
Point points[200];
Point copypoints[200];
Point temp;
int main(){
//Variable declaration area
int input, i, give;
char choice = ' ', choise2 = ' ';
int array_size;
//File to store the execution time
FILE * fp;
fp = fopen("temp.txt", "w");
if (fp == NULL){
return 1;
}
//CSV file with the data to sort
FILE * file;
file = fopen("DonationData.csv", "r");
if (file == NULL){
return 1;
}
char buffer[200];
fgets(buffer, 200, file);
Point points[200] = {};
Point copypoints[200] = {}; //making another array so that we can check if the sorting was done correctly
i = 0;
while(!feof(file)){
Point* p = points + i;
sscanf(buffer, "%s %s %s %d", &p->name, &p->surname, &p->email, &p->donation);
fgets(buffer, 200, file);
i++;
}
//printf("Read point: %s %s %s %d", points[i].name, points[i].surname, points[i].email, points[i].donation);
//PrintArray(copypoints);
int n = i;
for(i = 0; i < P; i++){
printf("Read point: %s %s %s %d\n", points[i].name, points[i].surname, points[i].email, points[i].donation);
}
/*
printf("\n\n\n\n");
for(i = 0; i < P; i++){
printf("Read point: %s %s %s %d\n", copypoints[i].name, copypoints[i].surname, copypoints[i].email, copypoints[i].donation);
}
*/
//seed for rand
srand(time(NULL));
do{
//Calling user Menu
choice = SortMenu();
if (choice == 'Q'){
break;
}
//printf("%d", input);
//system("pause");
//calling all the functions (I used if statements because at the start switch was not working but now I know why)
if ( choice == '1' ){
CopyArray(points, copypoints);
printf("Sorting your Data using Bubble-sort.\n");
BubbleSort(copypoints);
printf("\n\n Finished Sorting!\n\n");
printf("Before: ");
PrintArray(points);
printf("\nAfter: ");
PrintArray(copypoints);
printf("\n\n");
double time_taken = (double)(end - start) / (double)(CLOCKS_PER_SEC);
//fprintf(fp, "Bubble-sort = Execution time: %lf | Scenario %d\n",time_taken,s+1);
printf("Essential info has been recorded to the text file.\n");
//system("pause");
printf("\n\n");
}
else if ( choice == '2' ){
CopyArray(points, copypoints);
printf("Sorting your Data using Quick-sort.\n");
QuickSort(copypoints, 0, P-1);
printf("\n\n Finished Sorting!\n\n");
printf("Before: ");
PrintArray(points);
printf("\nAfter: ");
PrintArray(copypoints);
printf("\n\n");
double time_taken = (double)(end - start) / (double)(CLOCKS_PER_SEC);
fprintf(fp, "Quick-sort = Execution time: %lf | Scenario %d\n",time_taken,s+1);
printf("Essential info has been recorded to the text file.\n");
//system("pause");
printf("\n\n");
}
else if ( choice == '3' ){
CopyArray(points, copypoints);
printf("Sorting your Data using Merge-sort.\n");
MergeSort(copypoints, 0, scenarios[s] - 1);
printf("\n\n Finished Sorting!\n\n");
printf("Before: ");
PrintArray(points);
printf("\nAfter: ");
PrintArray(copypoints);
printf("\n\n");
double time_taken = (double)(end - start) / (double)(CLOCKS_PER_SEC);
fprintf(fp, "Merge-sort = Execution time: %lf | Scenario %d\n",time_taken,s+1);
printf("Essential info has been recorded to the text file.\n");
//system("pause");
printf("\n\n");
}
else if ( choice == '4' ){
CopyArray(points, copypoints);
printf("Sorting your Data using Selection-sort.\n");
SelectionSort(copypoints);
printf("\n\n Finished Sorting!\n\n");
printf("Before: ");
PrintArray(points);
printf("\nAfter: ");
PrintArray(copypoints);
printf("\n\n");
double time_taken = (double)(end - start) / (double)(CLOCKS_PER_SEC);
fprintf(fp, "Selectio-sort = Execution time: %lf | Scenario %d\n",time_taken,s+1);
printf("Essential info has been recorded to the text file.\n");
//system("pause");
printf("\n\n");
}
else if ( choice == '5' ){
CopyArray(points, copypoints);
printf("Sorting your Data using Insertion-sort.\n");
InsertionSort(copypoints);
printf("\n\n Finished Sorting!\n\n");
printf("Before: ");
PrintArray(points);
printf("\nAfter: ");
PrintArray(copypoints);
printf("\n\n");
double time_taken = (double)(end - start) / (double)(CLOCKS_PER_SEC);
fprintf(fp, "Insertion-sort = Execution time: %lf | Scenario %d\n",time_taken,s+1);
printf("Essential info has been recorded to the text file.\n");
//system("pause");
printf("\n\n");
}
else if ( choice == '6' ){
CopyArray(points, copypoints);
printf("Sorting your Data using Shell-sort.\n");
ShellSort(copypoints);
printf("\n\n Finished Sorting!\n\n");
printf("Before: ");
PrintArray(points);
printf("\nAfter: ");
PrintArray(copypoints);
printf("\n\n");
double time_taken = (double)(end - start) / (double)(CLOCKS_PER_SEC);
fprintf(fp, "Shell-sort = Execution time: %lf | Scenario %d\n",time_taken,s+1);
printf("Essential info has been recorded to the text file.\n");
//system("pause");
printf("\n\n");
}
else if ( choice == '7' ){
printf("Printing your Array...\n");
PrintArray(array, P);
}
else if ( choice == 'E' ){
printf("Exiting Scenario.\n\n\n");
break;
}
else{
printf("\n\n Please enter 1-7 or E!\n\n");
}
//Change scenario question so you can record all the scenarios in a row
if (s == 9 && choice != 'E'){
printf("\nYou're on Scenario 10. Would you like to change the scenario?\n 1. YES\n 2. NO\n");
printf("Choice: ");
scanf("%d", &input);
if(input == 1){
printf("Change to scenario:");
scanf("%d", &input);
s = input -2;
printf("\n\n");
break;
}
printf("\n\n");
}
}while( choice != 'E' );
fclose(fp);
fclose(file);
return 0;
}
//I stole this because mine just wouldn't work
char SortMenu() {
char ch1 = ' ';
char ch2[] = {' ', ' ', ' '};
// system("clear"); // For DOS-based system("cls");
printf("\n\n");
//Menu for the users
printf("Please sellect what sorting system you would like to use.\n"
"1. Bubble-sort\n"
"2. Quick-sort\n"
"3. Merge-sort\n"
"4. Selection-sort\n"
"5. Insertion sort\n"
"6. Shell sort\n"
"7. Print Array\n"
"E. Exit current scenario\n"
"Q. Quit Program\n");
printf("Choice: ");
scanf("%s", ch2);
ch1 = ch2[0];
return ch1;
}
void PrintArray(Point A[]) {
long int i;
printf("\n\n");
for (i=0; i < P; i++) {
printf("Read point: %s %s %s %d\n", A[i].name, A[i].surname, A[i].email, A[i].donation);
}
printf("\n\n");
//system("pause");
}
void CopyArray(Point Source[], Point Copy[]) {
int i;
for (i=0; i < P; i++)
Copy[i] = Source[i];
}
void swap(Point* A, Point* B ) {
Point temp = *A;
*A = *B;
*B = temp;
}
double power(int base, int exponent) {
double result;
int i;
result = 1;
for (i = 1; i <= exponent; i++)
result = result * base;
return result;
}
void BubbleSort(Point A[]) {
start = clock();
int j, last, t;
Point temp;
last = 1;
do {
t = 0;
for (j = (P-1); j >= last; j--) {
if (A[j-1].donation > A[j].donation) {
swap(&A[j-1], &A[j]);
t = j;
}
}
last = t;
} while (t > 0);
end = clock();
}
void QuickSort(long int A[], int bottom, int top) {
start = clock();
int i, j, x, k;
i = bottom;
j = top;
k = (bottom + top) / 2;
x = A[k];
do {
while (A[i] < x)
i++;
while (A[j] > x)
j--;
if (i <= j) {
swap(&A[i], &A[j]);
i++;
j--;
}
} while (i <= j);
if (bottom < j)
QuickSort(A, bottom, j);
if (i < top)
QuickSort(A, i, top);
end = clock();
}
void SelectionSort(long int A[]) {
start = clock();
int i, j, x, k;
for (i=(P-1); i >= 1; i--) {
x = A[i];
k = i;
for (j = i; j >= 0; j--) {
if (A[j] > x) {
k = j;
x = A[j];
}
}
swap(&A[i], &A[k]);
}
end = clock();
}
void InsertionSort(long int A[]) {
start = clock();
int i, j, t;
for (j=1; j < P; j++) {
i = j - 1;
t = A[j];
do {
if (t >= A[i])
break;
A[i+1] = A[i];
i--;
} while (i >= 0);
A[i+1] = t;
}
end = clock();
}
void ShellSort(long int A[]) {
start = clock();
int i, j, s, pas, qq;
double h[20];
for (i=0; i <= 19; i++)
h[i] = power(2, i);
for (s=19; s >= 0; s--) {
pas = h[s];
for (j = pas; j < P; j++) {
i = j - pas;
qq = A[j];
do {
if (qq >= A[i])
break;
A[i+pas] = A[i];
i = i - pas;
} while (i >= 0);
A[i+pas] = qq;
}
}
end = clock();
}
void MergeSort(long int A[], int l, int r)
{
start = clock();
if (l < r) {
int m = l + (r - l) / 2;
MergeSort(A, l, m);
MergeSort(A, m + 1, r);
Merge(A, l, m, r);
}
end = clock();
}
void Merge(long int A[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = A[l + i];
for (j = 0; j < n2; j++)
R[j] = A[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
A[k] = L[i];
i++;
}
else {
A[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
A[k] = L[i];
i++;
k++;
}
while (j < n2) {
A[k] = R[j];
j++;
k++;
}
}
I have this assignment for University where I have to take data out of a .csv and then sort it with 6 different sorting algorithms and measure the execution time.
The problems that I've encountered and I'm stuck at are the following:
1.When I transfer all the data to a struct array at the end of every row there's an awkard 0 (look at the screenshots bellow)
2.I've tried passing the array from bubblesort fuction to swap function but it doesn't swap them (I think it might be because of the previous problem)
The .csv looks like this, a row has a name, surname, email, and an intiger
"Eric","Tucker","e.tucker#randatmail.com",4591
"Catherine","Hawkins","c.hawkins#randatmail.com",9325
"Bruce","Harper","b.harper#randatmail.com",8371
"Kristian","Bailey","k.bailey#randatmail.com",437
"Garry","Harrison","g.harrison#randatmail.com",976
"Rafael","Farrell","r.farrell#randatmail.com",8685
"Penelope","Craig","p.craig#randatmail.com",1224
This is the output of the first problem I was talking about
Read point: "Rafael","Phillips","r.phillips#randatmail.com",7092 92 0
Read point: "Lucia","Carroll","l.carroll#randatmail.com",6879 0
Read point: "Lyndon","Roberts","l.roberts#randatmail.com",6460 0
If you need more info from me, let me know and I'll provide it to you

How to save in a file in C

#include "Header.h"
void mostraTabuleiro(int lin, int col, int **m){
int i, j, l;
char k = 65;
for (l = 1; l <= col; l++){
printf("\t%c", k);
k++;
}
printf("\n");
for (i = 1; i <= lin; i++){
printf("%d", i);
for (j = 1; j <= col; j++){
if (i == lin && j == col)
printf("\t[X]");
else
printf("\t[*] ");
}
printf("\n");
}
}
and now i want to save the mostratabuleiro in a file and i started doing this
int GuardaFicheiro(char *nome_fich){
FILE *fnovo;
char *novo_fich = "estadosTabuleiro.txt";
fnovo = fopen(novo_fich, "wt");
if (fnovo == NULL){
printf("Erro ao abrir o ficehiro de texto %s para escrita.\n", novo_fich);
return;
}
//mostraTabuleiro(6, 8, Tabuleiro, fnovo);
fclose(fnovo);
}
if i put fprintf in the function mostraTabuleiro after that it doesn't appera anything and the file is blank.
This should be corrected
fnovo = fopen(novo_fich, "wt");
into:
fnovo = fopen(novo_fich, "w");
after that use fprintf();
fprintf(fnovo, /*source char * */);
You may please note that you should ask question on S.O. in this style. You can also read this.
void mostraTabuleiro(int lin, int col, int **m, FILE *fnovo) {
int i, j, k;
for (k = 1; k <= col; k++){
fprintf(fnovo, "\t%d", k);
}
fprintf(fnovo, "\n");
for (i = 1; i <= lin; i++){
fprintf(fnovo, "%d", i);
for (j = 1; j <= col; j++){
if (i == lin && j == col)
fprintf(fnovo, "\t[X]");
else
fprintf(fnovo, "\t[*] ");
}
fprintf(fnovo, "\n");
}
}
and
void GuardaFicheiro(int lines, int columns, int **m){
FILE *fnovo;
char *novo_fich = "estadosTabuleiro.txt";
fnovo = fopen(novo_fich, "wt");
if(fnovo == NULL){
printf("error opening file %s for writing.\n", novo_fich);
return;
}
// this will write to the file
mostraTabuleiro(lines, columns, m, fnovo);
// this will write on screen : stdout
mostraTabuleiro(lines, columns, m, stdout);
fclose(fnovo);
}
and
int iniciaJogo() {
tabuleiro tab;
int i, j, m, n;
int res = 0;
int **Tabuleiro;
int cont = 0;
int iteracoes = 0;
do{
do{
printf("Dimensoes do ambiente\nLines\n");
scanf("%d", &tab.N_Linhas);
} while (tab.N_Linhas < 4 || tab.N_Linhas > 8);
do{
printf("Columns\n");
scanf("%d", &tab.N_Colunas);
} while (tab.N_Colunas < 6 || tab.N_Colunas > 10);
} while (tab.N_Linhas > tab.N_Colunas);
Tabuleiro = criaTabuleiro(tab.N_Linhas, tab.N_Colunas);
GuardaFicheiro(tab.N_Linhas, tab.N_Colunas, Tabuleiro);
//mostraTabuleiro(tab.N_Linhas, tab.N_Colunas, Tabuleiro, fnovo);
}
And, may be main like:
int main(){
iniciaJogo();
return 0;
}
I am sure the above code would work for you. But you should read little about C Programming - functions, structures, and FileIO.
There are many unused variables in your code, you may check compiling your code with gcc -Wall -Wextra yourFileName.c

How do I continuously write to and read from the same file in C

I am trying to store the coordinates (x, y) in a text file, where x denotes the row number and y the column. I will then use this information to change the element of the array to 1, and the others will remain at 0. I want to do this multiple times to the same .txt file. I'm trying to simulate the famous Game of Life. The trouble is that is only successfully reads from the file once so the array cannot update, and so the array just prints off the same stuff as before.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ROWS 30
#define COLS 20
#define ITERATIONS 6
int fillBoard(int b[ROWS][COLS]);
int newRound(FILE *i, int b[ROWS][COLS]);
int cellAliveOrDead(FILE *p, int b[ROWS][COLS]);
int cellBirth(FILE *p, int b[ROWS][COLS]);
int main(void) {
int board[ROWS][COLS];
char fileName[] = "#life 1.06";
int i, j;
int x, y;
int round = 0;
FILE *fp, *ifp;
char fileFormat[11];
int p, o;
fp = fopen("life.txt", "r");
ifp = fopen("life2.txt", "r");
if (fp == NULL) {
printf("Error\n");
exit(1);
}
if (ifp == NULL) {
exit(1);
}
fillBoard(board);
fgets(fileFormat, 11, fp); // read input from first line
if (strcmp(fileName, fileFormat) == 0) {
while (fscanf(fp, "%d %d", &x, &y) == 2) {
board[x][y] = 1;
printf("x:%d y:%d\n", x, y);
}
} else {
printf("Wrong file");
}
// print game with the starter cells
for (i = 0; i < ROWS; i++) {
printf("\n");
for (j = 0; j < COLS; j++) {
printf("%d", board[i][j]);
}
}
newRound(ifp, board);
fclose(fp);
fclose(ifp);
return(0);
}
int newRound(FILE *ij, int b[ROWS][COLS]) {
int round = 0;
int x, y;
int i, j;
while (round < ITERATIONS) {
printf("\n");
cellAliveOrDead(ij, b);
cellBirth(ij, b);
fillBoard(b);
while (fscanf(ij, "%d %d", &x, &y) == 2) {
b[x][y] = 1;
printf("x:%d y:%d\n", x, y);
}
round++;
// print game round 2
for (i = 0; i < ROWS; i++) {
printf("\n");
for (j = 0; j < COLS; j++) {
printf("%d", b[i][j]);
}
}
}
}
int fillBoard(int b[ROWS][COLS]) {
int i, j;
for(i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
b[i][j] = 0;
}
}
}
int cellAliveOrDead(FILE *p, int b[ROWS][COLS]) {
int count;
int i, j;
for(i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
count = 0;
if(b[i][j] == 1) {
if(b[i-1][j] == 1) count++;
if(b[i+1][j] == 1) count++;
if(b[i][j-1] == 1) count++;
if(b[i][j+1] == 1) count++;
if(b[i-1][j-1] == 1) count++;
if(b[i-1][j+1] == 1) count++;
if(b[i+1][j-1] == 1) count++;
if(b[i+1][j+1] == 1) count++;
if(count == 2 || count == 3) {
//b[i][j] = 1;
fprintf(p, "%d %d\n", i, j);
}
}
}
}
}
int cellBirth(FILE *p, int b[ROWS][COLS]) {
int count;
int i, j;
for(i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
count = 0;
if (b[i][j] == 0) {
if(b[i-1][j] == 1) count++;
if(b[i+1][j] == 1) count++;
if(b[i][j-1] == 1) count++;
if(b[i][j+1] == 1) count++;
if(b[i-1][j-1] == 1) count++;
if(b[i-1][j+1] == 1) count++;
if(b[i+1][j-1] == 1) count++;
if(b[i+1][j+1] == 1) count++;
if (count == 3) {
//b[i][j] = 1;
fprintf(p, "%d %d\n", i, j);
}
}
}
}
}
The simplest answer would be to use 2 files.
Write into a FILE* A. Then close it and read it as FILE* B, and write into a FILE* A. Repeat.
The other method would be to use fseek. This is quite risky as the chances of you rewriting on top of essential information is quite possible. But follow this answer, and you should be fine.
Also see this if you are curious about how fseek works.

C error: expected declaration or statement at end of input

Alright, so from what I've seen, it seems these errors usually show up whenever there's a semicolon missing, or a misplaced curly-brace or something of that nature. I'm surely just missing it somehow, but I'm not able to find where the error is, or if it is due to an error of that sort. This error in pointing toward line 235, so the end of the last function.
This is the code
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAX 100
void display_menu();
int check_option(int option);
int check_size(int size);
void initialize_2Darray(int x[][MAX], int size);
void print_2Darray(int x[][MAX], int size);
void initialize_1Darray(int y[], int size);
void print_1Darray(int y[], int size);
int search_min(int x[][MAX], int r, int c, int size);
int count_match(int x[][MAX], int y[], int size, int r);
int closest_row(int x[][MAX], int y[], int size);
void sort_1Darray(int y[], int size);
void sort_2Darray(int x[][MAX], int size);
int main()
{
int size, r, c, option;
int exit = 0; //exits program when = 1
int x[MAX][MAX], y[MAX];
srand(time(NULL));
printf("Enter the size: ");
scanf("%d", &size);
while(check_size(size) == 0) {
printf("\nInvalid input, enter the size of the array again: ");
scanf("%d", &size);
}
while(exit != 6) {
initialize_2Darray(x, size);
initialize_1Darray(y, size);
display_menu();
scanf("%d", &option);
while(check_option(option) == 0) {
printf("Invalid option, enter again: ");
scanf("%d", &option);
}
//Search Min Operation
if(option == 1) {
print_2Darray(x, size);
printf("Enter the row: ");
scanf("%d", &r);
printf("\nEnter the col: ");
scanf("%d", &c);
printf("The smallest number present in row %d and col %d is %d", r, c, search_min(x, r, c, size));
}
//Count Matches Op.
else if(option == 2) {
printf("Count Matches Operation\n\n2D array\n");
print_2Darray(x, size);
printf("\n1D array\n");
print_1Darray(y, size);
printf("\nEnter the row: ");
scanf("%d", &r);
if(count_match(x, y, size, r) > 0)
printf("There are %d matches from 1D array present in 2D array", count_match(x, y, size, r));
else
printf("There are no numbers from 1D array present in 2D array");
}
//Closest Row Op.
else if(option == 3) {
printf("\nClosest Row Operation\n\n2D array\n");
print_2Darray(x, size);
printf("\n1D array\n");
print_1Darray(y, size);
printf("Row closest to the 1D array is row %d", closest_row(x, y, size));
}
//Sort 1D Array Op.
else if(option == 4) {
printf("Sort 1D Array Operation\n\n1D Array before sorting:\n");
print_1Darray(y, size);
sort_1Darray(y, size);
printf("\n\n1D Array after sorting:\n");
print_1Darray(y, size);
}
//Sort 2D Array Op.
else if(option == 5) {
printf("\nSort 2D Array Option\n\n2D Array before sorting:\n");
print_2Darray(x, size);
sort_2Darray(x, size);
printf("\n\n2D Array after sorting:\n");
print_2Darray(x, size);
}
//Exit
else if(option == 6)
exit = 6;
}
return 0;
}
void display_menu()
{
printf("\nArray operations, your options are:\n\n1: Search Min\n2: Count Matches\n3: Closest Row\n4: Sort 1D Array\n5: Sort 2D Array\n6: Exit\nEnter the operation you want to perform: ");
}
int check_option(int option)
{
if(option > 0 && option < 7)
return 1;
else
return 0;
}
int check_size(int size)
{
if(size > 0 && size <= 100)
return 1;
else
return 0;
}
void initialize_2Darray(int x[][MAX], int size)
{
int i, s; //counters
for(i=0; i < size; i++) {
for(s=0; s < size; s++) {
x[i][s] = rand()%10;
}
}
}
void print_2Darray(int x[][MAX], int size)
{
int i, s; //counters
for(i=0; i < size; i++) {
printf("\n");
for(s=0; s < size; s++) {
printf("%d ", x[i][s]);
}
}
printf("\n");
}
void initialize_1Darray(int y[], int size)
{
int i, r;
for(i=0; i < size; i++) {
r = rand()%10;
y[i] = r;
}
}
void print_1Darray(int y[], int size)
{
int i;
//Prints array values until (s)ize is reached
for(i=0; i < size; i++) {
printf("%d ", y[i]);
}
}
int search_min(int x[][MAX], int r, int c, int size)
{
int i, j; //counters
int min = 9;
for(i=0; i < size; i++) {
if(x[r][i] < min) {
min = x[r][i];
}
}
for(j=0; j < size; j++) {
if(x[j][c] < min) {
min = x[j][c];
}
}
return min;
}
int count_match(int x[][MAX], int y[], int size, int r)
{
int i, j, count;
for(i=0; i < size; i++) {
for(j=0; j < size; j++) {
if(y[i] == x[r][j])
count++;
}
return count;
}
int closest_row(int x[][MAX], int y[], int size)
{
int l, i, j; //counters
int sum = 0;
int dif = 0;
int row, totaldif; //best matching row & total dif
for(l=0; l < size; l++) {
for(i=0; i < size; i++) {
for(j=0; j < size; j++) {
dif = abs(y[j] - x[i][j]);
sum += dif;
}
if(sum < totaldif) {
totaldif = sum;
row = i;
}
sum = 0;
}
}
return row;
}
void sort_1Darray(int y[], int size)
{
int a, b, temp;
//Loops through the array, swapping values until in proper order of ascension
for(a = 0; a < size; a++) {
for(b = 0; b < size-1; b++) {
if(y[b] > y[b+1]) {
temp = y[b+1];
y[b+1] = y[b];
y[b] = temp;
}
}
}
}
void sort_2Darray(int x[][MAX], int size)
{
int a, b, c, temp;
//Loops through the array, swapping values until in proper order of ascension
for(c=0; c < size; c++) {
for(a = 0; a < size; a++) {
for(b = 0; b < size-1; b++) {
if(x[a][b] > x[a][b+1]) {
temp = x[a][b+1];
x[a][b+1] = x[a][b];
x[a][b] = temp;
}
}
}
}
}
Run your code through indent. It can help you find this sort of problem very quickly.
Here's the output from your code. As you can see, the problem is caused by a missing brace at the end of count_match():
int
count_match(int x[][MAX], int y[], int size, int r)
{
int i , j, count;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
if (y[i] == x[r][j])
count++;
}
return count;
}
/*** CLOSING BRACE MISSING HERE ***/
int closest_row(int x[][MAX], int y[], int size){
int l , i, j;
//counters

Resources