I'm trying to write a program where the user introduces an array numbers and alphabethic characters. Then the program reads the array, if he sees a number, the program should push that number into one stack. However, if he sees an alphabetical character, the last number pushed is popped.
So far I have this code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 20
int top, i;
void push (double stack[], double x, int top)
{
stack[top] = x;
}
int pop (double stack[])
{
double x;
stack [top]=x;
return x;
}
void display (double stack[],int top)
{
int i;
printf ("\n The stack is: ");
for (i=0; i<=top; i++)
{
printf ("%lf\n",stack[i]);
}
}
void main()
{
int r;
int stack[10];
char array[10];
printf("introduce the numbers");
fgets(array,MAX,stdin);
int l;
r=strlen(array);
top=0;
for (l=0;l<=r;l++)
{
int n;
if (isdigit(array[l]))
{
push(stack,array[l],top);
top=top+1;
}
if (islower(array[l]))
{
pop(stack);
printf("you have popped %d", n);
top=top-1;
}
}
display(stack,top);
}
For some reason the program does not work, if I introduce 22a the output is:
you have popped 4194432
The stack is: 50.00000
50.00000
I am particularly interested in how should I write the pop,push and display to make this program work. How can I do it?
First off, your variable n, the value of which you're printing, is uninitialized and contains whatever garbage that was in the memory at the moment of its creation.
Also, why are you printing it? I think you meant to say n = pop(stack);, right? Otherwise this printing is useless.
Throughout your code you're writing loops the wrong way: for (t=0; t<=threshold; t++). This code will make the loop run threshold + 1 times, but you obviously want only threshold, so do for (t=0; t<threshold; t++) instead.
You're also reading (fgets(array,MAX,stdin);) maximum twenty characters into your array, which can hold only ten characters.
To use strlen on an array, you need it to end with zero (null-terminator). In your code array is not necessarily initialized with zeros, so use memset(array, 0, 10); before using array:
Docs on memset
Tutorial on for loops
void main() is wrong
What to read to learn C
Related
My function isn't working properly. The program runs but when it gets to the for loop the function doesn't work and stops the program even though it is supposed to continue looping. If you could please check my Array function and tell me if there is anything i'm not understanding or doing correctly.
Thanks for your time.
I know for a fact the loop isn't the problem because when I remove the function it works fine. I've also tried placing the 'b' within the function array parameter like this "int Array(int a[b], int b, int c);"
#include <stdio.h>
#include <stdlib.h>
/*Function*/
int Array(int a[], int b, int c);
/*Main Program*/
int main()
{
int S, C, *A, *B;
printf("How Many Numbers Would You Like in Array A and B? ");
scanf("%d\n", & S);
/*For Loop Asking The User to Enter a Value and using the Array function to calculate/store the B[] Value*/
for (C=0; C<=S; ++C){
printf("\nWhat is A[%d] ", C);
scanf("%d", & A[C]);
B[C] = Array(A, S, C);
}
}
/*Function*/
int Array(int a[], int b, int c)
{
if (a[c] < 0){
return a[c] * 10;
} else {
return a[c] * 2;
}
}
Expected Results:
The program asks the user to input the array size which will be used for *A and *B
The program uses a for loop to ask the user to enter a value for each position in array *A, using that value to compute the value for each matching B position
Actual Results:
The program asks the user to input the array size which will be used for *A and *B
The program uses a for loop to ask the user to enter a value for each position in array *A, the program asks the user for one value then stops running.
You're not allocating any memory for the array A. You just declare it as a pointer to int, then start writing values to it, which are going to some random memory location. After the first scanf that gets S, you need to assign A = malloc(S * sizeof(int)) before accessing it.
I've written a function to rotate an array,
I've checked and it works when code is in one block I.E. everything
is coded under main(), but when I divide the code so that the rotation is done under a different function I can't get it to work (it truncates instead of rotating).
I'm pretty sure it's something to do with the array pointer.
sorry complete noob
please help:
#include<stdio.h>
void rotate(int *arr,int length);
int main()
{
// this code creates an array via input
int length;
int i;
int num;
printf("enter length of array\n");
scanf("%d",&length);
int arr[length];
for (i=0;i<length;i++) {
printf("enter number\n");
scanf("%d",&num);
arr[i]=num;
}
// just prints original
for(i=0;i<length;i++){
printf("original arr[%d]=%d\n",i,arr[i]);
}
//runs rotate function
rotate(arr,length);
return 0;
}
//the rotate function inputs rotation amount and uses nested for loop to
execute
void rotate(int *arr,int length)
{
int n;
printf("by how many do you want to rotate array?");
scanf("%d",&n);
int i;
int j;
int temp;
for (j=0;j<n;j++)
{
temp=arr[0];
for (i=0;i<length-1;i++)
{
arr[i]=arr[i+1];
}
arr[length-1]=temp;
printf("rotated arr[%d] = %d\n",i,arr[i]);
}
}
my output looks like this:
enter length of array
5
enter number
1
enter number
2
enter number
3
enter number
4
enter number
5
original arr[0]=1
original arr[1]=2
original arr[2]=3
original arr[3]=4
original arr[4]=5
by how many do you want to rotate array?
3
rotated arr[4] = 1
rotated arr[4] = 2
rotated arr[4] = 3
RUN FINISHED; exit value 0; real time: 9s; user: 0ms; system: 0ms
In C you need to declare the function before "main" function, or do the declaration and definition both above the main function. Also do share your error message, for help.
Also, in C language you can't really create dynamic arrays like that( i.e. taking an integer value and then defining the size of array using it "int array[integer] " is wrong of doing it, if the value of integer is being given during runtime)
Read http://www.mathcs.emory.edu/~cheung/Courses/255/Syllabus/2-C-adv-data/dyn-array.html , or any other tutorial about dynamic arrays in C and how to use malloc and calloc.
According to me the problem is in your last print statement in rotate method which is inside the loop.
you must loop through the whole array again to print the rotated array.
like this.
void rotate(int *arr,int length)
{
int n;
printf("by how many do you want to rotate array?");
scanf("%d",&n);
int i;
int j;
int temp;
for (j=0;j<n;j++)
{
temp=arr[0];
for (i=0;i<length-1;i++)
{
arr[i]=arr[i+1];
}
arr[length-1]=temp;
}
for(i=0;i<length;i++){
printf("original arr[%d]=%d\n",i,arr[i]);
}
}
this will work.
And also, Always define functions at the top in c.
This a dot_product function of 2 vectors of the same length.
I don't understand how to build the array because how the machine will know which input goes to which input (for example i want a={1,2,3} but the input of 123 will come a[0]= 123)...
How do I make end of array[index] input and how do I make end of the whole array.
#include <stdio.h>
#include <stdlib.h>
#define MAXINPUT 100
int dot_product(int v[], int u[], int n)
{
int result = 0;
int i;
for (i=0; i < n; i++)
result += v[i]*u[i];
return result;
}
int main(){
int v1[MAXINPUT];
int v2[MAXINPUT];
int count = 0
int i,print;
printf(" first vector:");
for(i=0;i<MAXINPUT;i++){
scanf("%d", &v1[i]);
count +=1;
}
printf(" second vector:");
for(i=0;i<MAXINPUT;i++)
scanf("%d", &v2[i]);
print = dot_product(v1, v2, count);
printf("v1*v2:%d",print);
return 0;
}
The first problem I observe here is with
count +=1;
where count is an uninitialized automatic local variable, which makes it's initial value indeterminate. Attempt to use that value invokes undefined behavior.
You should be initializing count to 0.
That said, here, you're depending on the user to input the second array with exact same dimension of that of the first one. In case that does not happen, your program will blow up, as you did not initialize the arrays, again.
So i have this type of problem. How to make an array 1*x and then sum up its digits together. I wrote down something like this for now. Any ideas? Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[])
{
int a,i,w,j,m;
int s[a];
printf("How many digits do you want to sum up\n");
scanf("%d",&a);
for(i=0;i<a;i++)
{
printf("Enter numer %d: ",i);
scanf("%d",&s[i]);
}
for(j=0;j<a;j++)
{
m=s[j]+s[j++];
}
printf("\n %d",m);
return 0;
}
The problems of your code are:
int a;
int s[a];
Here a is uninitialized.So,array size is unknown which is incorrect.And,instead of this
m=s[j]+s[j++];
you should do like this :
m += s[j];
One more thing,you have initialize m = 0 before starting to add.
I've Changed your program to this:
#include <stdio.h>
int main(int argc, char *argv[]) {
int a,i,m = 0;
//First get the array size
printf("How many digits do you want to sum up\n");
scanf("%d",&a);
//Then declare the array with the size (a)
int s[a];
for(i = 0; i < a; i++){
printf("Enter numer %d: ",i);
scanf("%d",&s[i]);
m += s[i];
}
printf("\n %d",m);
return 0;
}
Using uninitialized variable is undefined behaviour.
int s[a];
The above statement defines an array s of size a but the value of a is unpredictable since it is uninitialized and contains garbage. The size of the array must be known when it defined and it remains the same throughout its lifetime. You cannot resize your array by changing the value of a here. You can use dynamic memory allocation using malloc.
Further, the following statement again invokes undefined behaviour -
m=s[j]+s[j++];
That's because it violates the the following rule stated in the C99 standard §6.5 ¶2
Between the previous and next sequence point an object shall have its
stored value modified at most once by the evaluation of an expression.
Furthermore, the prior value shall be read only to determine the value
to be stored.
I am learning C at the moment, and am trying to build a simple interpreter. It takes one character and one number. The program below only uses 'r' for the char. The 'r' stands for the range (of the natural numbers) and the digit after it specifies the length of the range.
Example Execution:
Enter:
r 9
0 1 2 3 4 5 6 7 8
What happens instead:
Enter:
r 9
And here the program crashes. So I believe the error lies in the printing of the array.
The code in question is here:
#include <stdio.h>
#include <stdlib.h>
int* range(int i) {
int *a=(int*) malloc(i * sizeof(int));
int j;
for(j=0;j<i;j++)
a[j]=j;
return a;
}
void printArray(int a[], int length) {
int i;
printf("\n");
for(i=0;i<length;i++)
printf("%d ", a[i]);
}
int main() {
char c;
int n = 1;
while(n>=0){
printf("\nEnter:\n\t");
scanf("%c %d", c, n);
if(c='r')
printArray(range(n), n);
}
return 0;
}
So what is causing the program to crash?
Your arguments to scanf are wrong, you need
scanf("%c %d",&c, &n);
Your fundamental problem here is that you have no evidence about where the crash is happening, as it happens I bet it's in scanf().
I recommend you adopt two debugging techniques:
a). Add print statements in your code so you know what's happening
b). Use an interactive debugger so you can step through and see what's going on.