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]);
}
...
Related
I'm doing a program that check if 5 numbers that the user insert are even or odd, then they will be stored into an array and finally these values will be printed out on screen. In order to do this i've divided this program in two functions just to understand how the functions and the arrays works together, but it doesn't print the values that i've putted in. Why?
int check_even_and_odd(int number, int list[]){
printf("Insert the numbers\n");
scanf("%d", &list[number]);
if (number % 2 == 0) {
printf("Even\n");
}
else{
printf("Odd\n");
}
return 0;
}
int main () {
int k;
int i = 0;
int list2[5] = {0};
while (i < 5) {
i++;
k = check_even_and_odd(i, &list2[i]);
}
i = 0;
while (i < 5) {
i++;
printf("\n%d\n", list2[i]);
}
return 0;
}
Edit: Now that the main issue is gone, I want to add a little improvement to this little project. I want that the program tells to me how many Even or Odd number are in the array, but i don't know how to do it. I was thinking about adding 2 counters into the if statement (one for the even number and one for the odd numbers) but once i do this i don't know how to continue.
The program with the counters is this:
void check_even_and_odd(int number, int list[]){
int even = 0;
int odd = 0;
printf("Insert the numbers\n");
scanf("%d", &list[number]);
if (number % 2 == 0) {
even++;
}
else{
odd++;
}
printf("Even numbers are: %d\n", even);
printf("Odd numbers are: %d\n", odd);
}
int main () {
int i = 0;
int list2[5] = {0};
while (i < 5) {
i++;
check_even_and_odd(i, list2);
}
i = 0;
while (i < 5) {
i++;
printf("\n%d\n", list2[i]);
}
return 0;
}
Obviously it isn't complete, but as i have already said, i don't know how to continue
Your function expects an array argument but you are passing the address of individual elements of the array, so it won't work properly, you'll just need to use the correct argument:
k = check_even_and_odd(i, list2);
Quibble: k is never used so you don't really need it. You can just make your function void and remove the variable:
void check_even_and_odd(int number, int list[]){
printf("Insert the numbers\n");
scanf("%d", &list[number]);
if (number % 2 == 0){
printf("Even\n");
}
else{
printf("Odd\n");
}
}
int main(){
int i = 0;
int list2[5] = {0};
while (i < 5){
i++;
check_even_and_odd(i, list2);
}
i = 0;
while (i < 5){
i++;
printf("\n%d\n", list2[i]);
}
return 0;
}
Your fault is in line scanf("%d", &list[number]); just need to change it to scanf("%d", &list); but i think you are miss understanding whole array and pointer logic. You can't pass list as argument and if you do that, The compiler will changed it to pointer automatically. So if you want to tell a function about your list you just have to pass it your list address in memory (pointer). So you should do it like:
#include <stdio.h>
int How_Many_Odd = 0;
int How_Many_Even = 0;
void Add_To_List(int Number, int *ListIndex){
printf(
"Number %d is %s\n",
Number,
(Number % 2 == 0)? "Even": "Odd" // check if is odd or even
);
if(Number % 2 == 0)
How_Many_Even++;
else
How_Many_Odd++;
// changing value of pointer ListIndex to Number
*ListIndex = Number;
}
int main(){
// first creating integer array with size of 5
int List[5];
for(int i=0; i < 5; i++){
// waiting for user to enter number
int value;
scanf("%d", &value);
// changing value of index 0 to 3
Add_To_List(value, &List[i]);
}
// showing how many odds and how many evens
printf("%d numbers are even and %d numbers are odd\n", How_Many_Even, How_Many_Odd);
// you can show every index value too
for(int i=0; i < 5; i++)
printf("value of index %d is %d\n", i, List[i]);
return 0;
}
I recommend you to learn about pointer that will fix your issues
Here is your code fixed:
#include <stdio.h>
void check_even_and_odd(int number, int list[], unsigned int *even_count)
{
printf("Insert the numbers\n");
scanf("%d", &list[number]);
if (number % 2 == 0) {
printf("Even\n");
*even_count += 1;
}
else
{
printf("Odd\n");
}
}
int main()
{
unsigned int even_count;
int i = 0;
int list2[5] = {0};
while (i < 5)
{
check_even_and_odd(i, list2, &even_count);
i++;
}
i = 0;
while (i < 5)
{
printf("\n%d\n", list2[i]);
i++;
}
printf("There are %d even numbers and %d odd ones.\n", even_count, 5 - even_count);
return 0;
}
Basically, your main problem is in passing the list to the function in k = check_even_and_odd(i, &list2[i]);, as you should be passing the entire list, not a specific number in the list.
regarding:
if (number % 2 == 0) {
This is checking the passed in parameter rather than the value entered by the user. Suggest:
...
if( (list[number] % 2) == 0 )
{
printf( "%s\n", "number is even" );
....
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'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);
}
}
}
I am working on a program that will accept user input to fill an array and then quit when the user enters q. Next the array is passed to a function that finds the largest value in the array. My program seems like it would work, but I believe that user input for the array is incorrect and I am not sure how to solve it.
#include <stdio.h>
#define SIZE 30
int maxnum(int userarray[], int maxx);
int main()
{
int i;
int nums[SIZE];
int largest;
printf("Type integer numbers (up to 30), followed by q to quit:\n");
while(scanf("%d", &nums[i]) == 1)
{
for(i = 0; i < SIZE; i++)
{
//blank
}
}
largest = maxnum(nums, SIZE);
printf("The largest number is: %d\n", largest);
return 0;
}
int maxnum(int userarray[], int maxx)
{
int i;
int maxnumber;
maxnumber = userarray[0];
for(i = 1; i < maxx; i++)
{
if(maxnumber < userarray[i])
{
maxnumber = userarray[i];
}
}
return maxnumber;
}
First i is unitialized.
Then your inner for loop is strange (why someone would do that??) and sets i to SIZE in the end, which is not good.
I don't give more details, but the value of i is trash all the time because of those 2 mistakes it should be:
int i = 0;
while((i<SIZE) && (scanf("%d", &nums[i]) == 1))
{
i++;
}
so you read one by one, and protect against array out of bounds by the second condition.
After that you're passing NUMS
largest = maxnum(nums, SIZE);
whereas the array could contain fewer valid values. Just pass
largest = maxnum(nums, i);
Here is another solution for your problem.
In main() function
int n,i=0;
while(scanf("%d",&n) == 1){
nums[i++] = n;
}
n = maxnum(nums, i);
printf("The largest number is: %d\n", n);
Note : Initialize the value of i=0, Then input and update nums[] array
In maxnum() function
for(i = 0; i < maxx; i++) {
if(maxnumber < userarray[i]){
maxnumber = userarray[i];
}
}
Note: Start i=0 and find the max mumber and return the value
I have a function that takes array 1 and copies/manipulates it to array 2. Basically what it does is take the user input in array one, lets say (2, 3, 3) and array 2 is stored as (2, 0, 3, 0, 3). I know this works because it worked without implementing a function but sadly I have to have one. I cannot for the life of me figure out how to call the function, I believe I don't need a return since its a void and not returning a value. Below is my code any help would be appreciated.
#include <stdio.h>
void insert0(int n, int a1[], int a2[]);
int main() {
int i = 0;
int n = 0;
int a1[n];
int a2[2*n];
printf("Enter the length of the array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i = 0; i < n; i++){ //adds values to first array
scanf("%d",&a1[i]);
}
insert0(); //call function which is wrong and I cannot get anything to work
for( i = 0; i < n*2; i++){ //prints array 2
printf("%d", a2[i]);
}
void insert0 (int n, int a1[], int a2[]){ //inserts 0's between each number
for(i = 0; i < n; i++){
a2[i+i] = a1[i];
a2[i+i+1] = 0;
}
}
}
Modifying n after declaraing a1 and a2 won't magically increase their size. Declare a1 and a2 after reading the size into n to use variable-length arrays.
You must pass proper arguments to call insert0.
Defining functions inside functions is GCC extension and you shouldn't do that unless it is required.
a2 should have n*2 - 1 elements, not n*2 elements.
After moving it out of main(), i is not declared in insert0, so you have to declare it.
You should check if readings are successful.
Corrected code:
#include <stdio.h>
void insert0(int n, int a1[], int a2[]);
int main() {
int i = 0;
int n = 0;
printf("Enter the length of the array: ");
if(scanf("%d", &n) != 1){
puts("read error for n");
return 1;
}
if(n <= 0){
puts("invalid input");
return 1;
}
int a1[n];
int a2[2*n-1];
printf("Enter the elements of the array: ");
for(i = 0; i < n; i++){ //adds values to first array
if(scanf("%d", &a1[i]) != 1){
printf("read error for a1[%d]\n", i);
return 1;
}
}
insert0(n, a1, a2);
for( i = 0; i < n*2-1; i++){ //prints array 2
printf("%d", a2[i]);
}
}
void insert0 (int n, int a1[], int a2[]){ //inserts 0's between each number
int i;
for(i = 0; i < n; i++){
a2[i+i] = a1[i];
if (i+1 < n){ // don't put 0 after the last element
a2[i+i+1] = 0;
}
}
}