Printing pascal's triangle in C - c

I have to print the pascal's triangle given a certain number of levels desired. The max levels that will be asked for is 28. I am able to print the some of the rows correctly but then it starts printing negative numbers in the rest of my rows. I can't figure out why, help would be much appreciated!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printTriangle() {
int numLevels;
printf("Please enter how many levels of Pascal's Triangle you would like to see: ");
scanf("%d", &numLevels);
char pascalTriangle[28][28];
for (int k = 1; k <= numLevels; ++k) {
for (int i = 0; i < k; ++i) {
int val = (i == 0) || (i == k - 1) ? 1 : (pascalTriangle[k-1][i-1] + pascalTriangle[k-1][i]);
pascalTriangle[k][i] = val;
printf(" %d", val);
}
printf("\n");
}
}
int main() {
printTriangle();
}

Change char pascalTriangle[28][28]; to int pascalTriangle[28][28];. You're going over the max char value so it goes to negative.
There is no "array" type, only a collection of pointers. You can also change char to short, long, etc.
Also, change k <= numLevels to k < numLevels. This prevents the segmentation fault. To fix the logic, you have to change for(int i = 0; to for(int i = -1;
The fixed code is:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printTriangle() {
int numLevels;
printf("Please enter how many levels of Pascal's Triangle you would like to see: ");
scanf("%d", &numLevels);
long long pascalTriangle[28][28];
for (int k = 0; k < numLevels; ++k) {
for (int i = -1; i < k; ++i) {
long long val = (i == 0) || (i == k - 1) ? 1 : (pascalTriangle[k-1][i-1] + pascalTriangle[k-1][i]);
pascalTriangle[k][i] = val;
printf(" %lld", val);
}
printf("\n");
}
}
int main() {
printTriangle();
}

Related

C for condition tricks

I found a challenge on the internet and I'm really stuck.
The goal is to print 20 times _ by adding/changing only 1 character (only one operation performed in total):
#include <stdio.h>
int main(void)
{
int i;
int n=20;
for(i=0;i<n;i--)
{
printf("_");
}
return 0;
}
I have already found 1 solution but I can't find the last one? Is there some tricks I need to know about for loops ?
Replace i by n
#include <stdio.h>
int main()
{
int i, n = 20;
for (i = 0; i < n; n--)
printf("*");
getchar();
return 0;
}
Put - before i
#include <stdio.h>
int main()
{
int i, n = 20;
for (i = 0; -i < n; i--)
printf("*");
getchar();
return 0;
}
Replace < by +
#include <stdio.h>
int main()
{
int i, n = 20;
for (i = 0; i + n; i--)
printf("*");
getchar();
return 0;
}
Source: https://www.geeksforgeeks.org/changeadd-only-one-character-and-print-exactly-20-times/
to correct the posted code to only output 20 times, you could use:
#include <stdio.h>
int main(void)
{
int i;
int n=-20; // note the minus 20
for(i=0;i<n;i--)
{
printf("_");
}
return 0;
}
If it is allowed you could write:
n=10; for(i=0;i<n;i++){printf("__");}
or
n=10; for(i=0;i<n;i++){printf("_");printf("_");}

Storing Fibonacci numbers in an array (C)

Can't get my program to output the correct number. I feel like I am making a simple mistake. This is written in C.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
int list[n];
while(1)
{
scanf("%d", &n);
if(n == -1)
{
break;
}
else
{
for(i = 2; i < n; i++)
{
list[i] = list[i-1]+list[i-2];
}
printf("%d %d", i, list[i] );
}
}
}
(To make things simpler, I'm going to ignore dealing with input.)
First problem is turning on compiler warnings. Most C compilers don't give you warnings by default, you have to ask for them. Usually by compiling with -Wall. Once we do that, the basic problem is revealed.
test.c:6:14: warning: variable 'n' is uninitialized when used here [-Wuninitialized]
int list[n];
^
test.c:5:10: note: initialize the variable 'n' to silence this warning
int n, i;
^
= 0
1 warning generated.
int list[n] immediately creates a list of size n. Since n is uninitialized it will be garbage. You can printf("%d\n", n); and see, it'll be something like 1551959272.
So either n needs to be initialized, or you need to reallocate list dynamically as n changes. Dynamic allocation and reallocation gets complicated, so let's just make it a static size.
So we get this.
#include <stdio.h>
#include <stdlib.h>
int main() {
/* Allocate an array of MAX_N integers */
const int MAX_N = 10;
int list[MAX_N];
/* Do Fibonacci */
for(int i = 2; i < MAX_N; i++) {
list[i] = list[i-1]+list[i-2];
}
/* Print each element of the list and its index */
for( int i = 0; i < MAX_N; i++ ) {
printf("%d\n", list[i]);
}
}
That runs, but we get nothing but zeros (or garbage). You have a problem with your Fibonacci algorithm. It's f(n) = f(n-1) + f(n-2) with the initial conditions f(0) = 0 and f(1) = 1. You don't set those initial conditions. list is never initialized, so list[0] and list[1] will contain whatever garbage was in that hunk of memory.
#include <stdio.h>
#include <stdlib.h>
int main() {
/* Allocate an array of MAX_N integers */
const int MAX_N = 10;
int list[MAX_N];
/* Set the initial conditions */
list[0] = 0;
list[1] = 1;
/* Do Fibonacci */
for(int i = 2; i < MAX_N; i++) {
list[i] = list[i-1]+list[i-2];
}
/* Print each element of the list and its index */
for( int i = 0; i < MAX_N; i++ ) {
printf("%d\n", list[i]);
}
}
Now it works.
0 0
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34
Here is code snippet,
#include <stdio.h>
int main()
{
int MAX_SIZE = 100; //Initial value
int n, i;
int list[MAX_SIZE];
printf("Enter value of 'n'");
scanf("%d",&n);
if(n < 0){
printf("'n' cannot be negative number");
return 0;
}else if (n==1){
list[0]=0;
}else if(n == 2){
list[0]=0;
list[1]=1;
}else{
list[0]=0;
list[1]=1;
for(i = 2; i <= n; i++)
{
list[i] = list[i-1]+list[i-2];
}
}
//To view array elements
for(int i=0;i<n;i++){
printf("%3d",list[i]);
}
}
You don't have return in main function.
n must be defined previous. Otherwise it took random value from memory.
So, your list array is created with unknown value.
int list[n];
Also, this will never happends, becous n is declared, but not defined.
i < n;
Is this what you need?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int F[100];
F[0] = 0;
F[1] = 1;
int i = 2;
while(1)
{
if(i < 100)
{
F[i] = F[i-1] + F[i-2];
i++;
}
else
{
break;
}
}
i = 0;
while(1)
{
if(i < 100)
{
printf("%d ; ", F[i]);
i++;
}
else
{
break;
}
}
return 0;
}
You need to allocate memory on demand for each iteration. In your code, n is uninitalized which leads to unpredectiable behavior. Also you need to initialize list[0] and list[1] since this is the 'base' case.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
int* list; /* Declare a pointer to the list */
while(1)
{
scanf("%d", &n);
if(n == -1)
{
break;
}
else if ( n > 0 )
{
list = (int *) malloc( n * sizeof(int) );
list[0] = 1;
list[1] = 1;
for(i = 2; i < n; i++)
{
list[i] = list[i-1]+list[i-2];
}
printf("%d %d\n", i, list[i-1] );
free(list);
}
}
}

