How I can consider number as a value 1 in C language? - c

I have a problem in my C program. I need to write a histogram of numbers. If the number on the input will be outside the interval [1, 9], consider such a number as the value 1. I don't understand why it doesn't work.
#include <stdio.h>
#include <stdlib.h>
void printHistogram_vertical(int *hist, int n);
int main()
{
int i, j;
int inputValue;
scanf("%d", &inputValue);
int hist[inputValue];
for (i = 0; i < inputValue; ++i)
{
scanf("%d", &hist[i]);
}
int results[10] = {0};
for (i = 0; i < 10; ++i)
{
for (j = 0; j < inputValue; ++j)
{
if (hist[j] >= 10 && hist[j] < 1)
{
results[j] == 1;
}
if (hist[j] == i)
{
results[i]++;
}
}
}
return 0;
}
void printHistogram_vertical(int *hist, int n)
{
int i, j;
for (i = 1; i < n; i++)
{
printf(" %d ", i);
for (j = 0; j < hist[i]; ++j)
{
printf("#");
}
printf("\n");
}
}
Input:
9
3 3 2 3 7 1 1 4 10
My Output:
1 ##
2 #
3 ###
4 #
5
6
7 #
8
9
The correct output:
1 ###
2 #
3 ###
4 #
5
6
7 #
8
9
If the number is bigger than 10 and smaller than 1 it should count this number as 1. I write this function:
for (i = 0; i < 10; ++i)
{
for (j = 0; j < inputValue; ++j)
{
if (hist[j] >= 10 && hist[j] < 1)
{
results[j] == 1;
}
if (hist[j] == i)
{
results[i]++;
}
}
}

There are 2 problems with following condition:
if (hist[j] >= 10 && hist[j] < 1)
{
results[j] == 1;
}
The comparison is broken. Value cannot be above 9 AND below 1 at the same time. It should be OR instead.
What should be increment of index 1, is actually comparison == of wrong index.
Replacement:
if (hist[j] >= 10 || hist[j] < 1)
{
results[1]++;
}
But double for loop construction is more complicated than it needs to be. It could be replaced with single for loop:
for (j = 0; j < inputValue; ++j) {
int value = hist[j];
if(value >= 1 && value <= 9) {
results[value]++;
}
else {
results[1]++;
}
}

Related

I want to print the following pyramid of number pattern

1
2 4
3 5 7
6 8 10 12
9 11 13 15 17
Following is the code in which I am not able to print the pyramid:-
int main()
{
int i,j;
for(i=1;i<=5;i++){
for(j=1;j<=i;j++){
printf("%d ",i*j);
}
printf("\n");
}
return 0;
}
You need to track both even and odd numbers .
#include <stdio.h>
int main()
{
int even=1,odd=2;
int n=10;
for (int i = 1; i <= n; i++)
{
int a= (i % 2 == 0);
for (int j = 1; j < i; j++)
{
if(a)
{
printf("%d ",even);
}
else
{
printf("%d ",odd);
}
even += a ? 2 : 0;
odd += a ? 0 : 2;
}
printf("\n");
}
return 0;
}
Not very clean and compact algorithm but sth like this would work:
#include <stdio.h>
#include <stdlib.h>
int main() {
char tmp[10];
int n = 0, row = 1, odd = 1, even = 2, c = 0, selectOdd, fin = 0;
printf("maximum number: ");
scanf("%s", tmp);
n = atoi(tmp);
if (n != 0) {
while (fin < 2) {
selectOdd = row % 2;
c = row;
if (selectOdd) {
while (c != 0) {
printf("%3d", odd);
odd += 2;
if (odd > n) {
fin++;
break;
}
c--;
}
}
else {
while (c != 0) {
printf("%3d", even);
even += 2;
if (even > n) {
fin++;
break;
}
c--;
}
}
printf("\n");
row++;
}
}
return 0;
}
it's simple
your algorithm is odd, even, odd,... and so on
so you start with odd number until reach line number
for next line is even and you can find start number with this
you just need find number at start of line and continue print number number
in each step you just need
num += 2;
remember 'lineIndex' start from 1
num = (lineIndex - 1) * 2 + lineIndex % 2;
this is a full code
#include <stdio.h>
int main(){
int numIndex;
int lineIndex;
int num;
for (lineIndex = 1; lineIndex <= 5; lineIndex++) {
num = (lineIndex - 1) * 2 + lineIndex % 2;
for (numIndex = 0; numIndex < lineIndex; numIndex++) {
printf("%2d ", num);
num += 2;
}
printf("\n");
}
}

