C program for below pyramid If possible JAVA code also [closed] - c

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 7 years ago.
Improve this question
Desired Output
1234554321
1234__4321
123____321
12______21
1________1
Code
#include<stdio.h>
int main()
{
int num,c,sp,r=1;
printf("Enter loop repeat number(rows): ");
scanf("%d",&num);
printf("\n");
for(; num>=1; num--,r++)
{
for(c=1; c<=num; c++)
printf("%d",c);
for(sp=r; sp>1; sp--)
printf("_");
for(sp=r; sp>1; sp--)
printf("_");
for(c=num; c>=1; c--)
printf("%d",c);
printf("\n");
}
}
I am looking for other alternative codes which are less complex. Any help would be appreciated.

Rather than making multiple calls to printf, it seems cleaner to construct the string yourself:
#include<stdio.h>
#include<stdlib.h>
int
main( int argc, char ** argv )
{
unsigned num = argc > 1 ? strtol( argv[1], NULL, 0 ) : 5;
char digits[] = "123456789_987654321";
char *rhs = digits + sizeof digits - 1 - num;
if( num > 9 ) {
fprintf( stderr, "argument must be < 10" );
exit( EXIT_FAILURE );
}
digits[num] = '\0';
for( ; num > 0; ) {
printf( "%s%s\n", digits, rhs );
digits[ sizeof digits - 1 - num ] = '_';
digits[ --num ] = '_';
}
return 0;
}

Your lines are symmetrical. You can use a recursive function where you print before and after recursing to achieve this:
#include <stdlib.h>
#include <stdio.h>
void line(int i, int n, int m)
{
if (i < n) {
putchar(i > m ? '_' : '0' + (i + 1) % 10);
line(i + 1, n, m);
putchar(i > m ? '_' : '0' + (i + 1) % 10);
}
}
int main(int argc, char **argv)
{
int i, n = 0;
if (argc > 1) n = atoi(argv[1]);
if (n <= 0) n = 5;
i = n;
while (i--) {
line(0, n, i);
putchar('\n');
}
return 0;
}
The lines themselves are controlled with a regular loop. The newline '\n' can't be part of the recursive function, because it doesn't fit the symmetric pattern; it has to be printed explicitly. This version takes the size of the pyramid from the command line with a default of 5.

Something like this should do:
#include <stdio.h>
int main()
{
int num;
printf("Enter loop repeat number(rows): ");
scanf("%d",&num);
printf("\n");
for (int row = 0; row < num; ++row) {
int columnLimit = num - row;
for (int column = 1; column <= columnLimit; ++column) {
printf("%d", column);
}
for(int spacing = 0; spacing < row; ++spacing) {
printf("__");
}
for (int column = columnLimit; column > 0; --column) {
printf("%d", column);
}
printf("\n");
}
}
IDE One

#include<stdio.h>
int main()
{
int num,c,sp;
printf("\n");
for(num =5; num>=1; num--)
{
for(c=1; c<=5; c++)
{
if(c>num)
{
printf("_");
}
else
{
printf("%d",c);
}
}
for(c=5; c>=1; c--)
{
if(c>num)
{
printf("_");
}
else
{
printf("%d",c);
}
}
printf("\n");
}
}

Use ternary operator for simplification, this way you only need two lines
inside of the inner loop code,
val = column <= num ? column : limit - column + 1;
printf("%c", val > row ? '_' : val + 0x30);
Here it is:
int main(){
int num,column,row,limit,val;
printf("Enter loop repeat number(rows): ");
scanf("%d",&num);
printf("\n");
limit = num * 2;
for (row = num; row > 0; --row){ //num times
for (column = 1; column <= limit; ++column){
val = column <= num ? column : limit - column + 1;
printf("%c", val > row ? '_' : val + 0x30);
}
printf("\n");
}
return 0;
}
The downside is you still have to call printf multiple times. But obviously the code is really compact!

