How to count Up and Down using For Loop - c

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.

Related

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

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]++;
}
}

Shortest path with Bellman & Ford algorithm

I want to implement Shortest path with Bellman & Ford algorithm. my idea is I use adjacent matrix
to save the information of digraph. If I want to find the shorest path of vertex i ,then I observe in-
degree of vertex i by the ith column of adjacent matrix ,and I save the shortest value of ith column
to a variable "min".if I want to find the shorest path from source vertex v to vertex i.
I only compare distance[i] with (distance[j]+ min ), because "min" is equal to adjmatrix[j][i].
In addition, I make the traverse(source, k) function to comfirm which vertex we can reach it in k
steps and use the data structure stack to save information of vertex i. I assume to that i'll get all the
shortest path from source vertex v to every vertex o graph except v itself. But the consequence after
compiling isn't that I expected. I finally got distance[i], 0 <= i < MAX_VERTEX, 1000,-1, 5, 5, 0 ,1000,
1000, respectively. What is my problem? Thanks for answer.
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX 7
#define FALSE 0
#define TRUE 1
#define MAX_DISTANCE_LIMIT 1000
#define MAX_STACK_LENGTH 100
#define MIN(x, y) ((x) < (y) ? x : y)
int stack[MAX_STACK_LENGTH];
int top = -1; //pointer to top of stack.
int adjmatrix[MAX_VERTEX][MAX_VERTEX];
short found[MAX_VERTEX]; //traverse(v ,k) : reach the vertex i By taking the k steps at most
int distance[MAX_VERTEX]; //save the shortest path that source v to every vertex i
int init_matrix(void);
void BellmanFord(int v); //v is source
void traverse(int v,int times);
void push(int vertex);
int pop(void);
int main(void){
int i,j;
init_matrix(); //initial matrix and found[] array
for(i = 0; i < MAX_VERTEX; i++){
for(j = 0; j < MAX_VERTEX; j++)
printf("%2d ", adjmatrix[i][j]);
printf("\n");
}
printf("--------------------------------------------------\n");
BellmanFord(0);
for(i = 0; i < MAX_VERTEX; i++)
printf("%4d ", i);
printf("\n");
for(i = 0; i < MAX_VERTEX; i++)
printf("%4d ", distance[i]);
return 0;
}
int init_matrix(void){
int num_edge = 0, i, j, w;
for(i = 0; i < MAX_VERTEX; i++){
found[i] = FALSE;
for(j = 0; j < MAX_VERTEX; j++)
adjmatrix[i][j] = MAX_DISTANCE_LIMIT; //set a large value to the entry of the vertice which aren't adjacent
}
while(1){
printf("enter the vertices and weight of edge connected between them(w,tail,head): ");
scanf("%d%d%d", &w, &i, &j);
if((i >= MAX_VERTEX) || (j >= MAX_VERTEX)){
fprintf(stderr, "index if the matrix should be less than %d");
exit(EXIT_FAILURE);
}
if(w == 0) break;
adjmatrix[i][j] = w;
num_edge++;
}
return num_edge;
}
void BellmanFord(int v){//compute all shortest path from v to every vertex ,and allow edge is negative
int i, k, min = MAX_DISTANCE_LIMIT, j, minpos;
for(int i = 0; i < MAX_VERTEX; i++)
distance[i] = adjmatrix[v][i]; //value of dist"1"
for(k = 2; k <= MAX_VERTEX - 1; k++){
traverse(v,k); //traverse(v ,k)will set found[i] that we can reach in k steps TRUE.
for(i = 0; i < MAX_VERTEX; i++ ){
if( found[i] == FALSE)
continue;
for(j = 0; j < MAX_VERTEX; j++)
if(adjmatrix[j][i]+distance[j] < min) {
min = adjmatrix[j][i]+distance[j];
minpos = j;
}
distance[i] = MIN(distance[i],adjmatrix[minpos][i]+distance[j]);
}
for(i = 0; i < MAX_VERTEX; i++ ) //initial found array to FALSE
found[i] = FALSE;
}
}
void traverse(int v,int times){
int i, next_order ,count = 0;
if (times == 0) return ;
for(i = 0; i < MAX_VERTEX; i++){
if((adjmatrix[v][i] != MAX_DISTANCE_LIMIT) && (!found[i])){
found[i] = TRUE;
if(times == 1)
return;
push(i);
count++;
}
}
for(i = 0; i < count; i++){
next_order = pop();
traverse(next_order,times-1);
}
return;
}
void push(int vertex){
if(top >= MAX_STACK_LENGTH){
fprintf(stderr, "The stack is full.");
exit(EXIT_FAILURE);
}
stack[++top] = vertex;
}
int pop(void){
if(top == -1){
fprintf(stderr, "The stack is empty.\n");
exit(EXIT_FAILURE);
}
else
return stack[top--];
}
/************************************
*graph information (w,tail,head)
input
6 0 1
5 0 2
5 0 3
-1 1 4
1 2 4
-2 2 1
-2 3 2
-1 3 5
3 5 6
3 4 6
0 0 0 //end the input
************************************
adjmatrix:
0 6 5 5 0 0 0
0 0 0 0 -1 0 0
0 -2 0 0 1 0 0
0 0 -2 0 0 -1 0
0 0 0 0 0 0 3
0 0 0 0 0 0 3
0 0 0 0 0 0 0
**************************************/

