How to repeat rows in a matrix in C? - c

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

Related

arrange the array in an order such that the even values are followed by odd values in the array

this is the program I made ,if I input [13,11,10,17,18] i get the output [12,13,17,11,10]. I do not understand what mistake I am making. somebody please help me understand.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n,j,i,num,v;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
scanf("%d",&v);
ptr[i] = v;
}
i=0;
j=0;
while(i<5){
j++;
if (ptr[j]%2==0 && i%2==0){
num=ptr[i];
ptr[i]=ptr[j];
ptr[j]=num;
}
if (ptr[j]%2!=0 && i%2 !=0){
num=ptr[i];
ptr[i]=ptr[j];
ptr[j]=num;
}
if (j==4){
i++;
j=0;
}
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
Ok, I tried to tell you how you should have written you program, but you didn't listen:
Make a https://stackoverflow.com/help/minimal-reproducible-example
A MCVE needs all the includes
No interactive stuff. You need to run and run and run your program in a debugger. You don't want to put data in manually every single time.
You want many tests, and you want to repeat them, so that when you fix one, you don't break another.
Make a function which does the job.
Free your memory!
Now to the solution: your idea of a solution was fine apart from the stuff about indexes. It's pretty similar to the one you will find down here. The only difference is that I put the odd numbers al the end to avoid checking elements multiple times.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
void evenodd(int *v, size_t n)
{
for (size_t i = 0; i < n; ++i) {
while (i < n && v[i] % 2 == 0) {
++i;
}
--n;
while (i < n && v[n] % 2) {
--n;
}
if (i < n) {
int tmp = v[i];
v[i] = v[n];
v[n] = tmp;
}
}
}
bool is_evenodd(int *v, size_t n)
{
size_t i = 0;
while (i < n && v[i] % 2 == 0) {
++i;
}
while (i < n && v[i] % 2 != 0) {
++i;
}
return i == n;
}
void main_test(const int *v, size_t n)
{
int *v1 = memcpy(malloc(n * sizeof(int)), v, n * sizeof(int));
evenodd(v1, n);
if (is_evenodd(v1, n)) {
printf("Ok!\n");
}
else {
printf("Fail!\n");
}
free(v1);
}
int main(void)
{
main_test((int[]) { 1 }, 0);
main_test((int[]) { 1 }, 1);
main_test((int[]) { 2 }, 1);
main_test((int[]) { 1, 2 }, 2);
main_test((int[]) { 1, 3 }, 2);
main_test((int[]) { 2, 1 }, 2);
main_test((int[]) { 2, 4 }, 2);
main_test((int[]) { 1, 3, 2 }, 3);
main_test((int[]) { 1, 4, 2 }, 3);
size_t n = 1000;
int *a = malloc(n * sizeof *a);
for (size_t i = 0; i < n; ++i) {
a[i] = rand();
}
main_test(a, n);
free(a);
return 0;
}
You can try the following code :
int even_index = 0; //start index
int odd_index = 4; //end index
for(int i=0;i<5;i++){
if(ptr[i] % 2 == 0){
int temp = ptr[even_index];
ptr[even_index++] = ptr[i]; //swapping values and incrementing even_index
ptr[i] = temp;
}else{
int temp = ptr[odd_index];
ptr[odd_index--] = ptr[i];
ptr[i] = temp;
}
}
or you can also count the number of even numbers in the digits during input and assign odd_value = even_num // number of even digits
ok so I solved it....
see the even numbers always end up in even indexes so we need to set a pointer on those even index(current index) and search for any even number after the current index.
if we find any(even number) we swap the current index value with the even number.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n,j,i,num,v;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
scanf("%d", &v);
ptr[i] = v;
}
i=0;
j=0;
while(i<n && j<n){
if (ptr[j]%2==0){
num=ptr[i];
ptr[i]=ptr[j];
ptr[j]=num;
i+=2;
j=i;
}
j++;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
If this problem is to sort an array in order (descending) and then further place all even values before odd values I would recommend:
Sort the array
Swap and shift any odd numbers with the even numbers
Here's a naive implementation:
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (arr[i] < arr[j]) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
int lastEven = 0;
for (int i = 0; i < len - 1; i++) {
if (arr[i] % 2 && (arr[i + 1] % 2 == 0)) {
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
lastEven = i;
} else if (arr[i] % 2 == 0 && lastEven-i > 1) {
for (int j = i; j > lastEven; j--) {
tmp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = tmp;
}
lastEven++;
}
}
Given the input [13,11,10,17,18] this will first sort the array ([18,17,13,11,10]) then separate the evens and odds ([18,10,17,13,11])

Inserting elements to array in C

My task is: If we look at any two neighbour values in an array, if the one on the right is two times greater than the one on the left, their average should be inserted between them and the new array consisting of old and new elements should be printed. I have a problem with moving the other elements after average.And using special functions or libraries is not allowed.I am beginner, and I hope you could help.
#include <stdio.h>
int main() {
int n, i, j;
double a[100], average;
printf("Enter the number of elements: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%lf", &a[i]);
}
for (i = 0; i < n; i++) {
if ((a[i + 1] / a[i]) == 2) {
for (i = j = 0; i < n; ++i)
b[j++] = a[i];
if (a[i + 1] / a[i] == 2)
average = (a[i + 1] + a[i]) / 2;
b[j++] =average;
}
}
for (i = 0; i < j; ++i) {
printf("%lf\n", b[i]);
}
}
A simple way to solve your problem is adding double b[199];, and copying everything over:
for (i = j = 0; i < n; ++i) {
b[j++] = a[i];
if (...) b[j++] = ...; /* Append the average to b. */
}
for (i = 0; i < j; ++i) {
printf("%lf\n", b[i]);
}
If you really want to move the elements forward within a itself, then you can do it by adding an inner for loop (and an additional loop variable int k;) which copies the elements one-by-one:
for (k = n++; k > i; --k) {
a[k] = a[k - 1];
}
In order to insert an element in an array, you must copy the elements with higher index from the last one down.
Also avoid dividing by a[i] that can be zero, and properly handle 0,0 that match the criteria for inserting the average, and skip the inserted value to avoid inserting more zeros.
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, j;
printf("Enter the number of elements: ");
if (scanf("%d", &n) != 1 || n <= 0)
return 1;
double *a = malloc(sizeof(*a) * (2 * n - 1)); // allocate the array to the maximum size
if (a == NULL)
return 0;
for (i = 0; i < n; i++) {
if (scanf("%lf", &a[i]) != 1)
return 1;
}
for (i = 1; i < n; i++) {
if (a[i] == a[i - 1] * 2) {
for (j = n; j > i; j--)
a[j] = a[j - 1];
a[i] = (a[i - 1] + a[i]) / 2;
n++; // increase number of elements
i++; // skip the new value
}
}
for (i = 0; i < n; ++i) {
printf("%f\n", a[i]);
}
free(a);
return 0;
}
To insert an element in a specific position you would need to move the rest of the array. However doing it many times is expensive and you may prefer to use an array to store the position at which you want to insert the elements and then insert them all at once.
Alternatively you can create a new array where to copy the original plus the new values.
However there's an easier and faster way, that is adding the new values straight away, while you fill the original array. Here's a program that does that.
#include <stdio.h>
#define SIZE 100
int main() {
int i, n, avg = 0;
double a[SIZE];
while( puts("Enter the number of elements:") && (scanf("%d", &n) != 1 || n < 1 || n > SIZE) );
scanf("%lf", &a[0]);
for(i = 1; i < n+avg && i < SIZE-1 && scanf("%lf", &a[i]) == 1; i++) {
if( a[i] == a[i-1] * 2 ) {
a[i+1] = a[i];
a[i] = (a[i] + a[i-1]) / 2;
++avg;
++i;
}
}
for(i = 0; i < n+avg; i++) {
printf("%lf\n", a[i]);
}
return 0;
}