A revisited one that asks the user for the max number...
int main()
{
int num;
printf("Enter loop repeat number(rows, 9 max): ");
scanf("%d",&num);
if (num > 9) num = 9;
int i,j;
for (i=num ; i>0 ; i--) {
for(j=1 ; j<=num ; j++) {
printf("%c", j>i ? '_':0x30+j);
}
for(j=num ; j>=1 ; j--) {
printf("%c", j>i ? '_':0x30+j);
}
printf("\n");
}
return 0;
}
0x30 is the ascii code for 0, adding j gives 1 to num.
edit a recursive bonus ...
int num; // global to avoid putting it in the recursive function
void recursive(int i, int j) {
printf("%c", i>j ? '_':0x30+i);
if (i<num) recursive(i+1, j);
printf("%c", i>j ? '_':0x30+i);
if(i==1) {
printf("\n");
if (--j > 0) recursive(1, j);
}
}
To be called as recursive(1, num);
int main(int argc, char **argv)
{
printf("Enter loop repeat number(rows, 9 max): ");
scanf("%d",&num);
if (num > 9) num = 9;
recursive(1, num);
return 0;
}

Assuming (but not checking!) that input does not exceed 9:
#include<stdio.h>
int main()
{
int num, r, c;
printf("Enter loop repeat number(rows): ");
scanf("%d",&num);
printf("\n");
for(r=num; r>=1; row--)
{
for(c=1; c<=num; c++)
putc(c<=r ? ('0'+c) : '_');
for(c=num; c>=1; c--)
putc(c<=r ? ('0'+c) : '_');
putc("\n");
}
}

The question seems to assume that it won't go above an input of 9, so I'll assume the same ...
int num=5; // Set as required
int max=9;
char leftNums[10] = "123456789";
char rightNums[10] = "987654321";
char pyramid[17] = "________________";
int rightStart = max - num;
for (int row=0; row<num; row++) {
int colLimit = num - row;
printf("%*.*s", colLimit, colLimit, leftNums);
printf("%*.*s", 2*row, 2*row, pyramid);
printf("%*.*s\n", colLimit, colLimit, &rightNums[rightStart+row]);
// Or, if you prefer for the last line:
// printf("%*.*s\n", colLimit, colLimit, rightNums+rightStart+row);
}
Notes:
You can obviously easily play around with letters, numbers and so on in this approach.
If you want to go above 9, you'll probably want to use letters rather than numbers ...
IDEone.com

This works until 9 rows:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int num, cols;
int i, j;
printf("Enter loop repeat number(rows): ");
scanf("%d",&num);
printf("\n");
if (num<10)
{
cols=num*2;
char **matrix = malloc(num*sizeof(char *));
for(i=0; i<num; i++)
{
matrix[i] = malloc(cols*sizeof(char *));
memset(matrix[i], '_', cols);
for (j=0; j<num; j++)
{
if (j<(num-i))
{
matrix[i][j] = (j+1)+0x30;
matrix[i][cols-j-1] = matrix[i][j];
}
}
}
for (i=0; i<num; i++)
{
for (j=0; j<cols; j++)
printf("%c", matrix[i][j]);
printf("\n");
free(matrix[i]);
}
free(matrix);
}
else
{
printf("Max allowed rows = 9\n");
}
return 0;
}
IDE One

Related

Prime factors of a number without using a flag variable?