Basic C help using arrays and for loops

#include "stdafx.h"
#include "stdio.h"
#include <string.h>
void main() {
int Results[8];
int i = 0;
int max = 0;
int maxindex;
printf("Enter the results of your 7 leavin cert subjects: ");
do {
printf("\nSubject %d: ", i + 1);
scanf_s("%d", Results);
i++;
} while (i < 7);
for (i < 7; Results[i] > 0; i++)
if (Results[i] > max)
max = Results[i];
printf("The best grade is %d", max);
}
Hello, so basically I'm trying to print out the largest number(Best result) by using a for loop. However it keeps telling me the that the best result is 0.
Does anybody know what I'm doing wrong. Any help would be greatly appreciated.
There are 2 major problems in your code:
You read all numbers into Results[0] with the scanf_s("%d", Results);. You should instead write:
if (scanf_s("%d", &Results[i]) != 1) {
/* not a number, handle the error */
}
The second loop is incorrect: for (i < 7; Results[i] > 0; i++) has multiple issues. Write instead for (i = 0; i < 7; i++)
And smaller ones too:
#include "stdio.h" should be written #include <stdio.h>
#include "stdafx.h" is not used, and so can be removed - regardless, it should be written as #include <stdafx.h> if it were to be used.
The Results array has size 8, but you only use 7 slots.
main should have prototype int main(void) or int main(int argc, char *argv[]) or equivalent.
favor idiomatic for (i = 0; i < 7; i++) loops over error prone do / while loops.
use braces for a non trivial loop body.
Here is a simpler and better version:
#include <stdio.h>
#include <string.h>
int main(void) {
int Results[7];
int i, n, max;
printf("Enter the results of your 7 leavin cert subjects: ");
for (i = 0; i < 7; i++) {
printf("\nSubject %d: ", i + 1);
if (scanf_s("%d", &Results[i]) != 1) {
printf("invalid number\n");
exit(1);
}
}
for (n = i, max = 0, i = 0; i < n; i++) {
if (Results[i] > max)
max = Results[i];
}
printf("The best grade is %d\n", max);
return 0;
}

