I was wondering how can i make a c program that only prints the black positions on a chess board for example:
- = (empty space);
-| A8 - C8 - E8 - G8 -
-| - B7 - D7 - F7 - H7
-| A6 - C6 - E6 - G6 -
-| - B5 - D5 - F5 - H5
-| A4 - C4 - E4 - G4 -
-| - B3 - D3 - F3 - H3
-| A2 - C2 - E2 - G2 -
-| - B1 - D1 - F1 - H1
#include <stdio.h>
int main()
{
int n = 8;
int i,j;
char a[100][100] = {
"A8"," ","C8"," ","E8"," ","G8",
" ","B7"," ","D7"," ","F8"," ","H7",
"A6"," ","C6"," ","E6"," ","G6",
" ","B5"," ","D5"," ","F5"," ","H5",
"A4"," ","C4"," ","E4"," ","G4",
" ","B3"," ","D3"," ","F3"," ","H3",
"A2"," ","C2"," ","E2"," ","G2",
" ","B1"," ","D1"," ","F1"," ","H1",
};
for(i = 0;i < n;i++){
for(j = 0;j < n;j++){
printf("%c ",a[i][j]);
}
printf("\n");
}
return 0;
}
There is absolutely no reason to use a 2D array here.
Representation on the screen and memory layout of data structures don't need to match. As an example:
#include <stdio.h>
int main(void)
{
unsigned int i;
for (i = 0; i < 64; i++) {
if ((((i % 8) + (i / 8)) & 1) == 0) {
printf("%c%u ", 'A' + (i % 8), 8 - (i / 8));
} else {
printf(" ");
}
if ((i % 8) == 7) {
printf("\n");
}
}
return 0;
}
This code isn't pretty but it works. It doesn't even use an array.
All you need is some operations like division and modulus to determine row and column. Then you need to notice that squares with coordinates (X,Y) share the same color if X+Y is even.
The code isn't pretty, but it uses very simple logic. As an exercise, within the for loop, try to get the coordinates X and Y into separate variables. Then it might be easier to understand.
Please read the comments marked with // CHANGE HERE.
char a[100][100] creates 100 character strings each of max length 99 (1 character for null terminator '\0' (Imagine 100 rows with 99 columns)
#include <stdio.h>
int main()
{
//int n = 8; // CHANGE HERE - unused
int i;
// CHANGE HERE
// 1. Replaced ' ' with ' ' (two spaces)
// 2. Added ' ' after G for white H column cells
char a[100][100] = {
"A8"," ","C8"," ","E8"," ","G8"," ",
" ","B7"," ","D7"," ","F8"," ","H7",
"A6"," ","C6"," ","E6"," ","G6"," ",
" ","B5"," ","D5"," ","F5"," ","H5",
"A4"," ","C4"," ","E4"," ","G4"," ",
" ","B3"," ","D3"," ","F3"," ","H3",
"A2"," ","C2"," ","E2"," ","G2"," ",
" ","B1"," ","D1"," ","F1"," ","H1",
};
// CHANGE HERE - chess board has 64 cells
for (i = 0; i < 64; i++) {
// CHANGE HERE - print a new line after every 8 entries
if (i != 0 && i % 8 == 0)
{
printf("\n");
}
printf("%s", a[i]);
}
printf("\n");
return 0;
}
Related
I'm trying to create a 4-variable kmap but I am not sure how to create the left side (00->10) of kmap. Thank you for your help. :)
Here is my code
#include <stdio.h>
int main()
{
unsigned int w, x, y, z;
unsigned int f;
/* Print header for K-map. */
printf(" yz \n");
printf(" 00 01 11 10 \n");
printf(" ______________\n");
/* row-printing loop */
for (w = 0; 2 > w; w = w + 1)
{
for (x = 0; 2 > x; x++){
printf("w=%u%x | ", w,x);
}
/* Loop over input variable b in binary order. */
for (y = 0; 2 > y; y = y + 1)
{
/* Loop over d in binary order.*/
for (z = 0; 2 > z; z = z + 1)
{
/* Use variables b and d to calculate *
* input variable c (iterated in *
* Gray code order). */
/* CALCULATE c HERE. */
y = x^z;
/* Calculate and print one K-map entry *
* (function F(a,b,c) ). */
/* INSERT CODE HERE. */
f = (w|~x) & (~w|~y) & (w|~x|~y) & 1;
printf("%u ", f);
}
}
/* End of row reached: print a newline character. */
printf("\n");
}
return 0;
}
For further information, this is what I have to do "Demonstrate its work using f(w,x,y,z) = xy'+w'z and g(w,x,y,z) = w'xyz'+ w + x' as examples"
You have four variables x,y,w,z so you need a kmap with 4x4=16 fields, like the second example in https://www.geeksforgeeks.org/introduction-of-k-map-karnaugh-map/. For the position of the variables and their negations in the kmap replace A,B,C,D with x,y,w,z in the picture :
The translation of letters to binary digits is
Simplify all the terms until no more terms can be simpified, the
output of the example below in this step is: ['10**', '1*0*', '1**0', '*110'] which is same as AB' + AC' + AD' + BCD'
source : https://github.com/zhcHoward/Kmap
So you basically need a square matrix
int matrix[4][4];
/*initialize matrix with '0'*/
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
matrix[i][j] = 0;
/* then needed fields to '1' i.e. xy', in most implementations the array is flattened for this */
Source code for a kmap solver is i.e. in http://krunalsiddhapathak.blogspot.com/2013/05/blog-post.html and in https://github.com/Ghost---Shadow/karnaugh-map-simplifier/blob/master/KarnaughMap/Map.cpp
For the verfication step ("Demonstrate that,...") see this .cpp code https://github.com/Ghost---Shadow/karnaugh-map-simplifier/blob/master/KarnaughMap/Simplifier.cpp and for background (POS, SOP, quad, octant,...) https://github.com/tasnim007/K-Map-Solver----Java-Project, https://www.geeksforgeeks.org/introduction-of-k-map-karnaugh-map/ and http://www.nzdl.org/cgi-bin/library?e=d-00000-00---off-0cdl--00-0----0-10-0---0---0direct-10---4-------0-1l--11-en-50---20-about---00-0-1-00-0--4----0-0-11-10-0utfZz-8-00&cl=CL2.4&d=HASHfb0a7f85db79899f86b6a0.8.1.5>=1
Problem: To display the sum of this pattern for n terms like 1+11+111+1111+11111..n terms
Test Data:
Input the number of terms: 5.
Expected Output:
1 + 11 + 111 + 1111 + 11111
The Sum is : 12345
I am trying this way->
//To display the sum of series like 1+11+111+11111
#include <stdio.h>
int
main(void){
//Here i declared some variables for storing information
int number,iteration,value=1,j,summation=0;
//Message to user
printf("Input the number of terms : ");
//taking input from the user
scanf("%d",&number);
//this condition will work till the iteration reaches to the inputted number
for(iteration=1; iteration<=number; iteration++){
for(j=1; j<=iteration; j++){
//To display the series like 1 11 111 1111 11111
printf("%d",value);
if(j==1){
summation=summation+value;
}
else if(j==2){
summation=summation+value*10;
}
else if(j==3){
summation=summation+value*100;
}
else if(j==4){
summation=summation+value*1000;
}
else if(j==5){
summation=summation+value*10000;
}
}
printf(" ");
}
printf("\n");
//To display the summation
printf("The summation is : %d",summation);
return 0;}
Now my problem is: This code does not work according to my expectation. It is working up to input value 5. But when I want to give input 6 times then I need to add an else if condition additionally in my code. I need to do this task whenever I increase the input value.
When the input value is 6 and i need to add and make the condition like that->
else if(j==6){
summation=summation+value*100000;
}
So I think, this is not the way of a proper solution to a problem. Every time I need to do the same thing for the inputted value. How can I solve this problem?. After that how can I simplify the solution? I believe that you guys are expert than me. Please share your knowledge with me. Thank you in advance.
Pass the input number to this function.
int findSum(int n)
{
int sum=0, cnt= 1;
for (int i = 1; i <= n; i++) {
sum += cnt;
cnt = (cnt * 10) + 1;
}
return sum;
}
If you want to make this work for large N (say, 1,000 or 20,000,000), you won’t be able use int or long long values. Instead, you could allocate an array of uint8s, and do your own digit-by-digit addition arithmetic, including the carry operation. Then print the results at the end. It wouldn’t be fast but it would work.
To keep your code simple, think right-to-left. Start with the least significant digit in the zero-th array element.
Here's an example that uses uint64_t to represent larger numbers. It shows the output you want for 1 up to 20 digits (longer causes an overflow).
The trick is to generate the numbers 1, 11, 111, and so on from the previous one by multiplying by 10 and adding 1. For example, 11111 = 1111 * 10 + 1.
#include <inttypes.h>
#include <stdio.h>
void sum(int n) {
uint64_t t = 0;
uint64_t x = 1;
for (int i = 0; i < n; i++) {
if (i > 0) printf(" + ");
printf("%" PRIu64, x);
t += x;
x = (x * 10) + 1;
}
printf(" = %" PRIu64 "\n", t);
}
int main() {
for (int i = 1; i < 21; i++) {
sum(i);
}
}
Here's a version that works for any n. It computes the total in time linear in n, although printing the terms being summed necessarily requires O(n^2) time.
The code works by noting that the last digit of the total consists of n 1s being added, the next-to last n-1 1s and so on. Plus carry of course. Note that the result is always exactly n digits long.
#include <stdio.h>
#include <stdlib.h>
void sum(int n) {
for (int i = 1; i <= n; i++) {
if (i > 1) printf(" + ");
for(int j = 0; j < i; j++) putchar('1');
}
printf(" = ");
char *s = malloc(n + 1);
s[n] = '\0';
int t = 0;
for (int i = n - 1; i >= 0; i--) {
t += i + 1;
s[i] = '0' + (t % 10);
t /= 10;
}
printf("%s\n", s);
free(s);
}
int main() {
sum(50);
}
Output (wrapped):
1 + 11 + 111 + 1111 + 11111 + 111111 + 1111111 + 11111111 + 111111111 + 1111111111 + 11111111111 + 111111111111 +
1111111111111 + 11111111111111 + 111111111111111 + 1111111111111111 + 11111111111111111 + 1111111111111111 11 +
1111111111111111111 + 11111111111111111111 + 111111111111111111111 + 1111111111111111111111 + 11111111111111111111111 +
111111111111111111111111 + 1111111111111111111111111 + 11111111111111111111111111 + 11111111111 1111111111111111 +
1111111111111111111111111111 + 11111111111111111111111111111 + 111111111111111111111111111111 +
1111111111111111111111111111111 + 11111111111111111111111111111111 + 111111111111111111111111111111111 +
1111111111111111111111111111111111 + 11111111111111111111111111111111111 + 111111111111111111111111111111111111 +
1111111111111111111111111111111111111 + 11111111111111111111111111111111111111 + 1111111111111111111111111
11111111111111 + 1111111111111111111111111111111111111111 + 11111111111111111111111111111111111111111 +
111111111111111111111111111111111111111111 + 1111111111111111111111111111111111111111111 + 1111111111111111111111111
1111111111111111111 + 111111111111111111111111111111111111111111111 + 1111111111111111111111111111111111111111111111 +
11111111111111111111111111111111111111111111111 + 111111111111111111111111111111111111111111111111 +
1111111111111111111111111111111111111111111111111 + 11111111111111111111111111111111111111111111111111 =
12345679012345679012345679012345679012345679012340
For handling numbers greater than int/long limits, you can use an array to get the sums per digit and print the output as a string.
#include <stdio.h>
int
main (int argc, char *argv[])
{
int n, i, j;
scanf("%d", &n);
char ones[n];
char sum[n + 1]; // + 1 index in case of a carry out
char output[n + 2]; // +1 more index than sum for null byte
// initialize to 0s
for (i = 0; i < n; i++) {
ones[i] = sum[i] = output[i] = 0;
}
sum[n] = output[n] = output[n+1] = 0;
for (i = 0; i < n; i++) {
ones[i] = 1;
output[i] = '1';
for (j = 0; j <= i; j++) { // add the current number of ones to sum
sum[j] += ones[j];
if (sum[j] >= 10) { // if theres a carry
sum[j + 1] += (sum[j] / 10); // add the carry to the next index
sum[j] %= 10; // keep the last digit
}
}
if (i == n - 1) {
printf ("%s ", output);
} else printf ("%s + ", output);
}
if(sum[n] == 0) {// leading digit is 0
i = n - 1;
} else i = n;
for (j = 0; i >= 0; i--, j++) {
output[j] = sum[i] + '0';
}
printf ("The sum is: %s\n", output);
return 0;
}
Given your user input variable number, the code may look something like this:
//...
if (number < 0)
{
// do some error handling
return -1;
}
int value_to_add = 1;
int sum = 0;
while (number--)
{
sum += value_to_add;
value_to_add = value_to_add * 10 + 1;
}
// ... (result is in "sum")
You also may consider the possibility of overflow (when the result gets so big that it does not fit in an int). You could, for instance, limit the user input (number).
glad to help!
(it seems like a homework, so hope you can learn something)
You're doing this with many 'if's to decide how much it should plus. And another way is to use *10+1 every time.
Please see the code:
#include <stdio.h>
long long sum,tmp=1,n;
int main(void){
scanf("%lld",&n);
for(int i=0;i<n;i++){
if(i<n-1)printf("%lld + ",tmp);
else printf("%lld ",tmp);
sum+=tmp;
tmp=tmp*10+1;
}
printf("= %lld",sum);
return 0;
}
That's it.
Wish you a good day:)
If I understood correctly you want to be able to programmatically add new terms without having to use an if statement. To do it I suggest you
for (j=0; j<=iteration; j++){
int powerOf10 = (int) pow((double) 10,j); //power elevation: notice 10^0=1, 10^1=10..
summation+=value*powerOf10;
}
This was just to give you an idea. Obviously, this code can be further refined.
If you don't understand all the casting I performed to compute powerOf10 I leave you this post: Why is my power operator (^) not working?
Paul Hankin's answer shows how to solve this problem for values of n greater than the number of digits storable in a long long.
That approach could be combined with another, based on a simple observation. If we write the sum starting from the greatest number, we can note an emerging pattern.
111111111111111111111111111111111111111111111...111 +
11111111111111111111111111111111111111111111...111 +
...
1111111111111111111111111111111111111...111 =
----------------------------------------------------
123456789999999999999999999999999999999999999...999 +
111111111111111111111111111111111111...111 =
----------------------------------------------------
123456790111111111111111111111111111111111111...110 +
11111111111111111111111111111111111...111 +
...
1111111111111111111111111111...111 =
----------------------------------------------------
123456790123456789999999999999999999999999999...998 +
111111111111111111111111111...111 =
----------------------------------------------------
123456790123456790111111111111111111111111111...109 +
11111111111111111111111111...111 +
...
1111111111111111111...111 =
----------------------------------------------------
123456790123456790123456789999999999999999999...997 +
111111111111111111...111 =
----------------------------------------------------
123456790123456790123456790111111111111111111...108 +
^ ^ ^ ^ ...
In practice, we can start by "filling" the number (represented as a string of n characters) with the repeating pattern "123456790" from left to right (the most significant digit beeing always '1').
Then, starting from the least significant digit, we can apply the algorithm of the sum with carry, but only as long as the calculated digit is different from the one already there (except the last one, which is always n % 10).
Only a few steps are needed, just around the number of decimal digits of n.
I want to write a function that prints all possible patterns like in the examples below. In every case, we must start in the top left of a 3x3 array. It's similar to the patterns to unlock mobile phones, except the line can't go diagonally and must pass through every box.
1--->2--->3 1--->2--->3
| |
v v
8<---7 4 or 6<---5<---4
| ^ | |
v | v v
9 6<---5 7--->8--->9
I started by writing a code where [0][0] was assigned 1 then randomise the rest of the digits in the 2d array until 1[0] or 0 was equal to 2, and so forth. But I feel like this is making the problem even more difficult to solve.
Then tried to use recursion to call the makePattern function again and again until the array is changed; however, it changes all values in the array to 2 because of these lines of code:
int value = 2;
array[x][y] = value;
However, I don't how to loop this value so that it increases as the function is called again.
#include <stdio.h>
#include <stdlib.h>
#define ROW 3
#define COLUMN 3
int makePattern(int array[ROW][COLUMN], int x, int y);
int main(void) {
int x, y;
int count = 2;
int i, j;
int array[ROW][COLUMN] = {
{'1', '0', '0'},
{'0', '0', '0'},
{'0', '0', '0'},
};
makePattern(array, 0, 0);
for (i = 0; i < ROW; i++) {
for (j = 0; j < COLUMN; j++) {
printf("%d", array[i][j]);
}
printf("\n");
}
return 0;
}
int makePattern(int array[ROW][COLUMN], int x, int y) {
int value = 2;
array[x][y] = value;
for (value = 2; value < 9; value++) {
if (x + 1 < ROW && array[x+1][y] == '0') {
makePattern(array, x + 1, y);
}
if (x - 1 >= 0 && array[x - 1][y] == '0') {
makePattern(array, x - 1, y);
}
if (y + 1 < COLUMN && array[x][y + 1] == '0') {
makePattern(array, x, y + 1);
}
if (y - 1 >= 0 && array[x][y - 1] == '0') {
makePattern(array, x, y - 1);
}
value++;
}
}
You're on the right track here in that you're using a 3x3 matrix to keep track of state (visited nodes and to store the path taken), x/y coordinates to represent the current location and spawning four recurse calls to handle the possible move directions (with bounds checks).
However, I'm not sure the loop running to 9 is going to work--this will spawn 36 recursive calls per frame. This might be workable in some implementations, but I think the easiest approach is to treat each frame as exploring one possible direction given an x/y coordinate pair, then backtracking (undoing the move) after all directions have been explored recursively from that square. Whenever we hit the last step, we know we've explored all of the squares and it's time to print the current solution path.
Here's code which achieves this and basically hardcodes the dimensions. An exercise would be to generalize the code to matrices of any size and return the path to separate printing from the traversal logic. I also opted to move state out of the main function.
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
static void print_unlock_patterns_r(int pad[3][3], int x, int y, int step) {
static int const directions[][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
pad[y][x] = 1 + step;
for (int i = 0; i < 4; i++) {
int xp = x + directions[i][0];
int yp = y + directions[i][1];
if (xp >= 0 && xp < 3 && yp >= 0 && yp < 3 && !pad[yp][xp]) {
print_unlock_patterns_r(pad, xp, yp, step + 1);
}
}
if (step == 8) {
for (int i = 0; i < 3; i++, puts("")) {
for (int j = 0; j < 3; printf("%d", pad[i][j++]));
}
puts("");
}
pad[y][x] = 0;
}
void print_unlock_patterns() {
int pad[3][3];
memset(pad, 0, sizeof(pad));
print_unlock_patterns_r(pad, 0, 0, 0);
}
int main(void) {
print_unlock_patterns();
return 0;
}
Output:
123
894
765
123
874
965
123
654
789
129
438
567
145
236
987
189
276
345
187
296
345
167
258
349
i build a program that translate base 10 ti base 2 and base 16:
#include <stdio.h>
int main(void)
{
int b10, b2, b16;
scanf("%d", &b10);//getting a number in base 10
b16 = b10;
b2 = b10;
//******print the number in base 2
int* ba2 = (int*)malloc(b10/2*4);
int i = 0,j;
while (b2 > 0){
ba2[i] = b2 % 2;
b2=b2 / 2;
i++;
}
for (j = i-1; j >= 0; j--){
printf("%d", ba2[j]);
}
free(ba2);
//**************************
//******print the number in base 16
printf("\n");
int* ba16 = (int*)malloc(b10 / 16 * 4);
i = 0;
while (b16 > 0){
ba16[i] = b16 % 16;
b16 = b16 / 16;
i++;
}
for (j = i - 1; j >= 0; j--){
if (ba16[j] < 10)
printf("%d", ba16[j]);
else
printf("%c", 'A' + (ba16[j] - 10));
}
free(ba16);
//****************************
getch();
return 0;
}
for some reason the program stop at the second free().
when i created a break point the program just stoped when i got to the free, no msg or warning.
can someone help me with is?
You are allocating memory as ba10/16 * 4. For input values less that 16, that evaluates to zero. As per malloc documentation, you will either get null pointer or a unique pointer which can be passed to free. But you are assigning values in ba16[0]. Same holds true for input value of 16. you have allocated 4 bytes. But the program goes on to assign ba16[0] and ba16[1], which will corrupt the array. The same problem exists with ba2 as well. I don't know if you tested with input values less than 16 or 2. Hope this helps.
Please help to shorten this function in order to have 25 or less lines!
it prints all possible combination of numbers from 0 to 99,
EX: 00 01, 00 02, 00 03, 00 04, 00 05, ..., 00 99, 01 02, ..., 97 99, 98 99
void dp_print_comb2(void)
{
char a;
char b;
char c;
char d;
a = '0';
b = '0';
while (a <= '9')
{
if (b > '9')
{
a++;
b = '0';
}
c = a;
if (b == '9')
c++;
d = b + 1;
if (b == '9')
d = '0';
while (c <= '9')
{
ok(a, b, c, d);
d++;
if (d > '9')
{
c++;
d = '0';
}
}
b++;
}
}
So if there is a way to split this function or to shorten please help me! thanks!
If the main and other function are needed i can put give them too!
ps: i started to learn C, and making some practice! (sorry for bad english)
void dp_print_comb2(void){
for(int ab = 0; ab < 100-1; ++ab)
for(int cd = ab + 1; cd < 100; ++cd)
printf("%02d %02d, ", ab, cd);
puts("");
}
If you want to make your code even shorter it is possible to make a single loop (Not tested but should work).
void foo(){
for(int i=0,j=0;j<100;i=(i+1)%100,j+=!i)
printf("%02d %02d,",i,j);
}
How does it work
i and j are initialized to 0
(Loop 0 to 99) Each loop i is incremented. As i!=0 j stay constant (=0)
(Loop 100) i returns to 0 (n%n -> 0) and j is incremented
(Loop 100 to 199) Each loop i is incremented. As i!=0 j stay constant (=1)
And so on...
PS1 : It won't be faster, and it's less clear that using two loops, but it shows a different way to do the same thing.
PS2 : It could be even possible to use only one variable (but it would be even less clear...).
from your example, when the numbers are the same, do not print them
Your question was unclear about any other constraints.
This is the code I would use:
#include <stdio.h>
#define MAX_PLUS_ONE (100)
// prototype
void dp_print_comb2( void )
void dp_print_comb2()
{
for( unsigned ab=0; ab < MAX_PLUS_ONE; ab++)
{
for( unsigned cd=0; cd < MAX_PLUS_ONE; cd++)
{
if( ab != cd )
{ // then numbers are not the same
printf( "%02u %02u, ", ab, cd);
} // end if
} // end for
} // end for
} // end function: db_print_comb2