I tried finding prime factors of a number without using a flag variable but I don't know what's the fault in the code.
#include <stdio.h>
int main(int argc, char const *argv[])
{
int num, i, j;
printf("Enter a number: ");
scanf("%d", &num);
for (i = 2; i <= num; i++)
{
if (num % i == 0)
{
for (j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
printf("%d", i);
}
}
}
}
return 0;
}
You have to print values that are factor of num and prime.
In your code you are printing factors of num, but not prime by printing i after seeing that a j that divids i exists.
Instead of that, you should check for all candidates of j and print i after seeing all js tested don't divide i.
Also you may want to add some delimiters between the factors to print.
Try this:
#include <stdio.h>
int main(int argc, char const *argv[])
{
int num, i, j;
printf("Enter a number: ");
scanf("%d", &num);
for (i = 2; i <= num; i++)
{
if (num % i == 0)
{
for (j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
break; /* stop iteration because a factor is found */
}
}
if (j > i / 2) /* check if the iteration ended not by finding factor but by checking all candidates */
{
printf("%d\n", i);
}
}
}
return 0;
}
Your approach feels a bit convoluted. Perhaps just do something like:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
unsigned num = argc > 1 ? strtoul(argv[1], NULL, 10) : 137;
int count = 0;
printf("%d = ", num);
for( unsigned i = 2; i <= num; i++ ){
while( num % i == 0 ){
printf("%s %d", count++ ? " *" : "", i);
num /= i;
}
}
printf(" ( %d factor%s )\n", count, count == 1 ? "" : "s");
return 0;
}

I am trying to find the duplicate of elements in an array

Can someone help me to figure out why my code is unable to accurately find the duplicate of elements?
#include <stdio.h>
int main() {
int array[10];
int count = 0;
printf("Enter a maximum of 10 values to store in an array: ");
for (int i = 0; i < 10; i++) {
scanf_s("%d", &array[i]);
}
for (int i = 0; i < 10; i++) {
for (int j = i + 1; j < 10; j++) {
if (array[i] == array[j]) {
count++;
break;
}
}
}
printf("The duplicates are : %d ", count);
}
I'm a beginner at this language so any advice and suggestions to help me solve this exercise will be much appreciated.
First of all the first loop runs 10 times even if the user enters less numbers. You can fix that by doing:
for (int i = 0; scanf_s("%d", &array[i]) == 1 && i < 10; i++);
Then the logic of the other two loops is wrong. I initially got wrong what you meant. I thought you wanted to know how many times a number is duplicated. So I wrote the wrong program and then modified it for your purposes. Here is your program:
#include <stdio.h>
int main() {
int n[10];
int dupes[5], d = 0;
int flag = 1, omg;
for ( omg = 0; scanf("%d", &n[omg]) == 1 && omg < 10; omg++);
for (int i = 0; i < omg; i++) {
for (int j = i+1; j < 10; j++) {
if( n[i] == n[j] ) {
if( d > 0 ) {
for(int k = 0; k < d; k++) {
if( n[i] == dupes[k] ) {
flag = 0;
break;
}
}
}
if( flag ) {
dupes[d] = n[i];
++d;
break;
}
else {
flag = 1;
break;
}
} // end outer if
}
}
printf("There are %d numbers that have at least one dupe\n", d);
return 0;
}
I named a variable omg out of desperation, writing this program was a nightmare. (Because it came from the ashes of a previous program)
Your code correctly determines the number of duplicate entries in the array.
If instead you want to determine the number of duplicated values, you must modify the algorithm:
#include <stdio.h>
int main() {
int array[10] = { 0 };
int count = 0;
printf("Enter a maximum of 10 values to store in an array: ");
for (int i = 0; i < 10; i++) {
scanf_s("%d", &array[i]);
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (array[i] == array[j]) {
if (i < j)
count++;
if (i != j)
break;
}
}
}
printf("There are %d duplicate values\n", count);
return 0;
}
I use a structure 'Number' which contains the number and its duplicate, then I fill the array and I put it in ascending order then I calculate the number of duplicate of each number and I fill in the strecture like this :
my code:
#include <stdio.h>
#define size 10
typedef struct Number
{
int number;
int duplicate;
}Number;
int main()
{
int array[size];
Number array2[size];
int count = 0;
printf("Enter a maximum of 10 values to store in an array: ");
for (int i = 0; i < size; i++)
{
scanf("%d", &array[i]);
}
int temp=size;
int temppppp=0;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(array[i]>array[j])
{
temppppp=array[i];
array[i]=array[j];
array[j]=temppppp;
}
}
}
printf("\n\n");
for (int i = 0; i < size; i++)
{
printf("[%d]",array[i]);
}
printf("\n\n");
int i=0;
int j=0;
while(i<size)
{count=1;
while(i<(size-1)&&array[i]==array[i+1])
{
count++;
i++;
}
if(count>=2)
{
array2[j].number=array[i-1];
array2[j].duplicate=count;
j++;
}
i++;
}
int p=0;
while(p<j)
{
printf("\n[%d] has duplicated %d times !\n",array2[p].number,array2[p].duplicate);
p=p+1;
}
printf("\n\n");
printf("\nThere are %d duplicate values\n", j);
}

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

