Drawing a triangle with one loop (Revised) - c

The triangle should look like this
1
11
111
1111
11111
111111
the number of rows is entered by the user and then transforms to the function
Note: Without arrays, must be with one loop(while or for) and not nested loops
the closest I got is a code with 2 loop (but can`t think about how to do it with less loops)
int i,k;
for(i=1;i<=x;i++)
{
for(k=1;k<=i;k++)
{
printf("1");
}
printf("\n");
}
The above question was asked by someone but it was marked as off topic I don't know why..?
I came up with this solution tell me if it's correct or not?
int i=1,k=1;
while (i<=x)
{
if(k<=i)
{
printf("1");
k++;
continue;
}
i++;
k=1;
printf("\n");
}
thanks

You can replace loops(iteration) with recursion, try this(with one loop):
#include <stdio.h>
void draw(int depth)
{
int i;
if(depth <= 0) return;
draw(depth-1);
for(i = 0; i < depth; i++)
printf("1");
printf("\n");
}
int main()
{
draw(5);
return 0;
}
You can do it even without loop
#include <stdio.h>
void draw_num_char(int num)
{
if(num <= 0) return;
printf("1");
draw_num_char(num-1);
}
void draw(int depth)
{
int i;
if(depth <= 0) return;
draw(depth-1);
draw_num_char(depth);
printf("\n");
}
int main()
{
draw(5);
return 0;
}

Recursive solution, one loop, no arrays.
#include <stdio.h>
void liner(int line, int limit) {
int i;
if (line > limit)
return;
for(i=1; i<=line; i++)
printf("1");
printf("\n");
liner (line + 1, limit);
}
int main() {
int limit;
printf ("Enter number of lines ");
scanf ("%d", &limit);
liner (1, limit);
return 0;
}

Related

How to make this program considered as a recursive rfunciton

I have created the program that functionally works the way it is supposed to but I have to make it recursive and I was told that function void expand() is not considered as a recursive function. Any tips?
#include <stdio.h>
#include <string.h>
#define max_size 300
int main(){
char defstr[max_size]="The universe is ever expanding!";
int num, buff_num;
printf("Input how much to expand: ");
scanf("%d",&num);
buff_num=num;
expand(defstr, num, 0, 0);
return 0;
}
void expand(char str[max_size], int n, int dash, int i){
if(n>-1){
if(str[i+1]!='\0'){
printf("%c",str[i]);
for(int j=dash; j>0; j--)
printf("-");
expand(str, n, dash, i+1);
}
else if(str[i+1]=='\0'){
printf("%c", str[i]);
printf("\n");
expand(str, n-1, dash+1, 0);
}
}
}
The program is built to output this type of text depending on the user input of how many dashes.
T-h-e- -u-n-i-v-e-r-s-e- -i-s- -e-v-e-r- -e-x-p-a-n-d-i-n-g-!
T--h--e-- --u--n--i--v--e--r--s--e-- --i--s-- --e--v--e--r-- --e--x--p--a--n--d--i--n--g--!
T---h---e--- ---u---n---i---v---e---r---s---e--- ---i---s--- ---e---v---e---r--- ---e---x---p---a---n---d---i---n---g---!
It is a recursive function in that it calls itself. However, my guess is that is is supposed to print the entire string with dashes each time.
void expand(char *str, int num_dashes)
{
// End recursion
if (num_dashes < 0) return;
// Call recursively
expand(str, num_dashes - 1);
// Print entire string with dashes
for (int i = 0; str[i]; i++) {
if (i != 0) {
for (int j = 0; j < num_dashes; j++) {
fputc('-', stdout);
}
}
fputc(str[i], stdout);
}
puts("");
}

Flood it game, crash after some tries

Task is to create a flood-it game in a 20x60 game, starting in the upper left corner. Numbers are used instead of colours for ease.
So, the code seems to be working fine up to one point.
But after a certain amount of rounds, player plays and then it just crashes ("...stopped working") message.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
int k=0,l=0;
void BoardMaking(int A[20][60]){
int i,j;
srand(time(0));
for(i=0;i<20;i++){
for(j=0;j<60;j++){
A[i][j]=rand()%5 +1;
}
}
}
void Print_Board(int A[20][60]){
int i,j;
for(i=0;i<20;i++){
for(j=0;j<60;j++){
printf("%d",A[i][j]);
}
printf("\n");
}
}
int Player(){
int x;
printf("\ngive a number between 1-5\n");
scanf("%d",&x);
return x;
}
void Change(int A[20][60],int y,int x){
A[k][l]=x;
if(A[k][l+1]==y){
A[k][l+1]=x;
l++;
Change(A,y,x);
}
if(A[k][l-1]==y){
A[k][l-1]=x;
l--;
Change(A,y,x);
}
if(A[k-1][l]==y){
A[k-1][l]=x;
k--;
Change(A,y,x);
}
if(A[k+1][l]==y){
A[k+1][l]=x;
k++;
Change(A,y,x);
}
k=0;l=0;
}
int main(){
int y,x;
int A[20][60];
BoardMaking(A);
while(1){
Print_Board(A);
x=Player();
if (x==A[0][0]){
printf("give another number \n");
}
else if (x!=A[0][0])
{
y=A[0][0];
Change(A,y,x);
}
}
return 0;
}
There is no bound checking in your Change function.
When k = 0 and l = 0 this condition (on line 50) if(A[k-1][l]==y){ accesses A[-1][0] which is outside of allocated memory.
This is how you can check for illegal values of k and l. (I'm not completely sure your code works properly but it does not crash anymore with following changes.)
void Change(int A[20][60],int y,int x){
A[k][l]=x;
if(l < 59 && A[k][l+1]==y){
A[k][l+1]=x;
l++;
Change(A,y,x);
}
if(l > 0 && A[k][l-1]==y){
A[k][l-1]=x;
l--;
Change(A,y,x);
}
if(k > 0 && A[k-1][l]==y){
A[k-1][l]=x;
k--;
Change(A,y,x);
}
if(k < 19 && A[k+1][l]==y){
A[k+1][l]=x;
k++;
Change(A,y,x);
}
k=0;l=0;
}
Thanks, #RuudHelderman for suggesting bound checking for right and bottom border.

How to remove the last comma in comma separated prime numbers within a range?

I have the code for finding prime numbers within a range.
The problem is to remove the last comma.
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
printf("%d,",x);
}
}
But the output contains an extra comma in the last.
For example
2,3,5,7,
whereas the expected output is
2,3,5,7
Instead of flag you can decide directly what you want to print between numbers
And note that you can break out of the internal loop as soon as f is set to 1
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
const char* delim = "";
scanf("%d%d",&a,&b);
for(x=a; x<=b; (x++,f=0))
{
for(i=2; i<x; i++)
{
if(x%i==0)
{
f=1;
break; //no need to continue the checking
}
}
if(f==0) {
printf("%s%d",delim,x);
delim = ", ";
}
}
putchar('\n');
}
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
char backspace = 8;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
printf("%d,",x);
}
printf("\b"); // or printf("%c", backspace);
}
Add another flag, just a simple counter that tells you if you are printing the first time then check the flag to decide what to print, e.g.
#include<stdio.h>
int main()
{
int a,b,i,x,c,first=0,f=1;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
{
if(first==0){
printf("%d",x);
}else{
printf(",%d",x);
}
first++
}
}
}
Use a flag to detect the first occurrence of printf() and print the first number as such without any ,. For consecutive number printing precede with ,
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1,flag=0;//Flag to mark first occurrence
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
break;// Once the condition fails can break of the for loop as it fails for the prime number condition at the first case itself
}
}
if(f==0)
{
if(flag==0)
{//Check if it is first time
printf("%d",x);
flag = 1;//If so print without ',' and set the flag
}
else
printf(",%d",x);// On next consecutive prints it prints using ','
}
}
}
This method also avoids the , when only one number is printed.
Eg: When input is 2 and 4. It prints just 3 and not 3,
Simply you need odd number best practice for minimum loop is given below;
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
scanf("%d%d",&a,&b);
while (a < b)
{
if ( (a%2) == 1) {
printf("%d", a);
if ( (a + 1) < b && (a + 2) < b)
printf(",");
}
a = a + 1;
}
}
please check from the site
http://rextester.com/MWNVE38245
Store the result into a buffer and when done print the buffer:
#include <stdio.h>
#include <errno.h>
#define RESULT_MAX (42)
size_t get_primes(int * result, size_t result_size, int a, int b)
{
int i, x, f = 1;
size_t result_index = 0;
if (NULL == result) || (0 == result_size) || ((size_t) -1 == result_size))
{
errno = EINVAL;
return (size_t) -1;
}
for (x = a; x <= b; (x++, f = 0))
{
for (i = 2; i < x; i++)
{
if (x % i == 0)
{
f = 1;
break;
}
}
if (f == 0)
{
result[result_index] = x;
++result_index;
if (result_size <= result_index)
{
fprintf(stderr, "Result buffer full. Aborting ...\n");
break;
}
}
}
return result_index;
}
int main(void)
{
int a = 0, b = 0;
int result[RESULT_MAX];
scanf("%d%d", &a, &b);
{
size_t result_index = get_primes(result, RESULT_MAX, a, b);
if ((size_t) -1 == result_index)
{
perror("get_primes() failed");
}
else if (0 == result_index)
{
fprintf(stderr, "No primes found.\n");
}
else
{
printf("%d", result[0]);
for (size_t i = 1; i < result_index; ++i)
{
printf(", %d", result[i]);
}
}
}
return 0;
}
This example uses a simple fixed-size buffer, if this does not suite your needs replace it by a dynamic one.
This is more of a "language-agnostic" problem: "How do I output a comma-separated list without a final comma?" It is not specifically about prime numbers.
You seem to be thinking of you list as a series of [prime comma] units. It isn't. A better way to think of it is as a single prime as the head of the list, followed by a tail of repeated [comma prime] units.
Some pseudocode to illustrate the general idea:
outputList(theList)
separator = ", "
output(theList.firstItem())
while (theList.hasMoreItems())
output(separator)
output(theList.nextItem())
endwhile
return
/* this is just logic */
for(i=2;i<=n;i++)
{
k=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
k=1;
}
if(k==0)
{
c++;
c++;
}
}
System.out.println(c);
for(i=2;i<=n;i++)
{
k=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
k=1;
}
if(k==0)
{
System.out.print(i);
b++;
if(b!=c-1)
{
System.out.print(",");
b++;
}
}
}
}
}
//comma separated values
#include <bits/stdc++.h>
using namespace std;
int Prime(int a, int n){
bool prime[n+1];
memset(prime,true,sizeof(prime));
for(int p=2;p*p<=n;p++){
if(prime[p]==true){
for(int i=p*p ; i<=n; i+=p ){
prime[i] = false;
}
}
}
for(int i = 2;i<= n;i++){
if(i==2) cout<<i; // here is the logic first print 2 then for other numbers first print the comma then the values
else if(prime[i]) cout<<","<<i;
}
}
int main(){
int a =2 ;
int n = 30;
Prime(a , n);
}
#include <stdio.h>
int main()
{
int i, j, n, count;
scanf("%d", &n);
for(i=2; i<n; i++)
{
count=0;
for(j=2; j<n; j++)
{
if(i%j==0)
count++;
}
if(count==1)
printf("%d," i);
}
printf("\b \b");
}
\b is a nondestructive backspace. It moves the cursor backward, but doesn't erase what's there, it replaces it. For a a destructive backspace,
use "\b \b" i.e. a backspace, a space, and another backspace.
This Program prints all the prime number up to given number with comma separated

Reading in an array of 12 numbers with spaces in between each number - C programming

I am a new C programming student and am having trouble with a code I am currently working on. I need to ask the user for a 12 number barcode with spaces in between each value. Also, I will need to refer to each individual value in the array later on in the code. For example, if my array is x[12], I need to use x[1], x[2], and all other values to calculate the odd sum, even sum, etc. Below is my first function to read in the bar code using a for loop. Any assistance for the script of this function would help.
#include <stdio.h>
#define ARRAY_SIZE 12
int fill_array() {
int x[ARRAY_SIZE], i;
printf("Enter a bar code to check. Separate digits with a space >\n");
for(i=0; i<ARRAY_SIZE; i++){
scanf("% d", &x);
}
return x;
}
You should pass array to read as the argument and store what is read there.
Also note that % d is a invalid format specifier for scanf().
#include <stdio.h>
#define ARRAY_SIZE 12
/* return 1 if suceeded, 0 if failed */
int fill_array(int* x) {
int i;
printf("Enter a bar code to check. Separate digits with a space >\n");
for(i=0; i<ARRAY_SIZE; i++){
if(scanf("%d", &x[i]) != 1) return 0;
}
return 1;
}
int main(void) {
int bar_code[ARRAY_SIZE];
int i;
if(fill_array(bar_code)) {
for(i=0; i<ARRAY_SIZE; i++) printf("%d,", bar_code[i]);
putchar('\n');
} else {
puts("failed to read");
}
return 0;
}
Alternately, you can allocate an array in the function and return its address.
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 12
/* return address of array if succeeded, NULL if failed */
int* fill_array(void) {
int *x, i;
x = malloc(sizeof(int) * ARRAY_SIZE);
if (x == NULL) {
perror("malloc");
return NULL;
}
printf("Enter a bar code to check. Separate digits with a space >\n");
for(i=0; i<ARRAY_SIZE; i++){
if(scanf("%d", &x[i]) != 1) {
free(x);
return NULL;
}
}
return x;
}
int main(void) {
int *bar_code;
int i;
if((bar_code = fill_array()) != NULL) {
for(i=0; i<ARRAY_SIZE; i++) printf("%d,", bar_code[i]);
putchar('\n');
free(bar_code);
} else {
puts("failed to read");
}
return 0;
}

I don't see why this doesn't work

The goal of this code was to print a pyramid. First I print a certain number of spaces then print some stars to eventually make a pyramid.
For example to print a pyramid of 5 first it would print a star after 4 spaces then the start and end variables would be changed so the new start would 3 and the new end would be six and it would print 3 stars.
#include <stdio.h>
#include <stdlib.h>
void printSpaces(int num){
int i;
for(i=0; i<num;i++)
{
printf(" ");
}
}
void pyramid(int n){
int start=n,end=n+1;
int k;
while(start>0 && end<2*n)
{
printSpaces(start);
for (k=start; k<end;k++)
{
printf("*");
}
printf("\n");
start=n-1;
end=n+1;
}
}
int main(void) {
puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
pyramid(5);
return 0;
}
The only thing it seems to be doing printing a row of 2 stars over and over.
you set start to n-1, but the value of n never changes. That means that start will continuously be set to the same value, n-1(4). Same for end, your loop will never terminate.
void pyramid(int n){
int start=n,end=n+1;
int k;
while(start>0 && end<2*n)
{
printSpaces(start);
for (k=start; k<end;k++)
{
printf("*");
}
printf("\n");
start=n-1;
end=n+1;
}
}
Also, on first invocation, k will be 4 and end will be 6, hence two stars.
Your problem is right here:
start=n-1;
end=n+1;
it should be something like start = start + 1 ?
I don't understand your program perfectly but I can tell that this is your error.
Matt McNabb was very close.
The following code contains the correct fix
The main change is to step 'start' and 'end' rather than re-initializing them to the passed parameter
#include <stdio.h>
#include <stdlib.h>
void printSpaces(int num){
int i;
for(i=0; i<num;i++)
{
printf(" ");
}
}
void pyramid(int n){
int start=n,end=n+1;
int k;
while(start>0 && end<2*n)
{
printSpaces(start);
for (k=start; k<end;k++)
{
printf("*");
}
printf("\n");
start--; //<< corrected
end++; //<< corrected
}
}
int main(void) {
puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
pyramid(5);
return 0;
}
the procedure that you are using to decrement the value of the variables end and start are wrong
I found this code about patterns in c in this site
http://www.programmingsimplified.com/c-program-print-stars-pyramid
#include <stdio.h>
#include <stdlib.h>
void pyramid(int end){
int k,c;
for (k=1; k< end; k++) {
printf(" ");
end= end -1;
for (c=1; c<= 2 * k-1; c++)
printf("*");
printf("\n");
}
}
int main() {
pyramid(15);
return 0;
}

Resources