Do we have to create an even and an odd array? - arrays

How can we modify the following code (which initially asks the user for 10 numbers to be entered, get stored in an array, and printed on the screen) so that the even numbers are printed on the first line, and the odd on the second:
#include <stdlib.h>
#include <stdio.h>
int i,j;
int array_1[10];
int main() {
for(i=0;i<10;i++) {
printf("Enter a number: ");
scanf("%d", &array_1[i]);
}
printf("The elements of the array are: ");
for (j=0;j<10;j++) {
printf("%d ", array_1[j]);
}
printf("\n");
return 0;
}

O(n) Solution:
you have to add odd numbers at the back of the array and add the even numbers at the front of the array and keep track of the indexes.
int array_1[10];
int main() {
int even = 0, odd = 10;
for (int i = 0; i < 10; i++) {
printf("Enter a number: ");
int inp;
scanf("%d", &inp);
if (inp % 2 == 0) {
array_1[even++] = inp;
} else {
array_1[--odd] = inp;
}
}
// even numbers
for (int i = 0; i < even; i++) {
printf("%i ", array_1[i]);
}
printf("\n");
// odd numbers
for (int i = 9; i >= odd; i--) {
printf("%i ", array_1[i]);
}
printf("\n");
return 0;
}

Since you asked, here is how I would do it. I suspect this may leave you with more questions than answers through.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#define NUMBERS_SIZE 10
typedef bool (*number_validator)(int num);
bool isEven(int num)
{
return (num & 1) == 0;
}
bool isOdd(int num)
{
return (num & 1) != 0;
}
void print(const char *title, int *array, int array_size, number_validator isValid)
{
printf("%s", title);
bool first = true;
for (int i = 0; i < array_size; ++i)
{
if (isValid(array[i]))
{
if (!first)
{
printf(", ");
}
printf("%d", array[i]);
first = false;
}
}
printf("\n");
}
int main()
{
int numbers[NUMBERS_SIZE] = { 0 };
for (int i = 0; i < NUMBERS_SIZE; i++)
{
printf("Enter a number: ");
scanf("%d", &numbers[i]);
}
printf("\n");
print("Even: ", numbers, NUMBERS_SIZE, isEven);
print(" Odd: ", numbers, NUMBERS_SIZE, isOdd);
return 0;
}
Demo on ideone

you can try this way.I have used binary AND(&) instead of MOD(%) as it is faster:
#include <stdlib.h>
#include <stdio.h>
int i,j;
int array_1[10];
int main()
{
for(i=0; i<10; i++)
{
printf("Enter a number: ");
scanf("%d", &array_1[i]);
}
printf("The Even elements of the array are: ");
for (j=0; j<10; j++)
{
if((array_1[j]&1) == 0)
printf("%d ", array_1[j]);
}
printf("\nThe Odd elements of the array are: ");
for (j=0; j<10; j++)
{
if((array_1[j]&1) != 0)
printf("%d ", array_1[j]);
}
printf("\n");
return 0;
}