Is there any method to print the value that user input with array?

It prints the wrong number/random number. What I want is to print numbers higher than 75.
int main() {
int array[5];
int num, i;
for (i = 1; i <= 5; i++) {
printf("Input Num %d : ", i);
scanf("%d", &num);
}
if (num >= 75) {
printf("%d\n", array[i]);
}
return 0;
}
Please use if within "for" loop. and please change "array" to "arr" or another name. The array will be a keyword in c++ sometime. should not use "array" to name a variable. here is my solution:
int main() {
int arr[5];
int num, i;
for (i = 1; i <= 5; i++) {
printf("Input Num %d : ", i);
num = 0;
scanf("%d", &num);
arr[i-1] = num;
}
for (i = 1; i <= 5; i++) {
if (arr[i - 1] >= 75) {
printf("%d\n", arr[i - 1]);
}
}
return 0;
}
You have a couple of errors:
You iterate over the wrong set. Arrays in C start from 0, NOT 1.
You never set any value for array. What should it contain then? Random stuff of course. You could avoid it by initializing your array to zero. That way you know you are not writing to your array if you get zeros in your output.
Code:
#include <stdio.h>
int main() {
int array[5] = {};
int num = 0,i;
for ( i = 0; i <5; i++) {
printf("Input Num %d : ",i );
scanf("%d",&num );
array[i] = num;
}
for ( i = 0; i <5; i++) {
if (array[i] >= 75) {
printf("%d\n",array[i]);
}
}
return 0;
}

how to make a christmas tree using loop in c program

