printing integer and char using the same argument in c - c

I have an assignment to implement a board game. I come up with an idea to print integer and char using the same statement for example,
int main() {
char c[2];
c[0]=1;
c[1]='X';
for (int i = 0;i<=1;++i) {
printf("%d", c[i]);
}
return 0;
}
this is not working as I have integer and char in the array. how could i modify this to just use one for loop?
EDIT:
I am trying to implement a noughts and crosses game. So I display my board as
1 2 3
4 5 6
7 8 9
and whenever a player put down a X or O at a position, I want to display my board for example,
1 X 3
4 5 6
7 8 9

You can just print chars. Since your digits are always 1 to 9 you can use chars '1' to '9' (49 to 57) instead.
It's not exactly a code you'd be writing in production, but it's a nice case of a little puzzle and what you can do with C.
int main() {
char c[2];
c[0]='1';
c[1]='X';
for (int i = 0;i<=1;++i) {
printf("%c", c[i]);
}
return 0;
}
I've slightly modified your code to make it clear how that might work.

Your code won't work as intended as you're mixing up two distinct data types. int and char are not the same type of element. They don't even have the same size; the size of char is defined as 1, and the size of int varies by implementation, but is usually 4 or 8. So your array will not even be able to hold ints. When you say:
c[0] = 1;
what is actually happening is that the array stores the char with the ASCII value of 1, which is the "Start of Heading" character.
To do what you want, do not use the int type at all. Use char throughout. That is, write something like this:
c[0] = '1';
Putting the '1' in single quotes makes it a char, not an int. You can use this to fill your 2D array and then make replacements with 'X' and '0' when needed.

You're doing to mistakes here.
You're using c[0]=1; instead of c[0]='1';. You want the character 1 and not the number 1.
You're using printf("%d instead of printf("%c. You want to print a character and not a number.
Here is some example code to achieve what you want:
void print_board(char *board) {
for(int i=0; i<9; i++) {
printf("%c ", board[i]);
if(i % 3 == 2)
printf("\n");
}
printf("\n");
}
void init_board(char *board) {
for(int i=0; i<9; i++)
board[i] = '1' + i;
}
int main(void) {
char board[9];
init_board(board);
print_board(board);
board[2] = 'X';
print_board(board);
board[5] = 'O';
print_board(board);
init_board(board);
print_board(board);
}
The above is not really production code. But it's enough to get you going.
Output:
$ ./a.out
1 2 3
4 5 6
7 8 9
1 2 X
4 5 6
7 8 9
1 2 X
4 5 O
7 8 9
1 2 3
4 5 6
7 8 9

Related

Array prints an unwanted number for no reason

/*This is a c program that inputs an array of 9 numbers, reverses it and prints it*/
#include <stdio.h>
int main()
{
int a[9];
printf("Enter 9 numbers \n");
int i;
for(i=0;i<9;i++)
{
scanf("%d",&a[i]);
}
int n=10;
int t;
for(i=0;i<9/2;i++)
{
t=a[i];
a[i]=a[8-i];
a[8-i]=t;
}
for(i=0;i<10;i++)
{
printf("%d\t",a[i]);
}
}
This is the output:
Enter 9 numbers 1 2 3 4 5 6 7 8
9
9 8 7 6 5 4 3 2 1
32765
I want to understand where the 32765 is coming from and how to fix it.
The last weird number you see there is the value of the next (10st) address from the cell after your array. "a" has been declared with 9 values, and you should remember that arrays in C start from 0. While printing you are trying to access 10 numbers (from 0 to 9)
As other answers point out, you are using a wrong array length at the last loop.
To avoid these kind of mistakes, use macros or const variables to store the fixed length of the array. For example:
#define ARRAYLEN 9
// ...
int a[ARRAYLEN];
// ...
for (int i = 0; i < ARRAYLEN; i++) {
// ...
}

Array in C containing Incorrect Values