No need to create a new array. You can just go through it first checking for even numbers, and then again for odd numbers. Also, there's no need to declare i and j before using them. You can just declare them and initialize them in the for loop:
#include <stdlib.h>
#include <stdio.h>
int array_1[10];
int main() {
for(int i=0;i<10;i++) {
printf("Enter a number: ");
scanf("%d", &array_1[i]);
}
printf("The elements of the array are: ");
// Print even numbers
for (int j=0;j<10;j++) {
if(array_1[j] % 2 == 0)
printf("%d ", array_1[j]);
}
printf("\n");
// Print odd numbers
for (int j=0;j<10;j++) {
if(array_1[j] % 2 != 0)
printf("%d ", array_1[j]);
}
printf("\n");
return 0;
}
Edit: As tadman suggested in the comment below, there's a better and cleaner way to do this kind of task. As you can see in the above example, I'm repeating 4 lines of code where only one character changes. This task could be abstracted into a function to reduce code repetition:
void printIfMod(int* arr, size_t array_size, int mod){
for (int j=0;j<array_size;j++) {
if(arr[j] % 2 != mod)
continue;
printf("%d ", arr[j]);
}
printf("\n");
Remember to add a function prototype before main if you place the function after main:
void printIfMod(int* arr, size_t array_size, int mod);
int main(){...}
Now, to print the numbers, call the method with modulo 0 to get even numbers, and 1 to get odd numbers:
// Print even numbers
void printIfMod(&array_1, 10, 0);
// Print odd numbers
void printIfMod(&array_1, 10, 1);
One last note, hard-coding array_size is not wise, and that goes for all arrays. I recommend using sizeof() to dynamically calculate the size of your array:
size_t size = sizeof(array_1) / sizeof(int);
// Print even numbers
void printIfMod(&array_1, size, 0);
// Print odd numbers
void printIfMod(&array_1, size, 1);

Related

How to put commas on a series of numbers in a proper way

Yes I have searched through the net and also here but failed to find similar cases. I have here a program which prints prime numbers between 2 given integers. But I have to print them with commas in a proper way. like 1, 2, 3, 4 without having a comma on the last integer. Here is my code.
#include<stdio.h>
void main()
{
int x, y, i, j;
puts("Enter first number: ");
scanf("%d", &x);
puts("Enter second number: ");
scanf("%d", &y);
for(i=x; i<=y; i++)
{
for(j=2; j<=i; j++)
{if(i%j==0)
{
break;
}
}
if(i==j)
{
printf("%d, ", i);
}
}
}
I wanted to identify the total number of prime numbers printed in order to set a condition that if it is the last one, a comma will not print but I don't know if it will work. That is the only thing I can think of for now and your help guys will be really appreciated. Thank you!
As #kaylum pointed out, use a flag to "skip" printing the comma when printing the first number. Set that flag to false after the very first number you print.
#include <stdio.h>
void main() {
int x, y, i, j;
puts("Enter first number: ");
scanf("%d", &x);
puts("Enter second number: ");
scanf("%d", &y);
int is_first_time = 1;
for (i = x; i <= y; i++) {
for (j = 2; j <= i; j++) {
if (i % j == 0) {
break;
}
}
if (i == j) {
if (is_first_time) {
printf("%d", i);
is_first_time = 0;
}
else {
printf(", %d", i);
}
}
}
}
You can use a flag, as others have suggested, but you can also use a string as a separator, setting it to empty for the first element and any desired separator after that.
#include <stdio.h>
void print_join(const char *sep, int n, int a[n])
{
const char *s = "";
for (int i = 0; i < n; i++)
{
printf("%s%d", s, i);
s = sep;
}
printf("\n");
}
int main(void)
{
int a[] = {1, 2, 3, 4, 5};
int n = sizeof a / sizeof *a;
print_join(", ", n, a);
print_join(";", n, a);
print_join("", n, a);
print_join("--", n, a);
return 0;
}

Functions and arrays which allows you to print what's the most repeated number

I have a problem with my code, it doesn't print the result I expect. This code allows the user to enter as many numbers as he wishes and then print the most repeated one
Here it is:
#include <stdio.h>
void reading_numbers(int array[]){
int i = 0;
int Max = 0;
printf("How much long the array will be?\n");
scanf("%d", &Max);
while (i < Max) {
printf("Insert the numbers\n");
scanf("%d", &array[i]);
i++;
}
}
void most_present_number(int array[], int Max){
int i = 0;
reading_numbers(array);
int current_number = array[i];
int current_number_count = 0;
int most_present_one = 0;
int most_present_one_counter = 0;
while (i < Max) {
if (array[i] == current_number) {
current_number_count++;
i++;
} else {
if (current_number_count > most_present_one_counter){
most_present_one = current_number;
most_present_one_counter = current_number_count;
}
current_number_count = 1;
}
}
printf("This is the most present number %d it is repeated %d times\n", most_present_one,
most_present_one_counter);
}
int main() {
int Max = 0;
int array[Max];
most_present_number(array, Max);
return 0;
}
The problem for me is when I call the function, but I don't know how to fix it
I should have written as a premise but I'm a bit new to C so probably there are some things in this code that don't make sense
I make a procedure to find the result ,int main() must have the size of array (mistake logic),because the procedure take the parameters of the main function (int main ())
Here is my code:
#include<stdio.h>
void most_present_number(int Max,int T[Max])
{
int i = 0;
while (i < Max)
{
printf("Insert the numbers :");
scanf("%d", &T[i]);
i++;
}
int k=0,cpt1=0,cpt=0;
for(int i=0;i<Max;i++)
{
cpt=0;
for(int j=i+1;j<Max;j++)
{
if(T[i]==T[j])
{
cpt++;
}
}
if(cpt>=cpt1)
{
cpt1=cpt;
k=T[i];
}
}
printf("This is the most present number %d it is repeated %d times\n",k,cpt1+1);
}
int main()
{
int Max = 0;
do
{
printf("How much long the array will be?\n");
scanf("%d", &Max);
}while(Max<1);
int T[Max];
most_present_number(Max,T);
}
the following proposed code:
cleanly compiles
performs the desired functionality
only includes header files those contents are actually used
and now the proposed code:
#include <stdio.h>
void reading_numbers( int Max, int array[ Max ][2])
{
for( int i = 0; i < Max; i++ )
{
printf("Insert the numbers\n");
scanf("%d", &array[i][0]);
array[i][1] = 0;
}
}
void most_present_number( int Max, int array[ Max ][2] )
{
for( int i=0; i < Max; i++ )
{
for( int j=i; j<Max; j++ )
{
if ( array[i][0] == array[j][0] )
{
array[i][1]++;
}
}
}
int most_present_one = array[0][0];
int most_present_one_counter = array[0][1];
for( int i=1; i<Max; i++ )
{
if( most_present_one_counter < array[i][1] )
{
most_present_one = array[i][0];
most_present_one_counter = array[i][1];
}
}
printf("This is the most present number %d it is repeated %d times\n",
most_present_one,
most_present_one_counter);
}
int main( void )
{
int Max = 0;
printf("How much long the array will be?\n");
scanf("%d", &Max);
int array[Max][2]; // uses variable length array feature of C
reading_numbers( Max, array );
most_present_number( Max, array );
return 0;
}
a typical run of the code:
How much long the array will be?
4
Insert the numbers
1
Insert the numbers
2
Insert the numbers
3
Insert the numbers
2
This is the most present number 2 it is repeated 2 times

A little problem with functions and arrays

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" );
....

Delete last input even number from array using stack

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.

How to print array returned from function

This code is supposed to recieve to arrays and then call function to return them in 1 array but I don't know how to print the last array returned from the function thanks in advance ???
and now I write anything because it says that the post is mostly code :D :D
#include <stdio.h>
#include <stdlib.h>
int join_arrays(int *array1, int *array2, int arr1_size, int arr2_size);
int main() {
int size_arr1, size_arr2, i, num1 = 1, s;
printf("Please enter the size of the first array: ");
scanf("%d", &size_arr1);
int arr1[size_arr1];
printf("start fill your first array: \n");
for (i = 0; i < size_arr1; i++) {
printf("enter element number %d: ",num1);
scanf("%d", &arr1[i]);
num1++;
}
num1 = 1;
printf("Please enter the size of the second array: ");
scanf("%d", &size_arr2);
int arr2[size_arr2];
int *ptr1_last;
printf("start fill your second array: \n");
for (i = 0; i < size_arr2; i++) {
printf("enter element number %d: ", num1);
scanf("%d", &arr2[i]);
num1++;
}
ptr1_last = join_arrays(arr1, arr2, size_arr1, size_arr2);
printf("sorted array= \n");
for (s = 0; s < (size_arr1 + size_arr2); s++) {
printf("%d\n", ptr1_last);
}
return 0;
}
int join_arrays(int *array1, int *array2, int arr1_size, int arr2_size) {
int counter_arr1, counter_arr2, m = 0;
int last_arr[arr1_size + arr2_size];
for (counter_arr1 = 0; counter_arr1 < arr1_size; counter_arr1++) {
last_arr[counter_arr1]=array1[counter_arr1];
}
for (counter_arr2 = counter_arr1; counter_arr2 < (arr1_size + arr2_size); counter_arr2++) {
last_arr[counter_arr2] = array2[m];
m++;
}
return last_arr[0];
}
Modified the code to create the receiving array in main and pass a pointer to it to the merge function because the local array last_arr would no longer exist when the function returned in your code.
#include <stdio.h>
#include <stdlib.h>
//Prototype changed to include a pointer to the receiving array, also no longer returns a value.
void join_arrays(int *last_arr, int *array1,int *array2,int arr1_size,int arr2_size);
int main()
{
int size_arr1,size_arr2,i,num1=1,s;
printf("Please enter the size of the first array: ");
scanf("%d",&size_arr1);
int arr1[size_arr1];
printf("start fill your first array: \n");
for(i=0; i<size_arr1; i++)
{
printf("enter element number %d: ",num1);
scanf("%d",&arr1[i]);
num1++;
}
num1=1;
printf("Please enter the size of the second array: ");
scanf("%d",&size_arr2);
int arr2[size_arr2];
int *ptr1_last;
printf("start fill your second array: \n");
for(i=0; i<size_arr2; i++)
{
printf("enter element number %d: ",num1);
scanf("%d",&arr2[i]);
num1++;
}
int last_arr[size_arr1 + size_arr2]; //Create receiving array here
join_arrays(last_arr, arr1,arr2,size_arr1,size_arr2); //And pass it to the function.
printf("merged array= \n");
for(s=0;s<(size_arr1+size_arr2);s++)
{
printf("%d\n", last_arr[s]);
}
return 0;
}
void join_arrays(int *last_arr, int *array1,int *array2,int arr1_size,int arr2_size)
{
int counter_arr1, m=0;
for(counter_arr1=0; counter_arr1<arr1_size; counter_arr1++)
{
last_arr[counter_arr1]=array1[counter_arr1];
}
for(; counter_arr1<(arr1_size+arr2_size); counter_arr1++)
{
last_arr[counter_arr1]=array2[m];
m++;
}
}
With that function you return only the first element of the last_array, you should create a global array so it's visible in all functions, or return a pointer of the last_array[0] position in memory

Resources