issues trying to make rows in c program - c

#include <stdio.h>
int prime(int limit,int col);
int main(){
int limit,col,count,i;
printf("Table of Primes\n");
printf("===============\n");
printf("Upper limit: ");
scanf("%d",&limit);
getchar();
printf("# of columns: ");
scanf("%d",&col);
count=prime( limit,col);
return 0;
}
int prime(int limit,int col){
int i,j,w;
for(w=0;w<col;w++){
for(i=2;i<=limit;i++){
for(j=2;j<=i;j++){
if(i%j==0){
break;
}
}
if(i==j){
printf("%d ",i);
}
}
printf("\n");
}
}
The code above is to find the amount of prime numbers between 2 and the user input numbers.
I have that working fine, but my issue is getting the Code to be put into columns (defined by # of columns)
I talked this over with my teacher and she said that I do not have to use a 2D array to accomplish this.
Can anyone please help me out?
Also the output is spouse to look like this:
Table of Primes
===============
Upper limit: 175
# of columns: 5
2 3 5 7 11
13 17 19 23 29
31 37 41 43 47
53 59 61 67 71
73 79 83 89 97
101 103 107 109 113
127 131 137 139 149
151 157 163 167 173
Thank you.

You can easily test the number of columns and print a newline. The function prime() also lacked a return value so I return w as the number of primes found. This is just a slight tweak to your prime() function.
#include <stdio.h>
#include <string.h>
int prime(int limit, int col) {
int i, j, w = 0;
for (i=2; i<=limit; i++) {
for (j=2; j<=i; j++) {
if (i%j == 0) {
break;
}
}
if (i==j) {
if (w++ % col == 0) // test number of columns
printf("\n");
printf("%7d", i); // specify field width
}
}
printf("\n");
return w;
}
int main(void) {
prime (173, 5);
return 0;
}
Program output:
2 3 5 7 11
13 17 19 23 29
31 37 41 43 47
53 59 61 67 71
73 79 83 89 97
101 103 107 109 113
127 131 137 139 149
151 157 163 167 173
I leave you to add the frills.

I suggest you to make separate functions for finding primes and displaying primes, so you will have more control on displaying those primes:
#include <stdio.h>
#include <math.h> // sqrt
int is_prime (int x);
void prime(int limit, int col);
int main ()
{
int limit, col;
printf("Table of Primes\n");
printf("===============\n");
printf("Upper limit: ");
scanf("%d",&limit);
getchar();
printf("# of columns: ");
scanf("%d",&col);
prime(limit, col);
printf("\n");
return 0;
}
int is_prime (int num)
{
int flag;
int i;
double p;
p = sqrt(num);
flag = 1;
if (num == 1)
return 0;
if (num == 2)
return flag;
if ((num % 2) == 0)
return 0;
for (i = 3; i <= p; i += 2)
{
if ((num % i) == 0)
{
flag = false;
return flag;
}
}
return flag;
}
void prime (int limit, int column)
{
int i, j, cnt;;
cnt = 0;
for (i = 0; i < limit; i++) {
if (is_prime(i)) {
printf("%4d ", i);
cnt++;
if ((cnt % column) == 0) {
printf("\n");
}
}
}
}
Of course you can change is_prime to your own function.

You can keep a variable to count how many numbers have been printed, then count % col will be zero every time count is a multiple of col, so this would work
#include <stdio.h>
void prime(int limit, int col);
int readint(const char *const message);
int main()
{
int limit,col;
printf("Table of Primes\n");
printf("===============\n");
limit = readint("Upper limit");
col = readint("# of columns");
prime(limit, col);
return 0;
}
int readint(const char *const message)
{
int value;
printf("%s> ", message);
while (scanf("%d", &value) != 1)
{
int chr;
printf("\tinvalid input\n");
printf("%s> ", message);
do {
chr = getchar();
} while ((chr != EOF) && (chr != '\n'));
}
return value;
}
void prime(int limit, int col)
{
int i, j;
int count;
count = 0;
for (i = 2 ; i <= limit ; i++)
{
for (j = 2 ; j <= i ; j++)
{
if (i % j == 0)
break;
}
if (i == j)
{
count += 1;
printf("%5d", i);
if ((count != 0) && (count % col == 0))
printf("\n");
}
}
}
Note that your code does not handle invalid input, I added that in this code, many people erroneously ignore scanf()'s return value, which is there for a reason.

Related

My loop doesn't loop through the array properly

A Fibonacci program that I wrote is not working correctly. This program should display the nth and nth series but this is what happened: the resulting output is:
1 8 13 21 34 55 1284926876 32762 -440528208 678 1285217672
Whereas it should be the 5th to 15th Fibonacci:
1 8 13 21 34 55 89 144 233 377 610 987
Here is the code:
#include <stdio.h>
int main() {
int jbf, c, a, b, m, s;
int hasil[100];
printf("============================ \n");
printf("| Program Fiboonanci ");
printf("| \n");
printf("============================ \n");
printf("enter number of rows : ");
scanf("%d", &jbf);
printf("starting from line: ");
scanf("%d", &m);
s = jbf + m;
if (jbf > 0) {
a = 0;
b = 1;
printf("%d ", b);
for (int i = 1; i < jbf; i++) {
c = a + b;
hasil[i] = c;
a = b;
b = c;
}
for (int i = m; i < s; i++) {
printf("%d ", hasil[i]);
}
} else {
printf("enter a value > 0");
}
}
You have
scanf("%d", &jbf);
for ( int i = 1; i < jbf; i++) {
s = jbf + m;
for ( int i = m; i < s; i++) {
it looks to me that s > jbf so you also print values which were not calculated. I would also check for s>99, you have int hasil[100];, but the indexes in that field are 0..99 not 1..100, but you index from 1, which is fine as long as you remember that you allocated space for 100 int values, but you can use only 99 of them right now.

Fill a nxn matrix in spiral order from 1 to n²

I was supposed to fill an nxn matrix in spiral order from 1 to n² using functions and then print its result but I don't know why my code doesn't function can anyone help please?
The principle was to create different functions, each filling the matrix at different time intervals then calling those functions in the main program which prints them in a spiral matrix.
#include <stdio.h>
#include <stdlib.h>
/* initializing the array and variables for the whole program*/
int A[5][5],top,bottom,left,right;
int FillRowForward(int A[5][5],int top,int left,int right,int z)
/*function that fills the top of the matrix from left to right*/
{ left = 0;
for(top=left,right=0;right<=4;right++)
{
A[top][right]=z;
z++;
}
return A[top][right];
}
int FillRowBackwards(int A[5][5],int bottom,int left,int right,int z)
/*fills the lower part from right to left*/
{ bottom =4;
for(left=bottom,right=4;right>=0;right--)
{
A[left][right-1]=A[left][right]+z;
}
return A[left][right-1];
}
int FillColumnDownward(int A[5][5],int top,int bottom,int left,int z)
/*fills the last column from top to bottom*/
{
left=0;
for(top=left,bottom=4;top<=4;top++)
{
A[top+1][bottom]= A[top][bottom]+z;
}
return A[top][bottom];
}
int FillColumnUpward(int A[5][5],int top,int bottom,int left, int z)
/*fills the first column from bottop to top*/
{
left =0;
for(bottom=left,top=0;bottom>=1;bottom--)
{
A[bottom-1][top]=A[bottom][top]+z
}
return A[bottom][top];
}
int main()
{
int i,j,k=1;
while(k<5*5){
int FillRowForward(int A[5][5],int top,int left,int right,int k);
top++;
int FillColumnDownward(int A[5][5],int top,int bottom,int right,int k);
right--;
int FillRowBackwards(int A[5][5],int bottom,int left,int right,int k);
bottom--;
int FillColumnUpward(int A[5][5],int top,int bottom,int left,int k);
}
//prints the matrix
for(i=0;i<=4;i++)
for(j=0;j<=4;j++)
printf("%d",A[i][j]);
return 0;
}
You have a number of problems like:
int FillRowForward(int A[5][5],int top,int left,int right,int k);
not being a function call and that you you never change k, i.e. you have an endless loop.
This solution uses a variable direction to track the current direction of filling the matrix.
#include <stdio.h>
#define ARRSIZE 10
int main()
{
int A[ARRSIZE][ARRSIZE] = { 0 };
int i=0, j=0;
int direction = 0;
for(int k = 1; k <= (ARRSIZE*ARRSIZE); ++k)
{
A[i][j] = k;
switch (direction)
{
case 0 : // Go rigth
if (((j + 1) == ARRSIZE) || (A[i][j+1] != 0))
{
// Switch direction
direction = 1;
++i;
}
else
{
++j;
}
break;
case 1 : // Go down
if (((i + 1) == ARRSIZE) || (A[i+1][j] != 0))
{
// Switch direction
direction = 2;
--j;
}
else
{
++i;
}
break;
case 2 : // Go left
if (((j - 1) == -1) || (A[i][j-1] != 0))
{
// Switch direction
direction = 3;
--i;
}
else
{
--j;
}
break;
case 3 : // Go up
if (((i - 1) == -1) || (A[i-1][j] != 0))
{
// Switch direction
direction = 0;
++j;
}
else
{
--i;
}
break;
}
}
for(i=0; i<ARRSIZE; i++)
{
for(j=0; j<ARRSIZE; j++)
printf("%4d",A[i][j]);
printf("\n");
}
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
36 37 38 39 40 41 42 43 44 11
35 64 65 66 67 68 69 70 45 12
34 63 84 85 86 87 88 71 46 13
33 62 83 96 97 98 89 72 47 14
32 61 82 95 100 99 90 73 48 15
31 60 81 94 93 92 91 74 49 16
30 59 80 79 78 77 76 75 50 17
29 58 57 56 55 54 53 52 51 18
28 27 26 25 24 23 22 21 20 19
You have a couple of problems here:
I suppose there is no need for global variables, so you can define everything in the main() function
As already pointed out "In main() you are only providing declarations of the functions, not calling them. "
You have an infinite loop in main() function because you never increased var k
Try to avoid using numbers in your function, use variables or symbolic constants instead. No difference on such small projects, but in bigger projects, you can easily confuse them, also if you want to change, you must change every value, etc.
Your functions are not doing what they are supposed to do. You can write something like this (I found my old program and modified it a bit):
#include <stdio.h>
void print_mat(int mat[][5], int m, int n)
{
int i,j;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
printf("%d\t", mat[i][j]);
}
printf("\n\n");
}
printf("\n");
}
void spiral(int mat[][5], int m, int n)
{
int i, k = 0, l = 0;
int counter = 1;
while(k < m && l < n)
{
for(i = l; i < n; i++)
{
mat[k][i] = counter++;
}
k++;
for(i = k; i < m; i++)
{
mat[i][n-1] = counter++;
}
n--;
if(k < m)
{
for(i = n-1; i >= l; i--)
{
mat[m-1][i] = counter++;
}
m--;
}
if(l < n)
{
for(i = m-1; i >= k; i--)
{
mat[i][l] = counter++;
}
l++;
}
}
}
int main()
{
int mat[5][5];
int n = 5;
spiral(mat,n,n);
print_mat(mat,n,n);
return 0;
}
Since you need to create different functions, you can try to divide this spiral() function into several smaller functions, it can be a good exercise.

To find and assign primes to an array

Hi I have made a simple program to print primes between 1 and 100 but I cannot figure a way to assign these values to an array of size 25 as we all know there are 25 primes between 1 and 100:
#include <stdio.h>
int main() {
int i, k;
for (i = 3; i < 100; i = i + 2) {
for (k = 2; k < i; k++) {
if (i % k == 0)
break;
}
if (i == k)
printf("%d\n", i);
}
}
Just create an array at the top, write to it, and then read out of it after you've found all your primes. Note that this could definitely be done more efficiently, but given the number of calculations you're doing, that's beside the point.
Code
#include<stdio.h>
int main() {
int primes[25];
int i, k;
int j = 0;
// find primes
for(i = 2; i < 100; i++) {
for (k = 2; k < i; k++) {
if (i % k == 0) {
break;
}
}
if (i == k) {
primes[j] = i;
j++;
}
}
// print primes
for (j = 0; j < 25; j++) {
printf("%d\n", primes[j]);
}
return 0;
}
Also note that 2 is prime, so you'll want to make sure that that's included in your output.
Output
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
Make an array before you begin, then create a variable that increments while each prime is found. It might look something like this:
#include <stdio.h>
int main() {
int primes[25];
primes[0] = 2;
int count = 1;
for (int i = 3; i < 100; i += 2) {
int k;
for (k = 2; k < i; k++) {
if (i % k == 0) break;
}
if(i == k) {
primes[count] = i;
count++;
}
}
}
Warning: this is a humorous answer, not to be taken seriously.
Just like we all know there are 25 primes between 1 and 100, we might as well know the magic value to avoid using an array at all:
#include <stdio.h>
int main() {
long long magic = 150964650272183;
printf("2");
for (int i = 3; magic; magic >>= 1, i += 2)
magic & 1 && printf(" %d", i);
printf("\n");
return 0;
}
Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Algorithm to determine whether a permutation can be generated by 2 parallel stacks

The setting is similar to the stack-sortable permutation problem discussed by Knuth before, but on permutation generation with stack.
I would like to write a program to determine whether a permutation is stack-generatable with 2 stacks instead of only 1.
This is actually a homework problem, which the requirement are as follows:
A permutation of 1 to n is a stack-generated permutation if and only
if it can be generated by pushing 1 to n onto a stack and popping them
o. For example, stack-generated permutation (2, 1, 3) can be
generated by doing operations push 1, push 2, pop, pop, push 3, pop.
In this problem, instead of using only one stack, we use two stacks:
every time you can push an element to either stack, or you can pop
element from either stack as long as it is non-empty. However, once an
element is popped, it cannot be pushed back to either stack again.
Your task is to determine whether a permutation can be generated by
using two stacks.
I know that if a permutation contain the pattern 4123, it cannot be generated. However, doing pattern matching seems very time consuming and likely out of my ability, not to mention that I do not know whether 4123 is the only pattern.
Currently I am trying to actually generate it with 2 stacks in order to determine whether a permutation can be generated, but my algorithm can only determine some of the stack-generatable permutation. Therefore I would like to know what is the correct algorithm for this problem. An working C code would of cause be amazing, but any tips, advise or pseudo code are also good enough. Thank you!
An example permutation to determine:
62 61 58 53 67 66 47 65 69 68 64 45 70 71 63 44 42 60 72 59 41 73 74 57 56 39 55 54 38 37 52 51 50 49 48 76 46 43 75 40 36 35 77 34 31 30 33 29 32 78 22 79 28 27 80 20 26 25 24 23 83 82 81 85 84 87 89 21 19 90 88 92 86 95 94 18 98 96 97 93 17 15 99 91 16 100 14 12 13 9 8 11 6 5 10 7 4 3 2 1
My current implementation(which is very messy and has no comment, so I do not recommend you reading it):
#include <stdio.h>
#define MAXSIZE 1000
typedef struct stack {
int data[MAXSIZE];
int top;
} Stack;
void push(Stack *s, int d);
int pop(Stack *s);
int peek(Stack *s);
int isEmpty(Stack *s);
int getPos(int d[], int size, int a);
void push(Stack *s, int d) {
(*s).top++;
(*s).data[(*s).top] = d;
}
int pop(Stack *s) {
int d = (*s).data[(*s).top];
(*s).top--;
return d;
}
int peek(Stack *s) {
if (!isEmpty(s)) {
return (*s).data[(*s).top];
} else return -1;
}
int isEmpty(Stack *s) {
if ((*s).top < 0) {
return 1;
} else return 0;
}
int getPos(int d[], int size, int a) {
int i = 0, al = -1;
for (i = 0; i < size; i++) {
if (d[i] == a) {
al = i;
}
}
if (al != -1) {
return al;
} else return -1;
}
int main() {
int t = 0;
scanf("%d", &t);
int i = 0;
for (i = 0; i < t; i++) {
int failed = 0;
int n = 0;
scanf("%d", &n);
int target[MAXSIZE];
int j = 0;
for (j = 0; j < n; j++) {
scanf("%d", &target[j]);
}
Stack s1, s2;
s1.top = -1;
s2.top = -1;
Stack *s1_ptr = &s1;
Stack *s2_ptr = &s2;
int output[MAXSIZE];
int oh = 0;
int th = 0;
int k = 1;
for (k = 1; k <= n; k++) {
int f1 = 0, f2 = 0;
int checkAgain = 1, pushed = 0;
while (checkAgain) {
checkAgain = 0;
if (k == target[th]) {
push(s1_ptr, k);
output[oh] = pop(s1_ptr);
oh++;
th++;
pushed = 1;
} else if (!isEmpty(s1_ptr) && peek(s1_ptr) == target[th]) {
output[oh] = pop(s1_ptr);
oh++;
th++;
checkAgain = 1;
} else if (!isEmpty(s2_ptr) && peek(s2_ptr) == target[th]) {
output[oh] = pop(s2_ptr);
oh++;
th++;
checkAgain = 1;
}
}
if (!pushed) {
if (isEmpty(s1_ptr)) {
push(s1_ptr, k);
} else if (isEmpty(s2_ptr)) {
push(s2_ptr, k);
} else {
int s1l = -1, s2l = -1;
if (peek(s1_ptr) >= 0) {
s1l = getPos(target, n, peek(s1_ptr));
}
if (peek(s2_ptr) >= 0) {
s2l = getPos(target, n, peek(s2_ptr));
}
int kl = getPos(target, n, k);
int canPush1 = 0, canPush2 = 0;
if (kl < s1l) {
canPush1 = 1;
}
if (kl < s2l) {
canPush2 = 1;
}
if (canPush1 && canPush2) {
if (s1l < s2l) {
push(s1_ptr, k);
} else {
push(s2_ptr, k);
}
} else if (canPush1 && !canPush2) {
push(s1_ptr, k);
} else if (!canPush1 && canPush2) {
push(s2_ptr, k);
} else {
failed = 1;
break;
}
}
}
}
if (failed) {
printf("No\n");
continue;
}
int m = th;
for (m = th; m < n; m++) {
if (peek(s1_ptr) == target[th]) {
output[oh] = pop(s1_ptr);
oh++;
th++;
} else if (peek(s2_ptr) == target[th]) {
output[oh] = pop(s2_ptr);
oh++;
th++;
} else {
failed = 1;
break;
}
}
if (th == n) {
printf("Yes\n");
} else {
printf("No\n");
}
}
return 0;
}
I solved it with the help from two Chinese sites, as there is actually a similar question in NOIP2008, which deals with permutation sortable by 2 stacks. The solution for generatable permutation is pretty similar. I can write more later if someone is interested about the solution.
The two sites that helped me:
NOIP2008 双栈排序 twostack 题解
NOIP2008提高组复赛题解
My solution:
#include <stdio.h>
#include <string.h>
#define MAXN 1002
int const NEINF = -1;
int targetPermutation[MAXN];
int precalculatedMax[MAXN];
int bipartiteGraph[MAXN];
int adjacencyMatrix[MAXN][MAXN];
int N;
int noSolution = 0;
void reset();
void colouringAndCheckConflict(int i, int c);
void checkAdjacencyAndDye();
void colouringAndCheckConflict(int i, int c) {
bipartiteGraph[i] = c;
int j;
for (j = 1; j <= N; j++) {
if (adjacencyMatrix[i][j]) {
if (bipartiteGraph[j] == c) //conflict : not a bipartite graph
{
noSolution = 1;
return;
}
if (!bipartiteGraph[j]) {
colouringAndCheckConflict(j, 3 - c); // color the opposite color 1<->2
}
}
}
}
void checkAdjacencyAndDye() {
/* 231 for sortable
* i<j<k, S[k]<S[i]<S[J]
* 312 for generatable
* k<i<j, S[i]<S[J]<S[k]
* DONE: Modify the algorithm to make it right for generation instead of sortable
*/
int i, j;
precalculatedMax[0] = NEINF;
for (i = 1; i <= N; i++) {
precalculatedMax[i] = targetPermutation[i];
if (precalculatedMax[i - 1] > precalculatedMax[i])
precalculatedMax[i] = precalculatedMax[i - 1];
}
for (i = 1; i <= N - 1; i++) {
for (j = i + 1; j <= N; j++) {
if (targetPermutation[i] < targetPermutation[j] && precalculatedMax[i - 1] > targetPermutation[j]) {
adjacencyMatrix[i][j] = adjacencyMatrix[j][i] = 1;
}
}
}
for (i = 1; i <= N; i++) {
if (!bipartiteGraph[i] && !noSolution) {
colouringAndCheckConflict(i, 1);
}
}
}
void reset() {
memset(adjacencyMatrix, 0, sizeof(adjacencyMatrix));
memset(bipartiteGraph, 0, sizeof(bipartiteGraph));
memset(targetPermutation, 0, sizeof(targetPermutation));
memset(precalculatedMax, 0, sizeof(precalculatedMax));
N = 0;
noSolution = 0;
}
int main() {
int t;
scanf("%d", &t);
int k;
for (k = 1; k <= t; k++) {
int i;
scanf("%d", &N);
for (i = 1; i <= N; i++) {
scanf("%d", &targetPermutation[i]);
}
checkAdjacencyAndDye();
if (!noSolution) {
printf("Yes\n");
} else {
printf("No\n");
}
reset();
}
return 0;
}

Creating a stem-and-leaf diagram

I am trying to make a program in C (for school purposes) that reads numbers from interval [0, 99] and makes a stem-and-leaf diagram out of them with tens on the beginning of a row and followed by all the units.
Here is example of input:
1 2 5 2 25 27 93 4 93 93 58 51
and output should be:
0 | 12245
2 | 57
5 | 18
9 | 333
and here's my code:
// uloha-9-5.c -- Tyzden 9 - Uloha 5
// Adam Kotvas, 18.11.2015 10:02:12
#include <stdio.h>
int main()
{
int n[100],i=0,j=0,l=0,desiatky[10],temp=0,k=0;
while(scanf("%d",&n[i])>0)
{
if(n[i]>99 || n[i]<0){
continue;
}
i++;
}
for(j=0;j<=10;j++)
{
desiatky[j]=0;
}
for(j=0;j<i;j++)
{
desiatky[(n[j]/10)%10]=1;
}
for(k=0;k<i;k++)
{
for(j=0;j<i;j++)
{
if(n[j]>n[j+1] && j!=i-1)
{
temp=n[j];
n[j]=n[j+1];
n[j+1]=temp;
}
}
}
for(j=0;j<10;j++)
{
if(desiatky[j]==1)
{
printf("%d | ",j);
for(l=0;l<i;l++)
{
if((n[l]/10)%10==j)
printf("%d",n[l]%10);
}
printf("\n");
}
}
return 0;
}
The problem is that it works good for all numbers in the given interval but when I try to submit it it says wrong output :(. Do you have any idea on what could be possibly wrong with this program?
Your code is a bit epic. More to the point:
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *av, const void *bv) { return *(int*)av - *(int*)bv; }
int main(void) {
unsigned n[1000000], i = 0, x;
while (scanf("%d", &x) == 1) if (x < 100) n[i++] = x;
if (i == 0) return 0;
qsort(n, i, sizeof n[0], cmp);
unsigned k = 0;
while (k < i) {
unsigned d = n[k] / 10;
printf("%d|", d);
while (k < i && n[k] / 10 == d) printf("%d", n[k++] % 10);
printf("\n");
}
return 0;
}

Resources