How could I align my output to the center?

#include<stdio.h>
int main()
{
int n ;
printf("Input the number of rows: ");
scanf("%d", &n);
for(int i = 1; i <= n ; i++)
{
for(int j = 1 ; j <= i ; j++)
{
if(j == i + 1)
{
break;
}
printf("%3d", j);
}
for(int j = i - 1 ; j > 0; j--)
{
if(j == 0)
{
break;
}
printf("%3d", j);
}
printf("\n");
}
}
Program session
Number of rows for this output n = 3
My output:
1
1 2 1
1 2 3 2 1
Preferred output:
1
1 2 1
1 2 3 2 1
This here is an exercise where I have to print a pyramid of numbers where the central number of the pyramid is the number of the row. I understand the logic but as you can see I have not been able to fulfill the task successfully. Any tips?
As pointed out by #WeatherWane, you need to add logic to add extra spaces. If you notice carefully, number of spaces on each line(excluding padding you add with %3d is equal to 3 * (n - i)). You can create a simple method like this to add spacing:
void addSpaces(int N, int currentIndex, int padding) {
for (int index = currentIndex; index < N; index++)
for (int spaces = 0; spaces < padding; spaces++)
printf(" ");
}
then you can call it from your first for loop like this:
for(int i = 1; i <= n ; i++)
{
addSpaces(n, i, 3);
for(int j = 1 ; j <= i ; j++)
{
// ...
I tested it and it seems to align it correctly:
c-posts : $ ./a.out
Input the number of rows: 5
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1

Queen puzzle 4x4

I am trying to solve this Queen problem of placing 4 queen in 4x4 matrix . I know it can be solved with backtracking algorithm . However i have not studied that and i am trying to solve it with my current knowledge . So what i am trying is to generate all possible combination of Queen in 4x4 matrix and print only one which cannot cancel each other .
1) For generating all combination , i am using rand function .
However there is obviously fault in my above coding . There are some outputs with only three '1' instead of four '1' . I am not able to eliminate this problem .
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
srand(time(NULL));
int ar[30][30], i , j , a , b , c = -1, d = -1, k = 0;
while (1)
{
for (i = 0 ; i < 4 ; i++)
{
for (j = 0 ; j < 4 ; j++)
{
ar[i][j] = 0;
}
}
for (i = 0 ; i < 2 ; i++)
{
for (j = 0 ; j < 2 ; j++)
{
a = rand() % 3 ;
b = rand() % 3 ;
if (a != c || b != d)
{
ar[a][b] = 1 ; // here 1 = Queen
c = a ;
d = b;
}
}
}
}
}
2) Also is there any way i can reduce the time complexity using only these method ?
Instead of using temporary variables to check whether the array is filled, use the array itself!
for (i = 0 ; i < 2 ; i++)
{
for (j = 0 ; j < 2 ; j++)
{
a = rand() % 3 ;
b = rand() % 3 ;
if (ar[a][b] == 0)
{
ar[a][b] = 1 ; // here 1 = Queen
}
}
}
Your problem is that the inner loop will execute 4 times and you can only control 1 repeat with variables c and d.
Let's say a is 1 and b is 1: you make c = 1 and d = 1.
then a is 2 and b is 1 ... making c = 2 and d = 1.
then if a is 1 and b is 1 again, you cannot check for duplicate.
(1) You check only that a queen isn't placed on the same square as the last queen you placed. Remove the variables c and d and check whether ar[a][b] is still zero.
(2) Your scatter approach will produce many set-ups that are misses. Especially, because you don't enforce that ther cannot be any queens on the same rank and file. (In addition, rand() % 3 produces random values from 0 to 2, inclusively. You will never get a non-threatening configuration that way.)
If you want to use your random (bogosort) approach, you could use a one-dimensional array where the index is the rank and the number is the file where a queen is. Then you start with:
int queen[4] = {0, 1, 2, 3};
and shuffle the array. For 4 queens, that will yield 4! = 24 possibile configurations. You could try to iterate through them systematically.
The following is the brute force, backtracking code for the 8 queens problem, asked some time ago. Just change 8 to 4:
int checkBoard(int board[8][8]);
int putQueens(int board[8][8], int nQueens);
void printBoard(int board[8][8]);
int eightQueens(void)
{
int board[8][8];
memset(board, 0, sizeof(int)*64);
if (putQueens(board, 0)) {
printBoard(board);
return (1);
}
return(0);
}
int putQueens(int board[8][8], int nQueens)
{
int i, j;
for (i=0; i<8; i++) {
for (j=0; j<8; j++) {
if (board[i][j]==0) {
board[i][j]= 1;
if (checkBoard(board)) {
if (nQueens==7) return(1);
if (putQueens(board, nQueens+1)) return(1);
}
board[i][j]= 0;
}
}
}
return(0);
}
int checkBoard(int board[8][8])
{
int i, j;
for (i=0; i<8; i++) {
for (j=0; j<8; j++) {
if (board[i][j]) {
int ii, jj;
for (ii=i+1; ii<8; ii++) {
if (board[ii][j]) return(0);
}
for (jj=j+1; jj<8; jj++) {
if (board[i][jj]) return(0);
}
for (ii=i+1, jj=j+1; ii<8 && jj<8; ii++, jj++) {
if (board[ii][jj]) return(0);
}
for (ii=i-1, jj=j-1; ii>0 && jj>0; ii--, jj--) {
if (board[ii][jj]) return(0);
}
for (ii=i-1, jj=j+1; ii>0 && jj<8; ii--, jj++) {
if (board[ii][jj]) return(0);
}
for (ii=i+1, jj=j-1; ii<8 && jj>0; ii++, jj--) {
if (board[ii][jj]) return(0);
}
}
}
}
return (1);
}
void printBoard(int board[8][8])
{
int i,j;
printf(" ");
for (j=0; j<8; j++) printf(" %1d",j+1); printf("\n");
for (i=0; i<8; i++) {
printf("%1d ",i+1);
for (j=0; j<8; j++)
printf(" %1c", board[i][j]==0? '-':'*');
printf("\n");
}
}

