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.
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.
My code is below, this is my first programming course so expect a possibly stupid mistake.
Basically I am trying to get the min/max and the position number of them. However, my max works correctly up until 6 numbers are generated and I can't seem to understand why.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n, r, x, i;
int max, min;
int num[0];
printf("Enter an integer");
scanf("%d", &n);
x = n;
printf("\n Pos | Val");
for(n=0; n<x; n++)
{
r = ( rand()%1000 ) + 1;
printf("\n %3d | %3d", n+1, r);
}
max=num[0];
i=0;
while(i<x) // while loop determing the biggest number
{
if(num[i]>max)
{
max=num[i];
}
i++;
}
printf("\nMax : %d",max); // biggest number
return 0;
}
There are actually several places that needs improvement in your code.
Firstly, it is invalid to declare an array of size 0 in your code int num[0];, so I'm not sure why your code work with a n up to 6.
Secondly, as you may learn very soon, indentation is very important while programming so that the code is better to understand and maintain in the future. Furthermore, while C is not a language that requires indentation (and that is considered one of its strengths) many common languages such as Python that rely on whitespace to differentiate functions do need careful management of indentation.
Third, RAND_MAX is not a multiple of 1000 so you would not obtain equal probability in your program. A srand function call is also recommended.
A possible implementation of your intended program (still ugly):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXN 1000
int main(void) {
int n, r, i;
int pos = 0;
int max;
int num[MAXN];
printf("Enter an integer");
scanf("%d", &n);
srand(time(0));
printf("\n Pos | Val");
for (i = 0; i<n; i++)
{
r = (int)(((double)rand() / (RAND_MAX + 1)) * 1000) + 1;
printf("\n %3d | %3d", i + 1, r);
num[i] = r;
}
max = num[0];
i = 0;
for (i = 1; i < n; i++)
{
if (num[i] > max)
{
max = num[i];
pos = i;
}
}
printf("\nMax : %d | Pos : %d", max, pos); // biggest number
//while (1);
return 0;
}
As far as my tests, this piece works well
As already identified by numerous answers and comments, your primary problem is your array. Standard C doesn't allow array sizes of zero. GCC does unless you tell it to complain.
However, all the other answers continue to blithely use the array. For the problem stated, there's no need for an array at all. Also, the question text mentions 'minimum' as well as 'maximum', and 'position' as well as 'value' — though the code shown reports neither minimum nor position. Clearly, if this is just a preliminary phase before using the data for some other work, then you probably do need to save the data in an array. You can then decide whether to use a C99 (or later) VLA — variable length array — or whether to use dynamic memory allocation with malloc() et al, remembering to free the allocated space with free().
Here's a simple revised program that doesn't use an array and does manage minimum and maximum as well as reporting positions. It deliberately changes the range of values to 0..999 so that there are never 4-digit numbers to throw the presentation off. You can decide what to do if you absolutely must used 1-based counting and values in the range 1..1000. (Using + 1 in selected locations is one part of the answer; deciding to replace %3d with either %d or %4d is probably the rest of the answer).
This code uses the time as a seed value for the random numbers, and it reports that seed value. If the program was going to be used seriously, I'd make it accept optional arguments, one of which would be the seed, so that previous runs can be recreated. I'd probably make it accept an argument for the number of random values to be generated too.
The code validates that a number was entered and validates that the number falls in the range 1..999, bailing out with an error message written to standard error if the value is not acceptable. Note that the error message diagnoses what is valid — there is nothing more frustrating than to be told that something is invalid but not why and what you need to do to fix it (and often, it helps to show what the program read — it might not be what the user thought the program would read).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int n;
printf("Enter number of random values to test: ");
if (scanf("%d", &n) != 1 || n <= 0 || n >= 1000)
{
fprintf(stderr, "Didn't read a valid number in the range 1..999\n");
return 1;
}
unsigned seed = time(0);
srand(seed);
printf("Seed: %u\n", seed);
int minval = 0;
int maxval = 0;
int minidx = 0;
int maxidx = 0;
printf("\n Pos | Val\n");
for (int i = 0; i < n; i++)
{
int r = (rand() % 1000);
printf(" %3d | %3d\n", i, r);
if (i == 0)
{
minval = r;
maxval = r;
minidx = i;
maxidx = i;
}
else if (r > maxval)
{
maxval = r;
maxidx = i;
}
else if (r < minval)
{
minval = r;
minidx = i;
}
}
printf("Minimum value was %3d at index %3d\n", minval, minidx);
printf("Maximum value was %3d at index %3d\n", maxval, maxidx);
return 0;
}
Example run (program mnmx67 compiled from mnmx67.c):
$ mnmx67
Enter number of random values to test: 10
Seed: 1503763592
Pos | Val
0 | 201
1 | 216
2 | 85
3 | 793
4 | 382
5 | 780
6 | 341
7 | 661
8 | 75
9 | 266
Minimum value was 75 at index 8
Maximum value was 793 at index 3
$
You did not store your random numbers in num, also You need to have some space to store these numbers. Try this for size, i commented my changes
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n, r, x, i;
int max, min;
int * num; // ++++++++ pointer to array
printf("Enter an integer");
scanf("%d", &n);
x = n;
num = malloc(x * sizeof(int)); // ++++++++++ allocate memory
printf("\n Pos | Val");
for(n=0; n<x; n++)
{
r = ( rand()%1000 ) + 1;
printf("\n %3d | %3d", n+1, r);
num[n] = r; // +++++++++ store your number
}
max=num[0];
i=0;
while(i<x) // while loop determing the biggest number
{
if(num[i]>max)
{
max=num[i];
}
i++;
}
printf("\nMax : %d",max); // biggest number
free(num); // +++++++++ free memory
return 0;
}
Your first mistake is that the array's dimension is zero. You need to set a size for the array.
I would do this by splitting the code into three additional functions: one to generate the numbers, and two others to find the min and max.
int *gennums(size_t n)
{
int *nums;
size_t i;
if ((nums = malloc(n * sizeof (int))) != NULL) {
for (i = 0; i < n; ++i)
nums[i] = rand() % 1000;
return nums; // caller must free
}
return NULL;
}
int min(const int *arr, size_t n)
{
assert(n > 0);
int m = arr[0];
size_t i;
for (i = 0; i < n; ++i)
if (arr[i] < m)
m = arr[i];
return m;
}
int max(const int *arr, size_t n)
{
assert(n > 0);
int m = arr[0];
size_t i;
for (i = 0; i < n; ++i)
if (arr[i] > m)
m = arr[i];
return m;
}
Here int num[0];
You are not storing your random numbers in this array.Searching in that is meaning less.
Also size of your array should be at-least equal to n
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);
}
}
}
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]);
}
...
So I was asked to write a program that tests whether a sequence of integers input by the user is a palindrome or not (reads same backwards as forwards). I can't figure out how to dynamically allocate memory so that the input can be of variable length. In the code you can see that the user enters the number of elements in their sequence, n. But during compilation, when n integers have been entered nothing happens. What is wrong with the code? Please explain in detail as much as possible, and if you know of any good references share them!! I'm struggling with pointers and arrays.
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i, n, x;
int* intarray;
printf("\nHow many integers are there?: \n");
scanf("d", &n);
intarray = (int*)malloc(n * sizeof(int));
printf("\nPlease enter the values:\n");
for (i = 0; i < n; i++)
{
scanf("%d", &intarray[i]);
}
n = n - 1;
x = n / 2;
for (i = 0; i <= x; i++)
{
if (intarray[i] != intarray[n - i])
{
printf("\nThis is not a palindrome\n");
return;
}
if (i = x)
{
printf("\nThis is a palindrome\n");
}
}
return;
}
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i, n, x;
int* intarray;
printf("\nHow many integers are there?: \n");
scanf("%d", &n); // and as mentioned by all above type specifier % is missing in %d (for integer type)
intarray = (int*)malloc(n * sizeof(int));
printf("\nPlease enter the values:\n");
for (i = 0; i < n; i++)
{
scanf("%d", &intarray[i]);
}
n = n - 1;
x = n / 2;
for (i = 0; i <= x; i++)
{
if (intarray[i] != intarray[n - i])
{
printf("\nThis is not a palindrome\n");
return;
}
if (i = x)
{
printf("\nThis is a palindrome\n");
}
}
return 0; // as your main()'s return type is int, you should should return an integer value
}
The problem is with the scanf("d", &n); statement that actually does not read anything into n as in order to read an integer you should use "%d" instead of "d".
2 changes:
1.
scanf("%d", &n);
%d is the format specifier for scanning integers.
2.
intarray = malloc(n * sizeof(int));
No need to cast malloc()