this program is trying to read in a 2D array (5x10) of char, and compress them. Such that (aaacccfeee -> a3c3f1e3). I have some trouble with my output, and I can't figure out where's the problem.
Here's the code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define SIZE1 5
#define SIZE2 10
void compress(char data[SIZE1][SIZE2]);
int main ()
{
int row, col;
char qn2[SIZE1][SIZE2];
printf("\nEnter your data (5x10 of characters): \n");
for (row = 0; row < SIZE1; ++row)
for (col = 0; col < SIZE2; ++col)
scanf("%c", &qn2[row][col]);
fflush(stdin);
compress(qn2);
return 0;
}
void compress(char data[SIZE1][SIZE2])
{
int row, col, count = 0;
char tempChar = data[0][0];
printf("\nThe compression output: \n");
for (row = 0; row < SIZE1; row++)
{
for (col = 0; col < SIZE2; col++)
{
if (data[row][col] == tempChar)
{
count ++;
}
else
{
printf("%c%d", tempChar, count);
tempChar = data[row][col];
count = 1;
}
} printf("\n");
}
}
Expected output:
Enter your data (5x10 of characters):
aaacccdeee
fffggghiii
jjjkkklmmm
nnnooopqqq
rrrssstuuu
The compression output:
a3c3d1e3
f3g3h1i3
j3k3l1m3
n3o3p1q3
r3s3t1u3
Output I got instead:
The compression output:
a3c3d1
e3f3g3h1
i3j3k3l1
m3n3o3p1
q3r3s3t1u3
Try this:
for (row = 0; row < SIZE1; row++)
{
for (col = 0; col < SIZE2; col++)
{
if (data[row][col] == tempChar)
{
count ++;
}
else
{
printf("%c", tempChar);
printf("%d", count);
tempChar = data[row][col];
count = 1;
}
}
}
if(count!=0) //need to print the last sequence of repeated characters.
{
printf("%c", tempChar);
printf("%d", count);
}
Related
I want to take integers like that
1 2 3
4 5 6
Than I should sum them with same line like
1+4=5
2+5=7
3+6=9
And I should print 5 7 9.
To do this I tried to take values from user in this way but only first scanf is running and the other is not.What is the reason for that and how can I fix it or is there any other useful way to do that?(How many value will user enter is unknown.)
char s1[21];
scanf("%[^\n]", s1);
char s2[21];
scanf("%[^\n]", s2);
for(int i =0; i<b1; i++)
printf("%d ",s1[i]+s2[i]);
You should read into integer arrays, not strings. scanf() will skip over the whitespace between the numbers.
int numbers1[b1], numbers2[b1];
for (int i = 0; i < b1; i++) {
scanf("%d", &numbers1[i]);
}
for (int i = 0; i < b1; i++) {
scanf("%d", &numbers2[i]);
}
for (int i = 0; i < b1; i++) {
printf("%d ", numbers1[i] + number2[i]);
}
printf("\n");
The following program doesn't work. I should debug it, but I am too lazy for that. However take a look. It might help giving you some idea.
#include <stdio.h>
#define SIZE 50
int main() {
int n[SIZE][SIZE], row, col, sum, i, j;
int numCol; // column of first row
int yeah = 1; // tells wether all the rows have the same number of columns
char c = 'c'; // to check for the newline
for(row = 0; row < SIZE; row++) {
for(col = 0; c != '\n' && col < SIZE; col++) {
if( scanf("%d%c", &n[row][col], &c) < 2 && row > 0 ) {
if( col != numCol - 1) {
yeah = 0;
}
goto outside_pls; // the only way to exit the outer loop;
}
} // end inner for
if( row == 0 ) {
numCol = col;
}
else if( col != numCol ) {
yeah = 0;
}
} // end outer for
outside_pls:
if( yeah ) {
printf("%d %d\n", row, col);
for(j = 0; j < col; j++) {
sum = 0;
for(i = 0; i < row; i++) {
sum += n[i][j];
}
printf("%d ", sum);
}
}
else {
puts("Number of columns doesn't match");
}
return 0;
}
You should take the index you are in and get all of your variables in the same index in all of your arrays.
Code should look like this
for(int i = 0; i< array1.length(); i++){
sum = array1[i]+array2[i]+.......;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N_MAX 10
#define N_MIN 2
#define TEMPSIZE 1024
float RowSum(float **matrix, int sizearray,int row) {
float sum;
for (int j=0 ; j <= row; j++) {
sum = 0;
for (int i=0 ; i < sizearray; i++) {
sum = sum + matrix[j][i];
}
}
return sum;
}
float ColSum(float **matrix, int sizearray, int col) {
float sum;
for (int j = 0; j <= col; j++) {
sum = 0;
for (int i = 0; i < sizearray; i++) {
sum = sum + matrix[i][j];
}
}
return sum;
}
int RepNum(int arraysize, float **matrix) {
int i, j, counter = 0;
int temparray[N_MAX*N_MAX];
for (i = 0; i < N_MAX*N_MAX; i++) {
temparray[i] = 0;
}
for (i = 0; i < arraysize; i++) {
for (j = 0; j < arraysize; j++) {
temparray[(int)matrix[i][j]]++;
}
}
for (i = 1; i < arraysize*arraysize; i++) {
if (temparray[i] > 1)
counter++;
}
return counter;
}
void PrintArray(float **matrix, int arraysize) {
for (int i = 0; i<arraysize; i++)
{
for (int j = 0; j<arraysize; j++)
printf("%3d ", (int)matrix[i][j]);
printf("\n");
}
}
int CheckInt(float **matrix, int arraysize) {
int counter = 0;
for (int i = 0; i < arraysize; i++) {
for (int j = 0; j < arraysize; j++) {
if (((int)matrix[i][j]) != matrix[i][j])
counter++;
}
}
return counter;
}
void main() {
printf("Hello! this program will help you to find out if you have a magic square!\nPlease enter your matrix order and following it the numbers you'd like to check: \n");
float **matrix;
char input[TEMPSIZE];
int sizear = 0;
float correctsum = 0.0;
int counter = 0, row, column;
fgets(input, TEMPSIZE, stdin);
char* str = strstr(input, " ");
if (str == 0)
return;
str[0] = 0;
str++;
sizear = atof(input);
if (sizear > N_MAX || sizear < N_MIN)
{
printf("ERROR: The matrix size cannot be %d size. \n", sizear);
exit(0);
}
matrix = (float**)calloc(1, sizear * sizeof(float*));
for (column = 0; column < sizear; column++)
{
matrix[column] = (float*)calloc(1, sizear * sizeof(float));
}
for (row = 0; row < sizear; row++)
{
for (column = 0; column < sizear; column++)
{
char* temp = strstr(str, " ");
if (temp == 0) /*gets the last number*/
{
++counter;
matrix[row][column] = atof(str);
goto end;
}
if (atof(temp) <= sizear*sizear && atof(temp) > 0) { /*puts all numbers in matrix*/
temp[0] = 0;
matrix[row][column] = atof(str);
str = temp + 1;
++counter;
}
else {
printf("you cannot enter the number %.3f \n", atof(temp));
exit(0);
}
}
}
end:
if (counter > sizear*sizear) {
printf("you've entered %d numbers, while you should've enter %d numners \n", counter, sizear*sizear);
}
else if (counter < sizear*sizear) {
printf("you've entered %d numbers, while you should've enter %d numners \n", counter, sizear*sizear);
}
else if (counter == sizear*sizear) {
correctsum = (float)((sizear*(sizear*sizear + 1)) / 2);
float row = RowSum(matrix, sizear, 0);
float coul = ColSum(matrix, sizear, 0);
if (row == coul && row== correctsum && coul==correctsum && RepNum(sizear, matrix) ==0 && CheckInt(matrix,sizear)==0) {
printf("It's a magic matrix!\n");
PrintArray(matrix, sizear);
}
else {
printf("Not a magic square:\n");
if (row != coul && row != correctsum && coul != correctsum) {
printf("* Coloums and rows sum do not match.\n");
}
if (RepNum(sizear, matrix) != 0) {
printf("* There are repeating numbers.\n");
}
if (CheckInt(matrix, sizear) != 0) {
printf("* One of the numbers or more you've entered isn't integer.\n");
}
}
}
for (column = 0; column < sizear; column++)
{
free(matrix[column]);
}
free(matrix);
}
When I hit more than sizearrayXsizearray numbers it doesn't add into the counter and stops at sizearrayXsizearray counting. Can anyone point out why it doesn't count it?
The exercise asked to check if the input is a magic square (sum rows=columns=diagonals), making sure there are no duplicates, only int numbers and that I don't enter more or less than sizearrayXsizearray numbers. The input from the user should look like 3 1 2 3 4 5 6 7 8 9 where the first number (here it is 3) is the array size and the rest are the numbers that would be checked as a magic square.
When I hit more than sizearrayXsizearray numbers it doesn't add into the counter and stops at sizearrayXsizearray counting. Can anyone point out why it doesn't count it?
Sure, it's simple: the counter is incremented in the loops
for (row = 0; row < sizear; row++)
{
for (column = 0; column < sizear; column++)
{
…
}
}
- the inner statements are run through (at most) sizear × sizear times, so the counter, starting from 0, cannot reach a higher value.
I have a program that is getting a segmentation fault. The program is a magic square program and asks users for the size of a square (a matrix) and then for the numbers of the square by row. I am using a pointer to point to the array in the declareArray function to reference where it is declared in the main function. I want to keep the pointer in order to practice using them, even though I know I can make the program work without pointers. I think the pointer is the problem here but I cant find what I am doing wrong with it.
here is the code:
int main(void)
{
int *arr[SIZE][SIZE] = "\0";
declareArray(&arr);
declareArray();
return 0;
}
//main logic
int declareArray(int *arr[SIZE][SIZE])
{
//variables
int rowNumber = 0;
int dimension = 0;
//int arr[SIZE][SIZE] = {0};
int row, col;
int sum, sum1, sum2;
int flag = 0;
//ask for input of squares
printf("Please enter the dimension of the square: ");
//makes sure the size is between 1 and 15 for the dimension of the square
if(scanf("%d", &dimension) != 1 || dimension >= 15 || dimension < 1)
{
printf("invalid input\n");
return 1;
}
//enter the data
//array rows
for(row = 0; row < dimension; ++row)
{
printf("Please enter the data for row %d: ", ++rowNumber);
//array columns
for(col = 0; col < dimension; ++col)
{
//store the user input
scanf("%2d", &*arr[row][col]);
}
}
printf("\n");
printf("Here is the square");
printf("\n");
//print the square
//array rows
for(row = 0; row < dimension; ++row)
{
//array columns
for(col = 0; col < dimension; ++col)
{
printf("%d", *arr[row][col]);
}
printf("\n");
}
//Checks Sum of diagonal elements
sum = 0;
for (row = 0; row < dimension; row++) {
for (col = 0; col < dimension; col++) {
if (row == col)
sum = sum + *arr[row][col];
}
}
//Checks Sum of Rows
for (row = 0; row < dimension; row++) {
sum1 = 0;
for (col = 0; col < dimension; col++) {
sum1 = sum1 + *arr[row][col];
}
if (sum == sum1)
flag = 1;
else {
flag = 0;
break;
}
}
//Checks sum of Columns
for (row = 0; row < dimension; row++) {
sum2 = 0;
for (col = 0; col < dimension; col++) {
sum2 = sum2 + *arr[col][row];
}
if (sum == sum2)
flag = 1;
else {
flag = 0;
break;
}
}
//if the sums match, it will print a success message with the constant
//if the sums dont match, a fail message will appear
if (flag == 1)
printf("\nTHE SQUARE IS A MAGIC SQUARE WITH A CONSTANT OF %d \n", sum);
else
printf("\nThe Square is not a magic square \n");
return 0;
}
I can see few issues here
int *arr[SIZE][SIZE] = "\0"; // this wont compile
declareArray(&arr); // needless
declareArray();
---
int arr[SIZE][SIZE] = {};
declareArray(arr);
//declareArray();
Declare function
int declareArray(int *arr[SIZE][SIZE]) // because function call changed
---
int declareArray(int arr[SIZE][SIZE])
finally in printf and scanf remove the * operator not needed anymore
as in
scanf("%2d", &*arr[row][col]); // remove *
---
scanf("%2d", &arr[row][col]);
printf("%d", *arr[row][col]); // remove *
---
printf("%d", arr[row][col]);
sum = sum + *arr[row][col]; // remove *
---
sum = sum + arr[row][col];
Note that when you declare an array, the name of the array is a pointer to the first element of the array:
&arr[0] == arr.
The argument passed to the declareArray function is an array of pointers to integers, therefore the space needed for the pointers was allocated yet the space for the actual ints was not, so when you are trying to scan an integer to the address pointed to by arr[row][col], you are trying to write to the address that it holds, 0 in your case , and address 0 is most likely out of the data segment, hence the segment_fault.
What should you do then?
Allocate the space needed with malloc(), assign the address returned to arr[row][col] and then scanf() as shown below, or alternatively, and quite simpler and better use an int array and simply assign the integer to arr[row][col] as shown in the answer above
#include <stdio.h>
#include <stdlib.h>
#define SIZE 15
int declareArray(int * arr[SIZE][SIZE]);
int main(void)
{
int * arr[SIZE][SIZE] = {0};
declareArray(arr);
return 0;
}
//main logic
int declareArray(int * arr[SIZE][SIZE])
{
//variables
int rowNumber = 0;
int dimension = 0;
int row, col;
int sum, sum1, sum2;
int flag = 0;
int * myVal;
//ask for input of squares
printf("Please enter the dimension of the square: ");
//makes sure the size is between 1 and 15 for the dimension of the square
if(scanf("%d", &dimension) != 1 || dimension >= 15 || dimension < 1)
{
printf("invalid input\n");
return 1;
}
//enter the data
//array rows
for(row = 0; row < dimension; ++row)
{
printf("Please enter the data for row %d: ", ++rowNumber);
//array columns
for(col = 0; col < dimension; ++col)
{
printf("insert data to row %d col %d: ", rowNumber, col+1);
arr[row][col] = (int *) malloc(sizeof(int));
scanf("%2d", arr[row][col] );
}
}
printf("\n");
printf("Here is the square");
printf("\n");
//print the square
//array rows
for(row = 0; row < dimension; ++row)
{
//array columns
for(col = 0; col < dimension; ++col)
{
printf("%d", *arr[row][col]);
}
printf("\n");
}
//Checks Sum of diagonal elements
sum = 0;
for (row = 0; row < dimension; row++) {
for (col = 0; col < dimension; col++) {
if (row == col)
sum = sum + *arr[row][col];
}
}
//Checks Sum of Rows
for (row = 0; row < dimension; row++) {
sum1 = 0;
for (col = 0; col < dimension; col++) {
sum1 = sum1 + *arr[row][col];
}
if (sum == sum1)
flag = 1;
else {
flag = 0;
break;
}
}
//Checks sum of Columns
for (row = 0; row < dimension; row++) {
sum2 = 0;
for (col = 0; col < dimension; col++) {
sum2 = sum2 + *arr[col][row];
}
if (sum == sum2)
flag = 1;
else {
flag = 0;
break;
}
}
//if the sums match, it will print a success message with the constant
//if the sums dont match, a fail message will appear
if (flag == 1)
printf("\nTHE SQUARE IS A MAGIC SQUARE WITH A CONSTANT OF %d \n", sum);
else
printf("\nThe Square is not a magic square \n");
return 0;
}
I am making a simple command-line Candy Crush game. This is my code below. I'm writing it in xCode then running it in Terminal using pico. The gameboard prints out correctly, but it doesn't put Xs on the board. Instead the board is printed and then a segmentation fault occurs.
//
// Assignment 3
//
#include <stdio.h>`enter code here`
//function headers
void displayOriginal (int img[10][10], int col, int row);
void removeOriginal (int img[10][10], int col, int row);
int main(){
//declare variables and array
int col = 0;
int row = 0;
int img[10][10];
//call functions
displayOriginal (img, col,row);
removeOriginal (img, col, row);
displayOriginal (img,col,row);
return 0;
}
//function for displaying gameboard
void displayOriginal (int img[10][10], int col, int row){
for(row = 0; row < 10; row++){//to create rows 0-9
for(col = 0; col < 10; col++){//to create columns 0-9
scanf("%d", &img[row][col]);
}
}
printf(" 0 1 2 3 4 5 6 7 8 9\n");//adds labels to x axis
for(row = 0; row < 10; row++){
printf("%d", row);//add labels to y axis
for(col = 0; col < 10; col++){
if (img[row][col] == 1){ //red
printf("\x1b[41m ");
} else if (img[row][col] == 2){//green
printf("\x1b[42m ");
} else if (img[row][col] == 3){//purple
printf("\x1b[43m ");
} else if (img[row][col] == 4){//blue
printf("\x1b[44m ");
} else if (img[row][col] == 5){//magenta
printf("\x1b[45m ");
} else if (img[row][col] == 0){
printf("XX");
}
printf("\x1b[m"); //white
}
printf("\n");
}
}
//function to label where the X's go
void removeOriginal (int img[10][10], int col, int row){
//variables
int previous = -10;
int temp;
int tally = 1;
for(row = 0; row < 10; row++){
for(col = 0; col < 10; col++){
if (previous == img[row][col]){//if previous block =current then add 1
tally++;
} else {
tally = 1;//return to 1 if previous does not equal current
}
if (tally >= 3){
previous = img[row][col];
for (temp = (tally-1); temp >= 0; temp--){
img [row-temp][col] = 0;
}
} else {
previous = img [row][col];
}
printf("Row %d Col %d Tally %d", row, col, tally);
}
}
}
Are you certain that row >= temp in this section? If it isn't, img[-1][col] will result in a segmentation fault.
if (tally >= 3)
{
previous = img[row][col];
for (temp = (tally-1); temp >= 0; temp--)
{
img [row-temp][col] = 0;
}
}
I have a 5 x 10 char matrix and I am suppose to compress it like a run length encoding.
printf("Enter your data (5x10) of characters: \n");
for (i = 0; i < SIZE1; i++)
for (j = 0; j < SIZE2; j++)
scanf("%c", &matrix2[i][j]);
printf("\n");
compress(matrix2);
break;
void compress(char data[SIZE1][SIZE2])
{
int row, column, count=1;
for (row = 0; row < SIZE1; row++)
{
for (column = 0; column < SIZE2; column++)
{
if (data[row][column] == data[row][column + 1])
{
count++;
}
else
{
printf("%c%d", data[row][column], count);
count = 1;
}
}
}
}
This is my code but I do not understand why my output will always have a 1 in front.
Input:
aaabbbcccd
aabbccddee
aaaaaaaaaa
abcabcabca
aaabbbcccc
output:
a3b3c3d1
1a2b2c2d2e2
1a10
1a1b1c1a1b1c1a1b1c1a1
1a3b3
expected output:
a3b3c3d1
a2b2c2d2e2
a10
a1b1c1a1b1c1a1b1c1a1
a3b3c4
It is counting the newline character too.
I believe the commenters are suggesting a change like so:
printf("Enter your data (5x10) of characters: \n");
for (i = 0; i < SIZE1; i++)
for (j = 0; j < SIZE2; j++)
scanf("%c", &matrix2[i][j]);
printf("\n");
compress(matrix2);
break;
void compress(char data[SIZE1][SIZE2])
{
int row, column, count=1;
for (row = 0; row < SIZE1; row++)
{
for (column = 0; column < SIZE2; column++)
{
if (data[row][column] == data[row][column + 1])
{
count++;
}
else
{
if (data[row][column] != '\n')
{
printf("%c%d", data[row][column], count);
count = 1;
}
}
}
}
}
Change the data entry. Have it deal with \n and error detection.
printf("Enter your data (%dx%d) of characters: \n", SIZE1, SIZE2);
for (i = 0; i < SIZE1; i++) {
char buffer[(SIZE2 + 2)*2]; // Consider IO buffers 2x the needed size
if (fgets(buffer, sizeof buffer, stdin) == NULL)
Handle_EndOfFileOrIOError();
size_t len = strlen(buffer);
if (len != SIZE2+1 || buffer[len-1] != '\n')
Handle_UnexpectDataLengthError(buffer, len);
for (j = 0; j < SIZE2; j++) {
matrix2[i][j] = buffer[j];
}
// or simply memcpy(matrix2[i], buffer, SIZE2);
printf("\n");
compress(matrix2);
break;