reading from a file to create array minesweeper code

I'm having trouble with this assignment. I am supposed to create minesweeper-ish arrays. It reads in a file:
100
3
0 0
2 1
7 7
10
0 0
0 1
0 2
0 3
0 4
0 5
0 6
0 7
7 0
7 1
the first line is the number of boards (100) the second line is the number of bombs in the board. the 2 integer lines are the row and column, respectively of the location of the bomb.
my problem is it only prins out one board and my second question is how do i switch the 9 to a * in the board?
thank you!
#include <stdio.h>
#define BOARD_SIZE 8
#define BOMB 9
int main() {
FILE *fp;
fp = fopen("mine.txt","r");
int numberBoards = 0;
int numberMines = 0;
int col;
int row;
int currentBoard = 0;
// first row is going to be the number of boards
fscanf(fp,"%d",&numberBoards);
while ( fscanf(fp,"%d",&numberMines) > 0 ) {
int i,j;
// start board with all zeros
int board[BOARD_SIZE][BOARD_SIZE] = { {0} };
currentBoard++;
printf("Board #%d:\n",currentBoard);
//Read in the mines and set them
for (i=0; i<numberMines; i++) {
fscanf(fp,"%d %d",&col,&row);
board[col-1][row-1] = BOMB;
}
//mine proximity
for (i=0; i<BOARD_SIZE; i++) {
for (j=0; j<BOARD_SIZE; j++) {
if ( board[i][j] == BOMB ) {
//Square to the left
if (j > 0 && board[i][j-1] != BOMB) {
board[i][j-1]++;
}
//Square to the right
if (j < 0 && board [i][j+1] !=BOMB){
board [i][j+1]++;
}
//Square to the top
if (i > 0 && board [i-1][j] !=BOMB) {
board [i-1][j]++;
}
//Square to the bottom
if ( i < 0 && board [i+1][j] !=BOMB){
board [i+1][j]++;
}
}
}
//Print out the minesweeper board
for (i=0; i<BOARD_SIZE; i++) {
for (j=0; j<BOARD_SIZE; j++) {
printf("%d ",board[i][j]);
}
printf("\n");
}
printf("\n");
}
//Close the file.
fclose(fp);
return 0;
}
}
The fclose and return should not be in the while loop - that is why it is creating just one board.
I don't understand your question about printing multiple boards. To print a * instead of a 9:
if ( board[i][j] == 9 ) printf("* ");
else printf("%d ",board[i][j]);

Resources