How to print diagonal star pattern in C

I'm confused to print this type of pattern given below:
* *
* *
*
* *
* *
I've tried this:
#include <stdio.h>
int main()
{
int n;
printf("Enter the value of base\n>>> ");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
for (int j = 0; j + n; j++)
{
if (// ??? )
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
return 0;
}
but I don't know what is the condition of if statement
Help Me to solve this please
The pattern consists of exactly n * 2 - 1 rows and columns. So you can run an outer loop to iterate through rows with structure for(i=1; i<= count; i++); where count = n * 2 - 1. Each row contains exactly n * 2 - 1 columns. So, run inner loop as for(j=1; j<=count; j++). And inside this loop we need stars to be printed when row and column number both are equal (i.e. print star whenever if(i == j)) and if(j == count - i + 1). For example:
#include <stdio.h>
int main() {
int i, j, n;
int count;
printf("Enter n: ");
scanf("%d", &n);
count = n * 2 - 1;
for (i = 1; i <= count; i++) {
for (j = 1; j <= count; j++) {
if (j == i || (j == count - i + 1)) {
printf("*");
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
To not change any code and answer your question "what goes in the if"
n - 1 - i == j || j == i
this does
This will work fine !! :)
#include<iostream>
using namespace std;
int main()
{
int n,m=0;
int m2=0;
cin>>n;
int f=-1,l=n;
for(int i=0;i<n;i++)
{
f=f+1;
l=l-1;
for(int j=0;j<n;j++)
{
if(j==f || j==l) cout<<"*";
else cout<<" ";
}
cout<<endl;
}
}

What is my C code not printing # in staircase pattern, this is from hackerrank, I did not pass all test cases, but i can't point out why?

Write a program that prints a staircase of size n.
I did not pass through all the test cases and don't understand where I made mistake.
This is my code:
void staircase(int n) {
char a[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if((i + j) > ((n / 2) + 1)) {
a[i][j] = '#';
printf("%c", a[i][j]);
} else {
printf(" ");
}
}
printf("\n");
}
}
Given Input
6
Expected Output
#
##
###
####
#####
######
Explanation:
The staircase is right-aligned, composed of # symbols and spaces, and has a height and width of n=6.
The problem is in the condition
if((i + j) > ((n / 2) + 1))
It should be
if(j >= n - i - 1) // or if(i + j >= n - 1)
To make this easier, I would create a helper function. Also, there's no need for the VLA a[n][n] that you don't even use for anything.
void repeat_char(int x, char ch) {
for(int i=0; i < x; ++i) putchar(ch);
}
void staircase(int n) {
for(int i = 1; i <= n; ++i) {
repeat_char(n - i, ' '); // or printf("%*s", n - i, "");
repeat_char(i, '#');
putchar('\n');
}
}
You do not need your a variable to do what you need. Here is a sample achieving what you want:
void staircase(unsigned n)
{
for (unsigned i = 0; i < n; ++i) {
for (unsigned j = 0; j < (n - i - 1); ++j)
printf(" ");
for (unsigned j = 0; j < (i + 1); ++j)
printf("#");
printf("\n");
}
}
The first loop is meant to cover every lines, then within it you make a loop which handles the spaces before the actual # symbols, and finally you make the loop handling the displaying of the symbols.
There is a much easier way of going about this than what you are trying to do:
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const int n = 6;
char* str = malloc(sizeof(*str)*(n + 1));
if (str == NULL) {
printf("Somthing wrong with memory!\n");
return 1;
}
memset(str, ' ', n);
str[n] = '\0';
for(int i = n - 1; i > -1; i--) {
str[i] = '#';
puts(str); //or maybe printf who cares
}
free(str);
return 0;
}

char() represetation of an array

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.

Resources