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);
}
}
}
Related
I'm a beginner at C programming. I'm making a program that will input numbers and delete the last input even number from the array using stack or the push-pop method.
The problem is I can't pop the last even number and I don't know what is wrong.
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int top = -1;
int stack[MAX];
void deleteEven(int num[], int i);
int main() {
int num[100];
int i, size;
printf("\n-----------------\n\n");
printf("Enter size of array: ");
scanf("%d", &size);
for (i = 0; i < size; i++) {
printf("Enter number: ");
scanf("%d", &num[i]);
top++;
stack[top] = num[i];
}
printf("\nList: ");
for (i = 0; i < size; i++) {
printf("%d, ", num[i]);
}
printf("\n");
printf("Even: ");
for (i = 0; i < size; i++) {
if (num[i] % 2 == 0) {
printf("%d, ", num[i]);
}
}
deleteEven(num, i);
return 0;
}
void deleteEven(int num[], int i) {
printf("\nAnswer: ");
if (num[i] % 2 == 0) {
stack[top--];
}
for (int j = top; j >= 0; --j) {
printf("%d, ", stack[j]);
}
}
I have implement the working one in C with implementing on your code, you can see below. I added int checkEven(int stack[], int stackSize) function which control the array if there is any even number or not. If not, so end the problem with returning 0 or whatever your error code is, other side if there is even number it returns the index of it and deleteEven function swipe the array (stack). It working for size of 5 array but you can fix it. I use 5 for easy testing.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 5
int top = -1;
int stack[MAX];
void deleteEven(int num[], int indexOfEven);
int checkEven(int stack[], int stackSize);
int main() {
int num[5];
int i, size;
printf("\n-----------------\n\n");
printf("Enter size of array: ");
scanf("%d", &size);
for (i = 0; i < size; i++) {
printf("Enter number: ");
scanf("%d", &num[i]);
top++;
stack[top] = num[i];
}
printf("\nList: ");
for (i = 0; i < size; i++) {
printf("%d, ", num[i]);
}
printf("\n===stack===");
for( i = 0; i <size; i++){
printf("%d ", stack[i]);
}
int indexOfEven = checkEven(stack,5);
if(indexOfEven >= 0){
printf("This sequence has even number");
printf("the index => %d ",indexOfEven);
deleteEven(stack, indexOfEven);
}else{
printf("this sequence has no even number");
/*
no even number
exit
*/
return 0;
}
return 0;
}
int checkEven(int stack[], int stackSize){
for(int i = stackSize - 1; i >= 0; i--){
if(stack[i] % 2 == 0){
return i;
}
}
return -1;
}
void deleteEven(int num[], int indexOfEven) {
int simpleArray[5];
for(int t = 0; t < 5; t++){
simpleArray[t] = num[t];
}
int c;
for (c = indexOfEven; c < 4; c++)
simpleArray[c] = num[c+1];
for (c = 0; c < 4; c++){
printf("\n%d\n", simpleArray[c]);
}
}
So far you see the O(n) implementation of it with array but you describe that you want to implement it with push() - pop() - peek() stack mechanism. I want to write sudo code for fully Stack implementation.
let it inputs be 1 - 2 - 3 - 5 - 7
describe inputSize
describe mainStack
describe helperStack
read inputs to mainStack
show stacks
mainStack -> [1-2-3-5-7]
helperStack -> []
while mainStack.peek() != NULL :
if mainStack.peek() % 2 == 0: // even number
mainStack.pop()
break the loop
else:
describe popValue = mainStack.pop()
helperStack.push( popValue )
if inputSize == helperStack:
// no even number
// so nothing break the loop, every value is odd so, all there is another stack
// finish program with error code or return main array / inputs
show stacks
mainStack -> [ 1 ]
helperStack -> [ 3 5 7 ]
now pop() the all helperStack and push it to mainStack
while helperStack.peek() != NULL:
mainStack.push( helperStack.pop() )
show stacks
mainStack -> [ 1 3 5 7 ]
helperStack -> [ ]
Return mainStack as array format.
It seems that the last loop before the call to deleteEven will increment i until the end of the stack array regardless the last number is even or not, because all you do is checking if the current number is even and then printing it, and right after that going to the next one. that will iterate through all the numbers which will result in calling deleteEven with the last index of the array.
how about going from the last element of the array to index 0 (backwards) and printing the first encounter with even number?
Also, not really sure why you're using two different arrays and copying elements one by one after using scanf.
can you help me with code which returns partial sum of 'X' numbers in array in c?
Complete :
int arr_sum( int arr[], int n )//Recursive sum of array
{
if (n < 0) //base case:
{
return arr[0];
}
else
{
return arr[n] + arr_sum(arr, n-1);
}
}
void sum_till_last (int *ar,int si )
{
**int sum,i;// the problem some where here
ar=(int*) malloc(si*sizeof(int));
for (i=0; i<si;i++)
{
sum=arr_sum(ar,i);
ar [i]=sum;
}
free (ar);**
}
void main ()
{
int i;
int a [5];
for (i = 0; i < 5; i++)
scanf_s("%d", &a[i]);
sum_till_last(a,5);
printf("%d\n",a[5]);
}
\i want to create new array with this this legality:
My input :
4
13
23
21
11
The output should be (without brackets or commas):
4
17
40
61
72
Now when we can see the full code, it's quite obvious that the problem is in the sum_till_last function where you overwrite the pointer you pass to the function with some new and uninitialized memory you allocate.
Drop the allocation (and the call to free of course). And fix the logical bug in arr_sum that causes you to get arr[0] + arr[0] when i is zero.
Here you go:
#include <stdio.h>
int main () {
int in_arr[5] = {4,13,23,21,11};
int out_arr[5];
int p_sum =0;
int i;
for ( i=0;i<5;i++){
out_arr[i] = in_arr[i]+p_sum;
p_sum=p_sum+in_arr[i];
}
for (i=0;i<5;i++){
printf("%d", out_arr[i] );
}
}
Fix according to your policy
#include <stdio.h>
#include <stdlib.h>
int arr_sum(int arr[], int n){
if (n == 0){//Change to this
return arr[0];
} else {
return arr[n] + arr_sum(arr, n-1);
}
}
void sum_till_last(int *ar, int si){
int sum,i;
int *temp = malloc(si * sizeof(int));//variable name ar is shadowing parameter name ar.
for(i = 0; i < si; i++){
temp[i] = arr_sum(ar, i);
if(i)
putchar(' ');
printf("%d", temp[i]);//need print out :D
}
free(temp);
}
int main(void){
int i, a[5];
for (i = 0; i < 5; i++)
scanf_s("%d", &a[i]);
sum_till_last(a, 5);
//printf("%d\n",a[5]);<-- this print only one element. and It's out of bounds element XD
}
I just made it simple so it´s easy to understand :)
I´m assuming "n" is always equal or less then array element number. Then you just print the SUM.
#include <stdio.h>
int arr_sum( int arr[], int n ){
int i=0,SUM=0;
for(; i < n;i++){
SUM= SUM+ arr[i];
printf("%d ",SUM);
}
}
int main(void) {
int array[] = {4, 13, 23, 21, 11};
arr_sum(array,5);
return 0;
}
Summary:
I want to be able to write a function that can let me store 10 values. I should be able to exit the loop with 0 without storing 0 to the array. I should be able to re-enter the array and keep storing until i get 10 values.
Questions:
I started to write something simple but when I store like 5 values it will print out the 5 values and then some random numbers. Why is that?
And how can I exit the loop without the array storing the 0?
I'm quite new to this stuff so I hope I've followed the rules correctly here.
Code:
#include <stdio.h>
int main(void)
{
int arrayTable[9] = {0};
int i;
for (i=0; i<10; i++)
{
printf("Enter Measurement #%i (or 0): ", i+1);
scanf("%d", &arrayTable[i]);
if (arrayTable[i] == 0)
{
break;
}
}
for (int i=0; i<10; i++)
{
printf("%d\n", arrayTable[i]);
}
return 0;
}
#include <stdio.h>
#define ArraySize 10
int main(void){
unsigned v, arrayTable[ArraySize] = {0};
int n = 0;//number of elements
while(n < ArraySize){
printf("Enter Measurement #%i (or 0): ", n + 1);
if(1 != scanf("%u", &v) || v == 0){//use other variable
break;
}
arrayTable[n++] = v;
}
for (int i = 0; i < n; ++i) {
printf("%u\n", arrayTable[i]);
}
return 0;
}
as long as you want discard 0 from array then use a temporary variable, input it, check whether it is a non-zero and if so store it to the element of array, if it is a zero exit the loop:
#include <stdio.h>
int main(void)
{
int arrayTable[10] = {0};
int iValue = 0;
int i = 0;
while(i < 10)
{
printf("Enter Measurement #%i (or 0): ", i+1);
scanf("%d", &iValue); // input iValue
if (!iValue) // if iValue is zero then exit loop without affecting array with this value
break;
else
{
arrayTable[i] = iValue; // if the value is non-zero store it in array and continue
i++;
}
}
for (int i = 0; i < 10; i++)
{
printf("%d\n", arrayTable[i]);
}
return 0;
}
You probbaly want this:
...
int arrayTable[10] = {0}; // <<< [10] instead of [9]
...
for (i=0; i<10; i++)
{
if (arrayTable[i] == 0) // <<< add this
break; // <<<
printf("%d\n", arrayTable[i]);
}
...
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]);
Following is just one section on one code.
t is test case number and then i have integer n for each t.
i want to break integer to digits and store in array and then print each element of array.
input
1
45
expected output
5
4
actual output
32767
0
code
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int t,n,n1,tmp,in,len,j;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int arr[]={};
n1=n;
in=0;
len=0;
while(n1>0)
{
tmp=n1%10;
arr[in]=tmp;
len++;
n1=n1/10;
in++;
}
for(j=0;j<len;j++)
{
printf("%d\n",arr[j]);
}
}
}
The problem is with your definition of int arr[]={}; which creates an empty array without space for storage. You are better off always defining a maximum array size, unless dynamically allocating. Fixing that issue (along with initializing all values) takes care of the issue.
The following is just one approach to correcting the issue. It defines a maximum number of array elements MAXVALUES of 128. It also adds prompts to orient the user to the data requested, and prevents the trailing newline from your first use of scanf from being read as the input for 'n':
#include <stdio.h>
#include <stdlib.h>
#define MAXVALUES 128
int main () {
int t = 0;
int n = 0;
int n1 = 0;
int tmp = 0;
int in = 0;
int len = 0;
int j = 0;
printf ("\n Enter the number of numbers to convert: ");
scanf ("%d%*c", &t);
while (t--) {
printf ("\n Enter the number 'n' : ");
scanf ("%d%*c", &n);
int arr[MAXVALUES] = {0};
in = 0;
len = 0;
n1 = n;
while (n1 > 0) {
tmp = n1 % 10;
arr[in] = tmp;
len++;
n1 = n1 / 10;
in++;
}
for (j = 0; j < len; j++) {
printf ("%d\n", arr[j]);
}
}
return 0;
}
output:
$ ./bin/arrayval
Enter the number of numbers to convert: 2
Enter the number 'n' : 12345
5
4
3
2
1
Enter the number 'n' : 56789
9
8
7
6
5
Dynamically Allocate arr based on digits in n
You can dynamically allocate arr to prevent having #define allocate more space than needed (this is kinda like using a sledge-hammer to swat a fly here). It just takes a little more work. Specifically, it takes knowing how many digits are in n before you allocate arr so you can allocate no more memory than needed. Here, the number of digits in n is calculated by the function szitoa and then arr is allocated. This is one approach to that type solution:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
/* determine number of chars required for string of int i,
does NOT include space for null char (like strlen) */
size_t
szitoa (int val)
{
int it = 0;
int sz = (val > 0) ? 0 : 1; /* provide space of '-' */
val = (val > 0) ? val : -val; /* absolute value */
for (it = 1; it < INT_MAX; it*=10) {
sz++;
if (val >= it && val < (it*10))
break;
}
return sz;
}
int main () {
int t = 0;
int n = 0;
int n1 = 0;
int tmp = 0;
int in = 0;
int len = 0;
int j = 0;
printf ("\n Enter the number of numbers to covert: ");
scanf ("%d%*c", &t);
while (t--) {
printf ("\n Enter the number 'n' : ");
scanf ("%d%*c", &n);
/* dynamically allocate arr and validate */
int *arr = calloc (szitoa (n), sizeof (int));
if (!arr) {
fprintf (stderr, "error: arr allocation failed\n");
exit (EXIT_FAILURE);
}
in = 0;
len = 0;
n1 = n;
while (n1 > 0) {
tmp = n1 % 10;
arr[in] = tmp;
len++;
n1 = n1 / 10;
in++;
}
for (j = 0; j < len; j++) {
printf ("%d\n", arr[j]);
}
if (arr) free (arr); /* free memory allocated to arr */
}
return 0;
}
This should work for you:
#include <stdio.h>
int main() {
int number, numberCount, tmp, count;
printf("Please enter a number:\n>");
scanf("%d", &number);
tmp = number;
for(numberCount = 0; tmp > 0; numberCount++)
tmp /= 10;
int numbers[numberCount];
for(count = (numberCount-1); number > 0; count--) {
numbers[count] = number % 10;
number /= 10;
}
for(count = 0; count < numberCount; count++)
printf("%d digit is: %d\n", count+1, numbers[count]);
return 0;
}
Input:
45
Output:
1 digit is: 4
2 digit is: 5
You are trying to write more integers to your array than you have allocated space for. This code here:
while(n1>0)
{
tmp=n1%10;
arr[in]=tmp; // You initialize the array space to in, which is ambiguous.
len++;
n1=n1/10;
in++; // You increment the array after already initializing space which you can't do in this manner.
}
If you wish to accomplish in expanding your array based on the number of inputs from the user which is also ambiguous - you might think about using dynamic memory.