Recursive function for finding same numbers on same positions between two arrays

Here is an example of what the result should be :
1234 and 1344 Have two numbers on same positions.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Proverka(int *num1[], int *num2[], int len, int pom)
{
if (len < 1 && pom < 1)
return 0;
if (*num1 == *num2)
return 1 + Proverka(num1++, num2++, len-1, pom-1);
else {
return Proverka(num1++, num2++, len-1, pom-1);
}
}
int main (void)
{
int *num1[5], *num2[5], pom, len, i, sin, j;
pom = sizeof(num1) / sizeof(num1[0]);
len = sizeof(num2) / sizeof(num2[0]);
for (i = 0; i < pom; i++) {
printf("Enter elements for first array :");
scanf("%d", num1[i]);
}
for (j = 0; j < len; j++){
printf("Enter elements for second array : ");
scanf("%d", num2[j]);
}
sin = Proverka(num1, num2, pom, len);
{
printf("They have %d numbers on same positions", sin);
}
return 0;
}
You have quite a lot of bugs in the code, here's a working version of it.
Read comments to understand what I changed.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Proverka(int *num1, int *num2, int len1, int len2)
{
if (len1 < 1 && len2 < 1) return 0;
// note the pre-increment. Your post-increment wouldn't have worked. Or just add 1.
return (*num1 == *num2) + Proverka(++num1, ++num2, len1 - 1, len2 - 1);
// this works, since "boolean" is really just 0 or 1
}
int main (void)
{
// I make array of ints, not of pointers to ints.
int num1[5], num2[5], len1, len2, i, same;
len1 = sizeof(num1) / sizeof(num1[0]);
len2 = sizeof(num2) / sizeof(num2[0]);
for (i = 0; i < len1; i++) {
printf("First array element %d:", i+1);
scanf("%d", &num1[i]); // pointer at the element
}
for (i = 0; i < len2; i++){
printf("Second array element %d:", i+1);
scanf("%d", &num2[i]);
}
// get pointers at the first array elements
same = Proverka(&num1[0], &num2[0], len1, len2);
printf("They have %d numbers on same positions\n", same); // newline - good practice
return 0;
}
Here's a bit more "optimized" and cleaned up version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ITEMS 5
int Proverka(const int *aa, const int *bb, const int len)
{
if (len == 0) return 0;
return (*aa == *bb) + Proverka(1 + aa, 1 + bb, len - 1);
}
int main (void)
{
int aa[ITEMS], bb[ITEMS], i, same;
for (i = 0; i < ITEMS; i++) {
printf("First array element %d:", i+1);
scanf("%d", &aa[i]);
}
for (i = 0; i < ITEMS; i++) {
printf("Second array element %d:", i+1);
scanf("%d", &bb[i]);
}
same = Proverka(&aa[0], &bb[0], ITEMS);
printf("They have %d numbers on same positions\n", same);
return 0;
}
Using recursion for this is not a very good choice, a loop would be easier and safer. But this works too - for not-too-large arrays.
int *num1[5],*num2[5] ... doesnt give you an array of integer pointers with memory allocated. Fix that. Allocate memory using malloc.
Or just say int num1[5],num2[5] and scanf("%d",&num1[i]);