I'm a freshmen student and we have an activity in intro pro.. We were tasked to create a Christmas tree using a loop...
I have my code here:
#include<stdio.h>
int main ()
{
int rows,a,b,space;
clrscr();
printf("Enter a number of rows:");
scanf("%d",&rows);
space=rows-1
for(b=space;b>=1;b--)
{
for(a=rows;a>=1;a--)
space--;
printf("");
for(a=2*(rows-b)-1;a>=1;a--)
printf("*",a);
printf("\n");
space = space-1;
}
getche();
return 0;
}
This code was given to us by our professor... the program runs, but the output is wrong. Can you help me?
when i run this program, the output was like this:
*
***
*****
******
*******
You have to find a pattern. Say you want a tree with n rows. Last row is going to have 2n-1 stars. Row before it will have 2n-3 and so on. To print a row, first you print a number of spaces, then a number of stars. For last row, you print 0 spaces and 2n-1 stars. For row before it, you print 1 space and 2n-3 stars and so on.
for(int i = 0; i < n; i++)
{ for(int j = i + 1; j < n; j++)
printf(" ");
for(int j = 0; j <= 2*i; j++)
printf("*");
if(i < n - 1) puts("");
}
The Code is a little bit to messed up for me, but this should work:
#include<stdio.h>
int main() {
/*Variables*/
int rows, starNumber, spaceNumber;
int rowCount, spaceCount, starCount, treeTrunkCount, treeTrunkSpaceCount;
printf("Enter Rows:\n>");
scanf("%d",&rows);
for(rowCount = 1; rowCount <= rows; rowCount++) {
starNumber = rowCount * 2 - 1;
spaceNumber = rowCount + rows - starNumber;
for(spaceCount = 0; spaceCount < spaceNumber; spaceCount++)
printf(" ");
for(starCount = 0; starCount < starNumber; starCount++)
printf("%c",'*');
printf("\n");
}
for(treeTrunkCount = 0; treeTrunkCount < 3; treeTrunkCount++) {
for(treeTrunkSpaceCount = 0; treeTrunkSpaceCount < (rows * 2 + 1)/2; treeTrunkSpaceCount++)
printf(" ");
printf("%c\n",'*');
}
}
This is the simplest solution to your program..
#include <stdio.h>
int main()
{
int i=-1,j=0,rows;
printf("Enter Rows:\n");
scanf("%d",&rows);
while(j++<rows) // Moving pointer for the first '*'
{
printf(" ");
}
printf("*"); // This prints the first '*'
while(++i<rows)
{
for(j=-2;++j<rows-i;) // This loop will print Spaces before '*' on each row
printf(" ");
for(j=0;++j<2*i;) // This loop will print * on each row
{
printf("*");
}
printf("\n"); // This printf will take you to the next Line
}
}
This is the shortest and simplest solution for your question:
#include<stdio.h>
#include<conio.h>
void main(){
int count;
int i,j;
printf("enter the numbers of line");
scanf("%d",&count);
for(i=1;i<=count;i++){
for(j=1;j<=i;j++){
printf("*");
}
printf("\n");
}
getch();
}
You forgot a space between "".
for(a=rows;a>=1;a--)
space--;
printf("");
should be
for(a=rows;a>=1;a--)
space--;
printf(" ");
#include <stdio.h>
int main() {
int n = 50;
for (int i = 0; i <= n; ++i) {
for (int k = i; k < n; ++k)
printf(" ");
for (int j = 0; j < i; ++j)
printf("*");
for (int j = 1; j < i; ++j)
printf("*");
printf("\n");
}
for (int l = 1; l < n/2; ++l) {
for (int i = 1; i < n; ++i)
printf(" ");
printf("[|]\n");
}
return 0;
}
A simple tree can be made up with for loop, Christmas may need more symbol...
//Linux C program to print a tree
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>
int pcenter(char *s) {
struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
int ct = w.ws_col;
int sl = strlen(s) / 2;
printf("%*s%*s\n", ct / 2 + sl, s, ct / 2 - sl, "");
return 0;
}
int ptree(char s, char t, int l, int r) {
int i;
for (i = 1; i <= l; i++) {
int j = 2 * i - 1;
char *p = malloc(j);
memset(p, s, j);
pcenter(p);
free(p);
}
for (i = 1; i <= r; i++) {
int j = 1;
char *p = malloc(j);
memset(p, t, j);
pcenter(p);
free(p);
}
return 0;
}
int main() {
// system("clear");
ptree('*', '|', 10, 5);
return 0;
}
#include<stdio.h>
main()
{
int n,i, j, space=1;
printf("Enter the number of rows: ");
scanf("%d",&n);
space=n-1;
for(i=1;i<=n;i++)
{
for(j=1;j<=space;j++)
{
printf(" ");
}
space--;
for(j=1;j<=2*i-1;j++)
{
printf("*");
}
printf("\n");
}
for(i=1;i<=n-3;i++)
{
for(j=1;j<=10;j++)
{
printf(" ");
}
for(j=1;j<=1;j++)
{
printf("*");
}
for(j=1;j<=1;j++)
{
printf("*");
}
for(j=1;j<=1;j++)
{
printf("*");
}
printf("\n");
}
}
#include<stdio.h>
int main()
{
int i,j,k,l=1,a,b;
for(i=8;i>=0;i--)
{
for(j=0;j<=i;j++)
{
printf(" ");
}
k=0 ;
while(k<l)
{
printf("*");
k=k+1;
}
l=l+2;
printf("\n");
}
i=8;
for(b=0;b<=3;b++)
{
for(a=0;a<=i-1;a++)
{
printf(" ");
}
printf("***");
printf("\n");
}
}

Resources