How to count Up and Down using For Loop

I want to get output like this using nested for loops:
0 0
0 1
0 2
0 3
1 3
1 2
1 1
1 0
2 0
2 1
2 2
2 3
3 3
3 2
3 1
3 0
So I came up with this solution:
for(i=0;i<4;i++) {
if(i == 1){
for(j=3;j>=0;--j) {
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}else if(i == 3){
for(j=3;j>=0;--j) {
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}else{
for(j=0;j<4;j++) {
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}
}
This works but is there way to do this without if conditions inside the loops?
Here you are.
#include <stdio.h>
int main(void)
{
const int N = 3;
for ( int i = 0; i <= N; i++ )
{
for ( int j = 0; j <= N; j++ )
{
printf( "%d %d\n", i , i % 2 == 0 ? j : N - j );
}
}
return 0;
}
The program output is
0 0
0 1
0 2
0 3
1 3
1 2
1 1
1 0
2 0
2 1
2 2
2 3
3 3
3 2
3 1
3 0
Or the loops can be written like
const int N = 4;
for ( int i = 0; i < N; i++ )
{
for ( int j = 0; j < N; j++ )
{
printf( "%d %d\n", i , i % 2 == 0 ? j : N - j - 1 );
}
}
I am not the Arduino guy, but as its similar to C and this question is more about the algorithm let me sketch an approach in C:
#define LEFT_START (0)
#define LEFT_END (3)
#define RIGHT_START (0)
#define RIGHT_END (3)
enum DIRECTION {
DOWN = -1,
UP = 1
};
int main(void)
{
for (int direction = UP, i = LEFT_START, j = RIGHT_START - sign;
i <= LEFT_END;
++i, direction *= -1)
{
for (j += direction;
j >= RIGHT_START && j <= RIGHT_END;
j += direction)
{
printf("%d %d\n", i, j);
}
}
}
No if/then, not explicitly, nor implicitly via ternary-operator, BTW. ;)
I don't know what your purpose was, but you need to use if statement. This code will do the thing you want
int n =3;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
for (int i=0; i<=n; i++){
if(i%2 == 0){
for (int j=0; j<=n; j++){
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}
else{
for (int j=n; j>=0; j--){
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}
}
}
The output looks like this,
Defining variables/constant n, i, j is entirely up to you based on your project. This code is just a simple demonstration.

how to check if a matrix has the same value in a row or column in C

I have a homework problem. It requires us to make a matrix based on user's input. For example : if user input 4 so the matrix will be 4 X 4. After that, the program will check if the matrix has the same value in a row or column. and it will give yes or no output.
For example :
input :
2
1 2
2 1
Output :
Yes
(because that matrix doesnt has a same value in a row or a column.)
Input 2 :
3
4 5 6
7 8 9
7 3 3
Output :
No
(Because that matrix have same values in a row or column (3 & 3 and 7 & 7)
Input 3:
2
1 2
3 2
Output :
No
(because that matrix have same value on column 1.)
Input 4
2
1 1
3 4
Output :
No
(because that matrix has same value in first row(1 1)
I have tried to do that, but some 'cases' still doesnt work. For example, i tried to include a count in my code but some of the count is not true.
example :
input :
4
3 4 5 6
2 3 4 5
6 5 6 3
5 4 6 3
OUTPUT :
No
count : 2
(it supposed to be 3 because it has the same value which are 6 (on row 3), 6 on column 3, and 3 on column 4.)
#include "stdio.h"
int main()
{
int matrix[500][500];
int testcase;
int count = 0;
scanf("%d",&testcase); getchar();
for(unsigned i = 0; i < testcase; i++) {
for(unsigned j = 0; j < testcase; j++) {
scanf("%d",&matrix[i][j]); getchar();
}
}
// printf("[0,0] = %c",matrix[0][0]);
// printf("\n[0,1] = %c",matrix[0][1]);
// printf("\n[1,0] = %c",matrix[1][0]);
// printf("\n[1,1] = %c",matrix[1][1]);
for(unsigned i = 0; i < testcase; i++) {
for(unsigned j = 0; j < testcase; j++) {
if(matrix[i][j] == matrix[i][j+1]) {
count = count + 1;
}
else if(matrix[i][j] == matrix[i+1][j]) {
count = count + 1;
}
}
}
if(count > 0) {
printf("No\n");
} else{
printf("Yes\n");
}
printf("Count : %d\n",count );
getchar();
return 0;
}
As I see you check if 2 numbers of the same value differ only one column or one row here:
if(matrix[i][j] == matrix[i][j+1]) {
count = count + 1;
}
else if(matrix[i][j] == matrix[i+1][j]) {
count = count + 1;
}
I think that you might need a temp variable so that you can scan each line and then each column separately , for example:
temp = matrix[i][j];
if(checkRow(temp, i, j, matrix, testcase) == true) count++;
if(checkColumn(temp, i, j, matrix, testcase) == true) count++;
and the checkRow would be something like this:
bool checkRow(int temp, int row, int col, int matrix[][500], int size)
{
for(int i=col; i < size;)
{
if(temp == matrix[row][i]) return true;
}
return false;
}
and respectively you will build the checkColumn function.
EDIT:
Since you told me you haven't learned how to use functions yet, this would be your final program. It works and I might suggest that the final test case should output "count = 4" since there is a case that you might missed.
Here is the code:
#include "stdio.h"
int main()
{
int matrix[500][500];
int testcase;
int count = 0;
scanf("%d",&testcase); getchar();
int temp;
for(unsigned i = 0; i < testcase; i++) {
for(unsigned j = 0; j < testcase; j++) {
scanf("%d",&matrix[i][j]); getchar();
}
}
// printf("[0,0] = %c",matrix[0][0]);
// printf("\n[0,1] = %c",matrix[0][1]);
// printf("\n[1,0] = %c",matrix[1][0]);
// printf("\n[1,1] = %c",matrix[1][1]);
for(unsigned i = 0; i < testcase; i++) {
for(unsigned j = 0; j < testcase; j++) {
temp = matrix[i][j];
//Scan current row
for(unsigned k = j+1; k < testcase; k++)
{
if(temp == matrix[i][k])
{
count++;
break;
}
}
//Scan current column
for(unsigned k = i+1; k < testcase; k++)
{
if(temp == matrix[k][j])
{
count ++;
break;
}
}
}
}
if(count > 0) {
printf("No\n");
} else{
printf("Yes\n");
}
printf("Count : %d\n",count );
getchar();
return 0;
}
May I suggest that before you copy the code you must understand the algorithm that lies behind it. It's simple and brute force thinking.

Sudoku code checker in c [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm writing a Sudoku solution checker for a class and I've hit a wall.
I'm at the point where I'm checking if I can see whether or individual columns and rows are unique. For some reason the code works on 4x4 grids but as soon as I get up to a 5x5 grid or higher (goal is to get to a 9x9 grid) the program starts to print out that it had failed even when it should succeed.
Any help would be much needed, I want need a point in the right direction or where I should look into
Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i, j, n, k, p, q;
int fail;
int array[5][5];
int check[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int a = 0;
char *output = NULL;
scanf("%d", &n);
// memory allocated for yes or no at end
output = malloc(sizeof(int) * (n));
while (a < n)
{
fail = 0;
// create this 2D array
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
scanf("%d", &(array[i][j]));
}
}
// seeing if row is unique
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
for (k = 0; k < 5; k++)
{
if (array[i][k] == array[i][k+1])
fail += 1;
}
}
}
// seeing if column is unique
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
for (k = 0; k < 5; k++)
{
if (array[k][j] == array[k+1][j])
fail += 1;
}
}
}
/* for (WHAT DO I DO FOR ROWS)
{
for (WHAT DO I DO FOR ROWS AGAIN BUT REPLACE ROWS WITH COLUMNS)
{
for (NOW IM LOST)
}
}
*/
// success or failure? 0 success, 1 failure
if (fail >= 1)
output[a] = 1;
else
output[a] = 0;
a++;
}
// print out yah or nah
for (i = 0; i < n; i++)
{
if (output[i] == 0)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
Forget my for loop for the grids, I'll work on that once I figure out how to get the columns and rows working correctly.
Thanks for the help!
Here is an input that would cause the program to fail when it should succeed
1
1 2 3 4 5
2 3 4 5 1
3 4 5 1 2
4 5 1 2 3
5 1 2 3 4
output would be
NO
EDIT: It is now working with a 9x9 grid! Thanks for the help!
#include <stdio.h>
#include <stdlib.h>
#define SIDE_LENGTH 9
int main ()
{
int i, j, n, k, p, q;
int fail;
int array[SIDE_LENGTH][SIDE_LENGTH];
int check[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int a = 0;
char *output = NULL;
scanf("%d", &n);
// memory allocated for yes or no at end
output = malloc(sizeof(int) * (n));
while (a < n)
{
fail = 0;
// create this 2D array
for (i = 0; i < SIDE_LENGTH; i++)
{
for (j = 0; j < SIDE_LENGTH; j++)
{
scanf("%d", &(array[i][j]));
}
}
// seeing if row is unique
for (i = 0; i < SIDE_LENGTH; i++)
{
for (j = 0; j < SIDE_LENGTH; j++)
{
for (k = 0; k < SIDE_LENGTH - 1; k++)
{
if (array[i][k] == array[i][k+1])
fail += 1;
}
}
}
// seeing if column is unique
for (i = 0; i < SIDE_LENGTH; i++)
{
for (j = 0; j < SIDE_LENGTH; j++)
{
for (k = 0; k < SIDE_LENGTH - 1; k++)
{
if (array[k][j] == array[k+1][j])
fail += 1;
}
}
}
/* for (WHAT DO I DO FOR ROWS)
{
for (WHAT DO I DO FOR ROWS AGAIN BUT REPLACE ROWS WITH COLUMNS)
{
for (NOW IM LOST)
}
}
*/
// success or failure? 0 success, 1 failure
if (fail >= 1)
output[a] = 1;
else
output[a] = 0;
a++;
}
// print out yah or nah
for (i = 0; i < n; i++)
{
if (output[i] == 0)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
input:
1
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9 1
3 4 5 6 7 8 9 1 2
4 5 6 7 8 9 1 2 3
5 6 7 8 9 1 2 3 4
6 7 8 9 1 2 3 4 5
7 8 9 1 2 3 4 5 6
8 9 1 2 3 4 5 6 7
9 1 2 3 4 5 6 7 8
#ameyCU helped find the error in my code
Setting k to one less than what i and j were set to allowed the code to successfully run on any X*X sized grid. Because k is one less than i and j, it won't try to access a part of the array that hasn't been allocated yet which is where my problem lied.
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
for (k = 0; k < 5; k++)
{
if (array[i][k] == array[i][k+1])
fail += 1;
}
}
}
Despite the overwriting of the array as already pointed out, your logic is flawed. You don't use j at all. You are just comparing the same values five times.
The problem is the comparison.
if (array[i][k] == array[i][k+1])
I think you are using i as row and column index, then using j to iterate for duplicates. k will be what you compare against so ...
/* compare if j'th value is same as k'th value */
if (j != k && array[i][j] == array[i][k]) /* Don't check same against same */
the second comparison should be
/* compare if j'th value is same as k'th value */
if (j != k && array[j][i] == array[k][i]) /* Don't check same against same */
That would fix your overflow (k+1) bug, and get you going.
The squares could be fixed with
struct co_ords {
int x;
int y;
};
struct co_ords boxes[][9] = {{ {0,0}, {0,1}, {0,2},
{1,0}, {1,1}, {1,2},
{2,0}, {2,1}, {2,2}
},
{ {3,0}, {3,1}, {3,2},
{4,0}, {4,1}, {4,2},
{5,0}, {5,1}, {5,2} },
... /* more boxes go here */
{ {6,6}, {6,7}, {6,8},
{7,6}, {7,7}, {7,8},
{8,6}, {8,7}, {8,8} }};
for( i = 0; i < 9; i++ ){
struct co_ords current_box * = boxes[i];
for( j = 0; j < 9; j++ ) {
for( k = 0; k < 9; k++ ){
if( j != k && array[ current_box[j].x ][ current_box[j].y] == array[ current_box[k].x ][ current_box[k].y] )
fail += 1;
}
}
}
int array[5][5];
so the array is allocated as 5x5
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
scanf("%d", &(array[i][j]));
}
}
and you are indexing from 0 to 5 ..
to use larger, please do replace all those "5"s with a precompiler definition.
#define SUDOKU_SIDE_LENGTH 5
...
int array[SUDOKU_SIDE_LENGTH ][SUDOKU_SIDE_LENGTH ];
...
for (i = 0; i < SUDOKU_SIDE_LENGTH ; i++)
{
for (j = 0; j < SUDOKU_SIDE_LENGTH ; j++)
{
scanf("%d", &(array[i][j]));
}
}
etc.. that will ensure that you always allocate enough space for the array.
adjust size on the definition, not in the code..

Clockwise Print of a 4X4 matrix in c

hi I am trying to print a 4 x 4 matrix in clockwise direction,
Input:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Expected output is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
My code is:
int MAXR=3,MAXC=3,MINR=0,MINC=0;
while(MINR < MAXR && MINC < MAXC)
{
for(i=MINC;i<=MAXC;i++)
{
printf("%d ",arr[MINR][i]);
}
for(j=MINR+1;j<=MAXR;j++)
{
printf("%d ",arr[j][MAXC]);
}
for(i=MAXC-1;i>=MINC;i--)
{
printf("%d ",arr[MAXR][i]);
}
MINR++;
if((MINR%2)==0)
{
MINC=MINC+2;
}
//MAXR--;
//MAXC--;
//printf("\nMAXR=%d MINR=%d\n",MAXR,MINR);
for(j=MAXR-1;j>MINR;j--)
{
printf("%d ",arr[j][MINC]);
}
MAXR--;
MAXC--;
}
But output is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 11
Please help me to fix the bug!
Thanks!
output is:
I hope you have fixed your defect by now. But it was a fun spec, so here is my version:
gcc (GCC) 4.7.3: gcc -Wall -Wextra -std=c99 spiral.c
#include <stdio.h>
int main() {
int matrix[4][4] = {
{ 1, 2, 3, 4 },
{ 12, 13, 14, 5 },
{ 11, 16, 15, 6 },
{ 10, 9, 8, 7 } };
int edge = sizeof(matrix[0]) / sizeof(int) - 1;
int i = 0;
int j = 0;
printf("%d ", matrix[i][j]);
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[i][++j]); }
while (0 < edge) {
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[++i][j]); }
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[i][--j]); }
--edge;
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[--i][j]); }
for (int c = 0; c < edge; ++c) { printf("%d ", matrix[i][++j]); }
--edge;
}
return 0;
}
My approach was to write out the sequence of required changes to i and j and find the pattern. What I found was that the pattern appeared after the first line, so I did that as a separate initial step.
The following code will help you to print of a matrix of any size (rows/cols) clockwisely.
void printMatrixClockwisely(int** numbers, int rows, int columns)
{
if(numbers == NULL || columns <= 0 || rows <= 0)
return;
int start = 0;
while(columns > start * 2 && rows > start * 2)
{
PrintMatrixInCircle(numbers, columns, rows, start);
++start;
}
}
void printNumber(int number)
{
printf("%d\t", number);
}
void PrintMatrixInCircle(int** numbers, int columns, int rows, int start)
{
int endX = columns - 1 - start;
int endY = rows - 1 - start;
// print a row from left to right
for(int i = start; i <= endX; ++i)
{
int number = numbers[start][i];
printNumber(number);
}
// print a col from up to down
if(start < endY)
{
for(int i = start + 1; i <= endY; ++i)
{
int number = numbers[i][endX];
printNumber(number);
}
}
// print a row from right to left
if(start < endX && start < endY)
{
for(int i = endX - 1; i >= start; --i)
{
int number = numbers[endY][i];
printNumber(number);
}
}
// print a col from down to up
if(start < endX && start < endY - 1)
{
for(int i = endY - 1; i >= start + 1; --i)
{
int number = numbers[i][start];
printNumber(number);
}
}
}

Resources