The goal of this program is to add the first and last elements of an array together and set that value as the first element of an output array, and then continue moving inwards as such. All of the sums will be stored in an output array. For this program, the rules stipulate that I may only use pointers and pointer arithmetic (i.e. no subscripting, no '[]', etc.) I have gotten the program to work for arrays of length 2 as well and length 4 (as I have only implemented functionality for even-lengthed arrays) however when I try any array of length 6 or above, the program adds together incorrect values that are not in the first array.
I have already tried using two different debuggers to isolate where the problem is coming from and for the life of me I can not figure it out. I have spent a few hours looking over my notes on C and going through the code, reworking it however I can. I feel as if there is something wrong with how I am interacting between the array and the pointer variables, but I am unsure. I couldn't seem to find any questions on Stack Overflow too similar to this one (yes, I looked).
void add(int *a1, int array_size, int *a2) {
int * p;
int * temp = (a1+(array_size-1));
if (array_size % 2 == 0) {
array_size = array_size/2;
for (p = a2; p < (a2+array_size); p++) {
*p = *a1 + *temp;
printf("%d", *a1);
printf(" + %d", *temp);
a1++;
temp--;
printf(" = %d\n", *p);
}
}
}
For arrays of length 2 and 4 (again, I am only testing even numbers for now), the code works fine.
Example Output:
Enter the length of the array: 2
Enter the elements of the array: 1 2
1 + 2 = 3
The output array is: 3
Enter the length of the array: 4
Enter the elements of the array: 1 2 3 4
1 + 4 = 5
2 + 3 = 5
The output array is: 5 5
Now this is where it is going wrong.
When I do this:
Enter the length of the array: 6
Enter the elements of the array: 1 2 3 4 5 6
I expect:
1 + 6 = 7
2 + 5 = 7
3 + 4 = 7
The output array is: 7 7 7
But instead, the output is:
1 + 0 = 1
2 + 3 = 5
3 + 4 = 7
The output array is: 1 5 7
My best guess is that something went wrong with my use of pointers or perhaps pointer syntax. Any help I can get, positive or negative, would be greatly appreciated.
This is the main() function:
int main() {
int size = 0;
int out_size = 0;
int arr[size];
printf("Enter the length of the array: ");
scanf("%d", & size);
printf("\nEnter the elements of the array: ");
for (int i = 0; i < size; i++) {
scanf("%d", & arr[i]);
}
if (size % 2 == 0) {
out_size = size/2;
}
else{
out_size = ((size-1)/2) + 1;
}
int out[out_size];
//calling the add function and using the addresses of arrays + array size
add(arr, size, out);
//iterating through and printing output array which has now been
//altered by the move function
printf("\nThe output array is: ");
for (int i = 0; i < out_size; i++) {
printf("%d ", out[i]);
}
return 0;
}
You are using an array of size 0:
int main() {
int size = 0;
int out_size = 0;
int arr[size]; // <- Here is your problem
You could move the array declarations after the size reading:
int main() {
int size = 0;
int out_size = 0;
printf("Enter the length of the array: ");
scanf("%d", & size);
int arr[size];
printf("\nEnter the elements of the array: ");
for (int i = 0; i < size; i++) {
scanf("%d", & arr[i]);
}

Correct way to write a pattern in C language [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
I want to obtain the following output:
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
The code am running is as follows:
#include <stdio.h>
int main(void) {
int i=1,flag=0,lines=0; //0 for forward, 1 for reverse
while(i!=0 && lines<3){
if(!flag){
printf("%d ",i);
if(i==10){
flag=1;
printf("\n");
lines++;
}
else
i++;
}
else if(flag){
printf("%d ",i);
if(i==1){
lines++;
flag=0;
printf("\n");
}
else
i--;
}
}
return 0;
}
Am getting the desired output from the above code but not sure if it's an optimal code. Any other method/suggestion? Considering unlimited space but time complexity should be kept minimum.
Condition: Use only one loop
Use forloops, minimize code that is repeated
#include <stdio.h>
int main(void) {
int lines, flag=1, val;
for(lines=0;lines<3;lines++)
{
if(flag == 1)
for(val=1;val<=10;val++)
printf("%d ", val);
else
for(val=10;val>0;val--)
printf("%d ", val);
printf("\n");
flag = -flag;
}
return 0;
}
Hint: you can use for loops to iterate in either direction:
for (int i = 1; i <= 10; ++i)
or
for (int i = 10; i >= 1; --i)
Also, a for loop is better than a while here because it really shows to the reader "I am iterating i from this to that."
Use an array and iterate it normally at first iteration, vice versa in the second iteration and then normally again.
Sample code:
#include <stdio.h>
#define SIZE 10
void print_arr(int* array, int size);
void print_rev_arr(int* array, int size);
int main(void)
{
int array[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int iter = 3;
for(int i = 0; i < iter; ++i)
if(i % 2)
print_arr(array, SIZE);
else
print_rev_arr(array, SIZE);
return 0;
}
void print_arr(int* array, int size)
{
for(int i = 0; i < size; ++i)
printf("%d ", array[i]);
printf("\n");
}
void print_rev_arr(int* array, int size)
{
for(int i = size - 1; i >= 0; --i)
printf("%d ", array[i]);
printf("\n");
}
Output:
Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
IO completely dominates this problem.
But the fastest way to iterate forwards is
for(i=0;i<N;i++)
and the fastest and most elegant way to iterate backwards is
int i = N;
while(N--)
You can do this:
Use a for loop that will start from 1 and reach 10. Print its
counter.
Use a for loop that will start from 10 and stop at 1. Print its
counter.
Use a for loop that will start from 1 and reach 10. Print its
counter.
Sample code:
#include <stdio.h>
#define LEN 10
#define ITER 3
int main(void)
{
for(int i = 0; i < ITER; ++i)
{
if(i % 2)
for(int j = 1; j <= LEN; ++j)
printf("%d ", j);
else
for(int j = LEN; j >0; --j)
printf("%d ", j);
printf("\n");
}
return 0;
}
Output:
Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
There are 2 things to consider.
First is whether the program is optimal or not. Is is quite easy to prove that your program is optimal (at least asymptotically optimal). You need to display 3n numbers, so you need at least 3n iterations. You have 3n iterations, so it's fine. You might be able to further optimize the iterations themselves, but that will arise as an implicit result of the second paragraph.
The second is readability. Your code is a bit verbose and unflexible. Consider the following:
int pattern[] = {1,2,3,4,5,6,7,8,9,10};
int patternSize = sizeof(pattern)/sizeof(int);
for (int i=0; i < 3; i++)
for (int j=0; j<patternSize; j++) {
if (i % 2)
printf("%d", pattern[patternSize - j - 1]);
else
printf("%d", pattern[i])
}
The code is shorter and clearer. Also, it is more maintable. It is clear what you have to do to chanelge the pattern. I could hardcode the pattern size as 10, but that would requite 2 changes when you change the pattern. I could generate the pattern, from the value of j, but that would limit the number of patterns that could be shown.
But what if the pattern is all the numbers from 1 to 200? Of course I'm not going to write them by hand. Just replace the array with a for loop that fills up the array. You don't have to change the code that displays the array. This is a small example of separation of concerns - one part of thr code does pattern generation, another part does the display, and they can be modified independently.
While this is asymptotically optimal, there are optimizations that can be made. For examples, using that array to store the pattern is not as efficient as generating the pattern from j. But in practice, unless more efficiency is needed, the advantages of this method outweigh the small performance penalty.
Okay, here's my take, I think it's more pleasant than most:
#include <stdio.h>
int main(void)
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 10; ++j)
{
const int v = (i % 2) ? 10 - j : j + 1;
printf("%d ", v);
}
putchar('\n');
}
return 0;
}
Some points:
Doesn't use an array, instead just generates the very simple pattern from the line number (i) and position (j).
Not designed for "pluggable" patterns by using an array, since the pattern was very simplistic and repeating, that is exploited to simplify the code.
Re-use the inner loop, rather than duplicating it.
Prints a linefeed in the proper place, to actually get separate lines (not all posted solutions to that).
The inner loop's body could be shortened to a single line by folding v into the printf() of course, but I aimed for readability and clarity, there.

Creating deck of cards in C

I am trying to create a deck of cards in C. The way I want to implement this is by having a 2 dimensional array of deck[51][1], which will have 52 slots of 2 slots each. The first slot will contain the card value (1-52) and the second slot will contain the suit (1-4).
I have tried to assign this by using the below code:
int deck[51][1];
int i;
int j;
int suit = 1;
int main()
{
for(i=0; i<52; i++){
for(j=0; j<2; j++){
if(j==0){
deck[i][j] = i+1;
} else {
deck[i][j] = suit % 4;
}
suit++;
}
}
I then try and make it print out every card's value using the following double loop:
for(i=0; i<52; i++){
for(j=0; j<2; j++){
printf("%i ",deck[i][j]);
}
printf("\n");
}
return 0;
}
However instead of resulting in 52 lines of the card value followed by its suit, it just displays a weird
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
and so on until
51 52
52 0
I can't work out why it's not assigning the suit % 4 value to the second item of every array, which should result in a neat
1 1
2 2
3 3
4 4
5 1
6 2
7 3
8 4
Although array indexes in C are zero-based, it does not mean that the compiler would add 1 to each dimension on a declaration. Your declaration makes an array that is 51x1, not 52x2. For 52x2 array use
int deck[52][2];
Your current implementation has undefined behavior, which makes the output of your program incorrect: accessing deck[x][1] goes past the boundaries of the array, producing incorrect output.

How to print from 1 to 9 with three numbers in a line using loops

I am coding a tic tac toe game in C. I am stuck at making a board like this:
1 2 3
4 5 6
7 8 9
I want to use loops so that I dont have to use a printf function with many \n's and \t's...
Here's my attempt:
for (i=0;i<=9;i++)
{
printf("\n\n\n\t\t\t");
for (j=i;j<=i+2;j++)
{
printf("%c\t",boarddots[j]);
}
if (i==3)
break;
}
Something like this, you could adapt it to your actual needs:
for(int i = 1; i <= 9; ++i)
{
printf("%d", i); // print numbers one by one
if (0 == i % 3)
printf("\n"); // start new line if current number is divisible by 3
}
P.S. Sorry for possible typos
for (int row = 0; row < 3; row++)
{
for (int column = 0; column < 3; column++)
{
printf("%d ", (row * 3) + column + 1);
}
printf ("\n");
}
/*
output:
1 2 3
4 5 6
7 8 9
*/
Your loop condition for (i=0;i<=9;i++) iterated once too many. Personally, I would uses a 2D array such as char board [3][3], but one step at a time to help with your immediate question.
#include<stdio.h>
char boarddots[] = "--O-XX-O-";
int main()
{
int i;
for (i=0; i<9; i++) {
if (i % 3 == 0)
printf("\n\n\n\t\t");
printf("\t%c",boarddots[i]);
}
return 0;
}
Could do print as a string and use string truncation:
char boarddots[9] = {'1','2','3','4','5','6','7','8','9'};
int loop;
for (loop=0; loop<9; loop+=3)
printf ("%.3s\n", &boarddots[loop]);
You don't need a NULL on the end of the char array as the truncation takes care of that.

Resources