C program — coding the figure given n when n is odd?

I have to display the following figure (The two triangles intercept) for a n given by the user, where n is odd. The figure is in this link: http://i.imgur.com/mQxarLz.jpg
*******
*****
***
*
*
***
*****
*******
I already wrote this code, but I don't know how to give the n, where n is odd. And my code doesn't compile; it says: "In the fifth row, syntax error before for".
#include <stdio.h>
int main (void) {
int n,i,k,m;
for(m=0;m<2;m++)
for (i=1;i<=n;i++){
if(m==0){
for(k = 1; k<=n-i; k++){
printf(" ");
}
}
}
for (k=1;k<2*i;k++){
printf("%s","*");
//printf("%d",i);
}
scanf("%d",&n);
for (k = 1; k<=i;k++)
for (k=1;k<(n-i)*2;k++)
for (i=1;i<=n;i++) {
printf("\n$");
}
return 0;
}
First, the answer to "how do I check whether an integer is odd": you simply divide by 2 and check if the remainder is 0 (even) or 1 (odd). In C and most related languages, this is what the modulo operator "%" does:
if ((n % 2) == 1) {
// The number is odd.
}
But you should make sure that you read your n right at the start, because in the code that you have submitted, n is read in your second "for" loop before you have actually written something to it. And that means, n contains garbage at that point.
Good programming is to solve problems in the most simple way you can find. This particular algorithm is really fundamental stuff, thus you shouldn't end up with anything much more complicated than this:
#include <stdio.h>
#include <stdbool.h>
void print_chars (char symbol, int n)
{
for(int i=0; i<n; i++)
{
printf("%c", symbol);
}
}
void print_triangle (int base_size, int height, bool pointing_up)
{
int star_count = pointing_up ? 1 : base_size;
for(int row = 0; row < height; row++)
{
int spaces = base_size - star_count;
print_chars (' ', spaces/2);
print_chars ('*', star_count);
print_chars (' ', spaces/2);
printf("%\n");
star_count += pointing_up ? 2 : -2;
}
}
int main (void)
{
print_triangle(7, 4, false);
print_triangle(7, 4, true);
}
Note that the above code will behave strange if the triangle's base isn't in sync with its height - I left that out intentionally, feel free to improve the program further with such.
#include <stdio.h>
void printAsterisk(int n, int length){
int i, slen = (length - n)/2;
for(i=0;i < slen;++i)
putchar(' ');
for(i=0;i < n;++i)
putchar('*');
putchar('\n');
}
/* non-recursive
void printTriangle(int n, int length){//n isn't required as an argument
int d= -2;
for(; n < length + 1; n += d){
if(n < 0) n += (d *= -1);
printAsterisk(n, length);
}
}
*/
void printTriangle(int n, int length){
if(n < 1) return;
printAsterisk(n, length);
printTriangle(n - 2, length);
printAsterisk(n, length);
}
int main(void){
int n;
do{
printf("input odd number:");
scanf("%d", &n);
}while(n % 2 == 0);
printTriangle(n, n);
return 0;
}

Resources