I had a program that I had to create which took a user inputted odd number between 1 to 99 and created a magic square which I have successfully done.
#include <stdio.h>
int main()
{
int n;
printf("\nThis programs creates a magic squares of a specified size.\n");
printf("The size must be an odd number between 1 and 99.\n");
printf("Enter the size of magic square: ");
scanf("%d", &n);
int magicsq[99][99];
int row = 0;
int col = (n - 1) / 2;
magicsq[row][col] = 1;
int i;
for(i = 2; i <= n * n; i++)
{
row = (row + n - 1) % n;
/* printf("i = %d\n", i);
printf("row %d\n", row);
col = (col % n); */
col = (col + 1) % n;
/* printf("col %d\n\n", col); */
if(magicsq[row][col] != 0)
{
row = (n + row + 2) % n;
col = (n + col - 1) % n;
/* printf("n = %d ; row = %d ; col = %d\n", n, row, col); */
}
magicsq[row][col] = i;
}
printf("\n");
int j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%5d", magicsq[i][j]);
}
printf("\n");
}
return 0;
}
I came across another question which stated me to introduce two functions namely, void create_magic_square(int n, char magic_square[99][99]) and void print_magic_square(int n, char magic_square[99][99])
#include <stdio.h>
void create_magic_square(int n, char magic_square[99][99]);
void print_magic_square(int n, char magic_square[99][99]);
int main()
{
int n;
char **magic_square;
printf("\nThis programs creates a magic squares of a specified size.\n");
printf("The size must be an odd number between 1 and 99.\n");
printf("Enter the size of magic square: ");
scanf("%d", &n);
create_magic_square(n, magic_square[99][99]);
print_magic_square(n, magic_square[99][99]);
return 0;
}
void create_magic_square(int n, char magic_square[99][99])
{
int *magicsq[][];
magic_square[99][99] = magicsq[][];
int row = 0;
int col = (n - 1) / 2;
magicsq[row][col] = 1;
int i;
for(i = 2; i <= n * n; i++)
{
row = (row + n - 1) % n;
printf("i = %d\n", i);
printf("row %d\n", row);
/* col = (col % n); */
col = (col + 1) % n;
printf("col %d\n\n", col);
if(magicsq[row][col] != 0)
{
row = (n + row + 2) % n;
col = (n + col - 1) % n;
printf("n = %d ; row = %d ; col = %d\n", n, row, col);
}
magicsq[row][col] = i;
}
}
void print_magic_square(int n, char magic_square[99][99])
{
printf("\n");
int j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%5d", magicsq[i][j]);
}
printf("\n");
}
}
Upon compiling, I am filled with tons of errors on my declaration of char type array and my usage of the parameters. I have googled char() parameters and types but I am not able to incorporate into my program.
I am new to c so constructive criticism is appreciated and helps me learn better if I am doing anything wrong.
Language: c99 ; Compiler: gcc
Of course there are lot of mistakes in your code related to pointers and arrays and those can't be completely explained in a single answer here.
I recommend you to study the pointers properly. Relationship between pointers and arrays, Multidimensional arrays are all need to be thoroughly understood before attempting to do what you are trying to.
Related
I need to create a program that gets a dynamic matrix and changes it to one dimension, for example 4x4 matrix will give 16 arrays length, where each index has a odd or even number, matching the index itself. The threads needs to go over the matrix at the same time and copy the odd and even numbers to the correct places in the array. The main thread needs to wait for the rest of them to finish before printing the array and every value with its respective thread. It should come out like this
We managed to fix the segmentation fault that kept happening, but now we need to set it so that each thread runs right after the other but instead each thread runs 4 times and then it switches to a different one. How can I change it so it'll run as asked?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <pthread.h>
#include <math.h>
#define CORE 4
int N;
int odd = 1;
int even = 0;
typedef struct my_thread {
int** matrix;
int* resArray;
int threadId;
int strart_raw;
int strart_cal;
int end_raw;
int end_cal;
int counter;
} my_thread;
void* createArray(struct my_thread* thread);
void main() {
pthread_t th[CORE];
int s_r = 0, s_c, e_r, e_c;
int i, j, lines, columns, * intMatrix;
printf("Type the N for the N*N matrix:\t");
scanf("%d", &N);
int size = N * N;
int result_Array[N * N];
int retcode;
int interval = size / CORE;
int matrix_build_counter = 1;
intMatrix = (int*)malloc(N * N * sizeof(int));
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
intMatrix[i * N + j] = matrix_build_counter;
matrix_build_counter++;
}
}
printf("The matrix:\n");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%d ", intMatrix[i * N + j]);
}
printf("\n");
}
struct my_thread thred_obj_array[CORE];
for (int i = 0; i < CORE; i++) {
thred_obj_array[i].matrix = &intMatrix;
thred_obj_array[i].resArray = result_Array;
thred_obj_array[i].threadId = i;
thred_obj_array[i].strart_raw = (int)((i * N) / CORE);
thred_obj_array[i].end_raw = (int)(((interval * (i + 1)) / N));
thred_obj_array[i].strart_cal = ((interval * i)) % N;
thred_obj_array[i].end_cal = ((interval) * (i + 1));
thred_obj_array[i].counter = (int)floor((interval)*i);
}
for (int i = 0; i < CORE; i++) {
retcode = pthread_create(&th[i], NULL, createArray, &thred_obj_array[i]);
if (retcode != 0) {
printf("Create thread failed with error %d\n", retcode);
}
}
printf("done");
for (int i = 0; i < CORE; i++) {
pthread_join(th[i], NULL);
}
printf("the result array is: ");
for (int i = 0; i < N * N; i++) {
printf("%d ", result_Array[i]);
}
}
void* createArray(struct my_thread* thread) {
int j;
for (int i = thread->strart_raw; i < N; i = i * sizeof(int) * N) {
for (j = thread->strart_cal; j < N; j++) {
printf("I am thread: %d And my value is: %d , (%d,%d)\n", thread->threadId, (*thread->matrix + i * N)[j], i, j);
if (((*thread->matrix + i * N)[j]) % 2 == 0) {
thread->resArray[even] = (*thread->matrix + i * N)[j];
even += 2;
printf("-----%d ---even---\n", even);
}
else {
thread->resArray[odd] = (*thread->matrix + i * N)[j];
odd += 2;
printf("---%d ---odd--\n", odd);
}
(thread->counter)++;
if (thread->counter == thread->end_cal) {
return;
}
}
thread->strart_cal = 0;
}
}
I want to draw an image like this (for size 8x8):
##..##..##..##..
##..##..##..##..
..##..##..##..##
..##..##..##..##
##..##..##..##..
##..##..##..##..
..##..##..##..##
..##..##..##..##
##..##..##..##..
##..##..##..##..
..##..##..##..##
..##..##..##..##
##..##..##..##..
##..##..##..##..
..##..##..##..##
..##..##..##..##
My code is:
{
int rows, cols, i, j, k;
scanf("%d", &rows);
scanf("%d", &cols);
k = 1;
for(i=1; i<=rows; i++)
{
for(j=1; j<=cols; j++)
{
if(k == 1)
{
printf("##");
}
else
{
printf("..");
}
k *= -1;
}
if(cols % 2 == 0)
{
k *= -1;
}
printf("\n");
}
return 0;
This code works good, but it's not like in the image!
That's the different approach to the solution. The core idea is to get a base string with 1/2 additional repetition of the pattern. Then you basically "shift" the string back and forth by two positions using pointer arithmetic (to manage the beginning of the string) and putting the null character \0 where appropriate (to manage the end of the string).
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main () {
int rows = 0;
int cols = 0;
/* From the example provided I assume that the number of columns
* and rows should be a multiple of 2
* even though the OP hasn't explicitly mentioned it
*/
scanf("%d %d", &rows, &cols);
// input validation goes here
// generating the base string
// notice that the string is 2 characters longer than required
char *str = malloc(sizeof(*str) * (cols + 1) * 2 + 1);
for (int i = 0; i < cols / 2; ++i) {
strcpy(str + i * 4, "##..");
}
strcpy(str + strlen(str), "##");
int n = 0;
int len = strlen(str);
for (int i = 0; i < rows; ++i) {
n = i % 2;
// switching back and forth between null character '\0' and '#'
str[len - 2] = n * 35; //35 - ASCII code for a '#'
// using pointer arithmetic we send to function either first element
// or third
printf("%s\n%s\n", str + n * 2, str + n * 2);
}
free(str);
return 0;
}
EDITED: Generalized the solution for arbitrary (but even!) number of rows and columns.
This code does what you ask for, I think.
#include <stdio.h>
int main() {
int rows, cols;
scanf("%d", &rows);
scanf("%d", &cols);
rows = rows*2;
int k = 0;
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
if(k < 2 && j % 2 == 0) {
printf("##");
}
else if(2 <= k && j % 2 != 0) {
printf("##");
}
else {
printf("..");
}
}
k++;
if(k == 4) {
k = 0;
}
printf("\n");
}
return 0;
}
Given the following piece of code, I don't understand why do we have to initialize every single row of the matrix when we have already created enough space in the stack.
#include <stdio.h>
#include <stdlib.h>
main() {
int **w;
int i, j;
int m, n;
printf("Number of rows in the matrix: ");
scanf("%d", &m);
printf("Number of columns in the matrix: ");
scanf("%d", &n);
w = (int **)malloc(m * n * sizeof(int));
for (i = 0; i < m; i++)
w[i] = (int *)malloc(n * sizeof(int));
for (i = 0; i < m; i++)
for (j = 0; j < n; j++) {
printf("Element [%d][%d]: ", i + 1, j + 1);
scanf("%d", &w[i][j]);
}
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("Element [%d][%d]: %d\n", i + 1, j + 1, w[i][j]);
}
There are many issues in your code:
space is not allocated on the stack, but from the heap.
in both cases, memory allocated for the objects is uninitialized, which means it is not initialized to anything in particular and can have any value whatsoever. Relying on any particular contents is undefined behavior.
the matrix dimensions and all the matrix elements are read from standard input with scanf(). Yet you do not check for scanf() failure to convert integers from the characters read from stdin, so any invalid or missing input is going to cause undefined behavior at some point in the program.
your matrix is actually structured as an array of pointers to arrays of int, which is fine, but inconsistent with the size arguments used to allocate the first array: w = (int **)malloc(m * n * sizeof(int)); should be
w = malloc(m * sizeof(*w));
you could easily get objects pre-initialized to 0 by using calloc() instead of malloc():
for (i = 0; i < m; i++)
w[i] = calloc(n, sizeof(int));
you should also check for malloc() failure and exit with an appropriate diagnostic message.
main() is an obsolete prototype for the main function. You should either use int main(), int main(void) or int main(int argc, char *argv[])...
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
int get_int(void) {
int n;
if (scanf("%d", &n) != 1) {
printf("invalid input\n");
exit(EXIT_FAILURE);
}
return n;
}
void xalloc(size_t size) {
void *p = calloc(size, 1);
if (p == NULL) {
printf("out of memory for %zu bytes\n", size);
exit(EXIT_FAILURE);
}
return p;
}
int main() {
int **w;
int i, j;
int m, n;
printf("Number of rows in the matrix: ");
m = get_int();
printf("Number of columns in the matrix: ");
n = get_int();
w = xalloc(m * sizeof(*w));
for (i = 0; i < m; i++) {
w[i] = xalloc(n * sizeof(int));
}
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("Element [%d][%d]: ", i + 1, j + 1);
w[i][j] = get_int();
}
}
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("Element [%d][%d]: %d\n", i + 1, j + 1, w[i][j]);
}
}
for (i = 0; i < m; i++) {
free(w[i]);
}
free(w);
return 0;
}
I want here to implement the value of array[i][j] into itself, but firstly I have to check if it is in range between example: -99 and 99. If the input is out of these boundaries, it should stop the program.
I tried it with a do-while loop and just now I tried while loop.
#include <stdio.h>
#include <stdlib.h>
int main(){
int array[2][2], i, n, j;
/*
do
{
printf("Value= ");
scanf("%d", &n);
array[i][j] = n;
i++;
j++;
}
while(n < 99 && n > -99);
*/
while(array[i][j] < 99 && array[i][j] > -99){
for(i = 0; i < 2; ++i){
for(j = 0; j < 2; ++j){
printf("Value= ");
scanf("%d", &array[i][j]);
}
}
}
// Print the result
for(i = 0; i < 2; ++i){
for(j = 0; j < 2; ++j){
printf("\n[%d][%d]: ", array[i][j]);
}
}
}
I got a endless loop which doesn't exit if the value is incorrect (out of these boundaries).
Try this, tested and works:
int *array, i, val, n, m;
printf("Put in array size in the form of n-m where n is number of rows and m is number of columns: ");
scanf("%d-%d", &n, &m);
array = (int *) malloc(sizeof(int) * n * m);
i = 0;
while (i < n * m) {
printf("Value for row: %d, column: %d: ", i / m + 1, i % m + 1);
scanf("%d", &val);
if (val > 99 || val < -99) continue;
*(array + i) = val;
i++;
}
for (i = 0; i < n * m; i++) {
if (i > 0 && i % n == 0) printf("\n");
printf("%d\t", *(array + i));
}
free(array);
Without pointers (Variable sized arrays does not work on C90, needs newer standard, or you may use fixed sized arrays):
int i, val, n, m;
printf("Put in array size in the form of n-m where n is number of rows and m is number of columns: ");
scanf("%d-%d", &n, &m);
int array[n][m];
i = 0;
while (i < n * m) {
printf("Value for row: %d, column: %d: ", i / m + 1, i % m + 1);
scanf("%d", &val);
if (val > 99 || val < -99) continue;
array[i / m][i % m] = val;
i++;
}
for (i = 0; i < n * m; i++) {
if (i > 0 && i % n == 0) printf("\n");
printf("%d\t", array[i / m][i % m]);
}
In your array undefeated values, in the first while you try to check random number in your memory. And so your i j will be random number.
Put if statement in your for loop to check the value in array, and delete while loop
Programming in C for finding maximum in 2D array using dynamic memory allocation.
int main() {
int i, arr[m][n], j, m, n;
int max = 0;
int *ptr;
printf("enter the value m");
scanf("%d", m);
printf("enter the vaue of n");
scanf("%d", n);
ptr = (int*) malloc(m * n * 4);
printf("enter the values\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", ((ptr + i * n) + j));
}
}
max = arr[0][0];
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
if (max < *((ptr + i * n) + j));
max = *((ptr + i * n) + j);
}
}
printf("%d", max);
}
I made changes to your code to remove the error you are getting. I commented the changes that I have made.
int main()
{
/*int i, arr[][], j, m, n;*/
/* Because arr is allocated dynamically, you have to declare as a pointer to int. */
int i, *arr, j, m, n;
int max = 0;
int *ptr;
printf("enter the value m");
scanf("%d", m);
printf("enter the vaue of n");
scanf("%d", n);
/*ptr = (int*)malloc(m * n * 4);*/
/* It is better to use sizeof(int) because int does not have the same length of all computers. */
ptr = (int*)malloc(m * n * sizeof(int));
printf("enter the values\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", ((ptr + i * n) + j));
}
}
/*max = arr[0];*/
/* To get the first int at arr, you could also use arr[0], but not arr[0][0] because */
/* this would require that arr be an array of pointers to array of int's, which is not the case. */
max = *arr;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
if (max < *((ptr + i * n) + j));
max = *((ptr + i * n) + j);
}
}
printf("%d", max);
}
You must learn the algorithms and programming language C.
So you can find some courses in this site :
learn-c
try this code is functioned:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[]) {
int i, j, m, n;
int max;
int **ptr;
printf("enter the value m: ");
scanf("%d", &m);
printf("enter the vaue of n: ");
scanf("%d", &n);
ptr = (int **)malloc(n * sizeof(int *));
for (i = 0; i < m; i++) {
*(ptr + i) = (int *)malloc(m * sizeof(int));
for (j = 0; j < n; j++) {
scanf("%d", (*(ptr + i) + j));
}
}
max = **ptr;
printf("\n\nMatrix:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", *(*(ptr + i) + j));
if (max < *(*(ptr + i) + j))
max = *(*(ptr + i) + j);
}
printf("\n");
}
printf("\nthe max is %d \n", max);
return 0;
}