Hi I have problem with initializing my function for printing an error message if some numbers in an array are same.
#include<stdio.h>
#include<stdlib.h>
void printRepeating(int arr[], int size)
{
int i, j;
for(i = 0; i < size; i++)
for(j = i+1; j < size; j++)
if(arr[i] == arr[j])
printf("Wrong input. Same numbers in array!\n");
}
int main()
{
int arr[200],i;
int res, num;
while((res = scanf("%d", &num)) == 1)
{
arr[i++] = num;
if(num == 0){
break;
}
}
for(i = 0; i < arr[i]; i++)
printf("%d ", arr[i]);
printf("\n");
int arr_size = sizeof(arr[i])/sizeof(arr[0]);
printRepeating(arr, arr_size);
return 0;
}
If I scan 1 2 3 1 4 5 0, my function printRepeating wont start nevertheless I have numbers 1 1 that are same in the array, Why ? And another problem is when I type 1 2 3 1 5 0 it only prints 1 2 3 and for example I when I scan 1 2 3 4 5 6 7 8 9 0 it prints all numbers except for 0.
There are multiple issues in your code. First, initialize i to be 0, and declare a new variable j alongside i,
int arr[200], i = 0, j;
The size of your array would simply be i, which you increment every time you insert an element in the array, and change this,
for(i = 0; i < arr[i]; i++)
printf("%d ", arr[i]);
to this
for(j = 0; j < i; j++)
printf("%d ", arr[j]);
since the size of your array is stored in variable i. Also, the way you are calculating the size of your array is wrong which returns 1 everytime since the numerator and denominator are the same. Generally, it is sizeof(array)/sizeof(array[0]), and in this case, it too, would return 200, since the size of your declared array is 200, but since you increment your i every time at insertion, simply set your arr_size to be i.
int arr_size = i;
This line
int arr_size = sizeof(arr[i])/sizeof(arr[0]);
does not do what you are expecting. You are only dividing the size of two elements of the array, which are always the same size, thus always giving 1 as result. If you want to give the number of elements to the function, give it a variable that you used to count each number as you read them.
Also this:
for(i = 0; i < arr[i]; i++)
printf("%d ", arr[i]);
Is only printing numbers that are not larger than their indices. Again, your program is missing a variable to count the number of input values.
Related
I need to input my own array and give its own elements, from that array i need to print the same one but if theres a number that is prime, it needs to switch it with the next number. Example:
My array: 4 6 3 5 7 11 13
The new array: 4 6 5 3 11 7 13
Here prime numbers are, 3 5 7 and 13, but 13 doesnt have an element to switch itself, so it stays the same.
#include <stdio.h>
#define array 100
int prime(int b
)
{
int i;
for (i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return b; // not prime
}
break;
}
return b;
}
int main()
{
int n, i, a[array];
printf("How many elements does the array have?\n");
scanf("%d", &n);
printf("Put in %d elements from the array!\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("My array is: \n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
for (i = 0; i < n; i++)
{
if (prime(a[i]))
{
int temp;
temp = prime(a[i]);
prime(a[i]) == prime(a[i + 1]);
}
}
printf("\nThe new array is:\n");
printf("%d ", prime(a[i]));
return 0;
}
I haven't learned pointers so is there a way without it or?
there are few things needs to modify
need to change function prime return type to bool. since we are interest to check if array element is Prime. if array element is Prime, return True
int prime(int b)
changed to
bool prime(int b)
also need to extend check if prime() function return true and if array index is not last element then only swap array element to next, else skip
if (prime(a[i]) == 1 && a[i-1] != n)
prost(a[i]) looks typo (I guess). corrected to a[i + 1]
this is not optimized code, it just modified version of your code. if you have concern specific performance, please follow suggestion mentioned by
chux - Reinstate Monica
code:
#include <stdbool.h>
#include <stdio.h>
#define array 100
bool prime(int b)
{
int i;
for (i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return false; // not prime
}
break;
}
return true;
}
int main()
{
int n, i, a[array];
int temp;
printf("How many elements does the array have?\n");
scanf("%d", &n);
printf("Put in %d elements from the array!\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("My array is: \n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
for (i = 0; i < n; i++)
{
if (prime(a[i]) == 1 && a[i] != a[n-1]) /* enter loop only array element is Prime number and it is not last element */
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
a[i++];
}
printf("\nThe new array is:\n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
return 0;
}
Output for above code: check out this link
How many elements does the array have?
7
Put in 7 elements from the array!
4
6
3
5
7
11
13
My array is:
4 6 3 5 7 11 13
The new array is:
4 6 5 3 11 7 13
...Program finished with exit code 0
Press ENTER to exit console.
First of all, you have a for loop that only makes one iteration because of a break keyword, also in main in a for loop with your swapping you need to assign return values from the prime function to variables, and in the same function, you should use singe '=' because you want to assign value but not to compare. Also in your same for loop, you should check if(prime(a[i+1])) so there won't be any segfaults.
I'm having a bit of trouble with this problem. The full text of the problem is as follows : "Write a function that returns a version of the given array of non-negative integers where each zero value in the
array is replaced by the smallest odd value to the right of the zero in the array. If there is no odd value to the right of the zero,
leave the zero as a zero."
Here is my code:
#include <stdio.h>
void lowestOdd(int num[], int size) {
int i, temp;
for (i = 0; i < size; i++) {
if (num[i] % 2 != 0 && num[i] < num[i + 1]) {
temp = num[i];
}
}
for (i = 0; i < size; i++) {
if (num[i] = 0) {
num[i] = temp;
}
}
}
void printArray(int array[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("%d/n", array[i]);
}
}
int main() {
int i, size;
int myarr[20];
printf("What is the size of your array? \n");
scanf("%d", &size);
for (i = 0; i < size; i++) {
scanf("%d", &myarr[i]);
}
lowestOdd(myarr[20], size);
printArray(myarr[20], size);
return 0;
}
I've tried implementing pointers in the lowestOdd function, but to no avail. I do think they're necessary here, but I'm not really that good at pointers. The warnings I get are mostly 'warning: passing argument 1 of 'lowestOdd' makes pointer from integer without a cast [-Wint-conversion]'. Also, in my code, I haven't added the statements that would check whether the number is a zero or whether there are any odd values to the right of the zero.
In the declaration
int myarr[20];
myarr is the identifier - the name used to refer to the array itself. myarr has the type int [20].
When used in this expression
lowestOdd(myarr[20], size);
[20] is the array subscript operator, accessing index 20. This is index is out of bounds, as the valid indices for the type int [20] are 0 to 19. This out of bounds access will cause Undefined Behaviour.
This warning
warning: passing argument 1 of 'lowestOdd' makes pointer from integer without a cast [-Wint-conversion]
is given because, although an invalid index to access, the expression myarr[20] evaluates to an int. lowestOdd expects an int * as its first argument.
Similar to before, in
if (num[i] % 2 != 0 && num[i] < num[i + 1])
num[i + 1] will access num[size] when i is size - 1 (again, valid indices are 0 to size - 1).
This is assignment
if (num[i] = 0)
where you want a comparison
if (num[i] == 0)
Note that
scanf("%d", &size);
for (i = 0; i < size; i++) {
scanf("%d", &myarr[i]);
risks the same out of bounds access if the user enters a value greater than 20 for size.
Ignoring the out of bounds access for a moment, lowestOdd attempts to find the last occurrence of the smaller number from each pair of numbers in the array, where the left number must be odd.
It then replaces all zeroes in the array with this value.
There is a chance temp is never assigned anything, and thus has an indeterminate value.
This is not correct.
Here is an example program (using a variable-length array).
Note that the syntax array + i is equivalent to &array[i].
? : is the conditional operator: in a ? b : c, if a is non-zero the expression evaluates to b, else it evaluates to c.
#include <stdio.h>
int min(int a, int b)
{
return a < b ? a : b;
}
int find_lowest_odd(int *base, size_t len)
{
int value = 0;
for (size_t i = 0; i < len; i++)
if (base[i] & 1) /* base[i] % 2 != 0 */
value = value ? min(value, base[i]) : base[i];
return value;
}
void mutate_array(int *a, size_t len)
{
for (size_t i = 0; i < len; i++)
if (0 == a[i]) /* search from the next position */
a[i] = find_lowest_odd(a + i + 1, len - i - 1);
}
void print_array(int *a, size_t len)
{
for (size_t i = 0; i < len; i++)
printf("%d ", a[i]);
putchar('\n');
}
int main(void) {
size_t size;
printf("What is the size of your array?: ");
if (1 != scanf("%zu", &size))
return 1;
int array[size];
for (size_t i = 0; i < size; i++) {
printf("#%zu: ", i + 1);
if (1 != scanf("%d", array + i))
return 1;
}
print_array(array, size);
mutate_array(array, size);
print_array(array, size);
}
I/O:
What is the size of your array?: 10
#1: 0
#2: 2
#3: 0
#4: 5
#5: 3
#6: 0
#7: 7
#8: 2
#9: 0
#10: 0
0 2 0 5 3 0 7 2 0 0
3 2 3 5 3 7 7 2 0 0
Once you can try this.
Here's my naive approach. For every zero in the array it is checking for the smallest odd element from that position to the last index and storing it in variable named smaller. After checking it replaces the original value of that index with smaller one.
#include<stdio.h>
void lowestOdd(int *num, int size){
int i, j;
for(i = 0; i < size - 1; i++){
if (num[i] != 0) continue;
int smaller = 99998;
for(j = i+1; j < size; j++){
if (num[j] % 2 != 0 && num[j] < smaller) smaller = num[j];
}
if (smaller != 99998) num[i] = smaller;
}
}
void printArray(int *array, int size){
int i;
for (i=0; i<size; i++){
printf("%d\n", array[i]);
}
}
int main()
{
int i, size;
int myarr[20];
printf("What is the size of your array? \n");
scanf("%d", &size);
for (i=0; i<size; i++){
scanf("%d", &myarr[i]);
}
lowestOdd(myarr, size);
printArray(myarr, size);
return 0;
}
I am trying to find the smallest element of an array, I think I am doing it correctly however I am receiving 0 as my smallest element, however, I am not entering 0 for any elements of my array.
I understand some things in here are done poorly but this is my whole code in order to be reproducible and fixed.
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
int main(){
char input[500];
printf("Enter a list of whitespace-separated real numbers terminated by EOF or 'end'.");
puts("");
printf("-----------------------------------------------------------------------------");
puts("");
gets(input);
int size = strlen(input);
int elements[size];
int i = 0;
char *p = strtok(input," ");
while( p != NULL)
{
elements[i++] = strtol(p, NULL, 10);
p = strtok(NULL," ");
}
//NUM OF ELEMENTS
int numOfElements = 0;
for(int j = 0; j < i; j++){
elements[j] = numOfElements++;
}
//MIN ELEMENT
int min = INT_MAX;
for(int k = 0; k < i; k++){
if(elements[k] < min){
min = elements[k];
}
}
printf("-----------------------------------------------------------------------------\n");
printf("# of Elements: %d\n", numOfElements);
printf("Minimum: %d\n", min);
return 0;
}
RESULT:
Enter a list of whitespace-separated numbers.
-----------------------------------------------------------------------------
1 2 3 4 5
-----------------------------------------------------------------------------
# of Elements: 5
Minimum: 0
EXPECTED:
Enter a list of whitespace-separated numbers.
-----------------------------------------------------------------------------
1 2 3 4 5
-----------------------------------------------------------------------------
# of Elements: 5
Minimum: 1
The problem in the original posted excerpt was the else in this loop:
int min = INT_MAX; //I tried int min = elements[0] also
for(int k = 0; k < i; k++){
if(elements[k] < min){
min = elements[k];
}else{
min = elements[0];
}
}
Consider what happens if you're partway through the array, and you've updated min multiple times, but now you encounter an element that's >= min. The else will reset min to elements[0]. Just delete it:
int min = INT_MAX; //I tried int min = elements[0] also
for(int k = 0; k < i; k++){
if(elements[k] < min){
min = elements[k];
}
}
As an aside, either initialization of min will work. If you initialize it to elements[0], then you can start the loop at k = 1.
Update: The above answer was based on the originally posted code excerpt. Now that more code has been posted (and the fix I showed above has been applied), there are additional problems.
The main problem is the numOfElements loop. This loop completely erases the values in elements, replacing them with 0, 1, 2, etc. So the minimum value really is 0. It's not clear what the point of this loop is. I suggest deleting it entirely. The number of values in elements is just i, so there's nothing to compute. You could rename i to numOfElements if you like.
Other problems: (1) The code needs to include <limits.h> for the definition of INT_MAX, and (2) It should not be using gets. Change it to use fgets or something similar.
//NUM OF ELEMENTS
int numOfElements = 0;
for(int j = 0; j < i; j++){
elements[j] = numOfElements++;
}
problem in here, you reset the elements array when you get count of this array
here is gdb mess when pass here
(gdb) p min
$3 = 0
(gdb) p elem
elem-hash.h elements
(gdb) p elements
$4 = {0, 1, 2, 3, 4, 5, -8096, 32767, 1431652112, 21845, 1431652512}
here is the right
//NUM OF ELEMENTS
int numOfElements = 0;
for(int j = 0; j < i; j++){
numOfElements++;
}
I do a code that will display to the screen 10 random numbers with no repetitions. I want to know if we can optimize the code or if you have a better and simple way in order to do this request.
Thanks !!
int main(){
int nbr = 0; srand(time(NULL));
int arr[10], i, j, flag;
for (i = 0; i < 10; i++)
{
do
{
nbr = rand() % 10 + 1;
flag = 1;
for (j = 0; j < i; j ++)
{
if (nbr == arr[j])
{
flag = 0;
break;
}
}
} while (!flag);
arr[i] = nbr;
}
for (i = 0; i < 10; i++)
{
printf("%5d", arr[i]);
}
system("PAUSE");
return 0;
}
So if i get what you're trying to do here it is:
generate an array of numbers between 1 and 10, in a random order (given rand() % 10 + 1)
instead of trial and error I'd suggest the following algorithm:
fill arr with 1...10
shuffle arr
this will run a lot faster
While I agree with the solution provided by Work of Artiz, this will result in the hard question to answer of when to stop shuffling.
To solve this you can use the following solution (which will use more memory, but less clock time):
1 Create an array temp having values 1..10 (ordered, not random)
2 Keep track of the length length of the array (10)
3 Generate a random index rand_i between 0 and length - 1
4 Copy temp[rand_i] to next position in your final array
5 Overwrite temp[rand_i] by temp[length-1]
6 Decrement length
7 Iterate Steps 3 - 6 until your array is filled (10 times)
This will both eliminate your excessive looping, and the problem of when to stop shuffling your array
EDIT: including code
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(){
int nbr = 0; srand(time(NULL));
int arr[10], i, j, flag;
int temp[10] = {1,2,3,4,5,6,7,8,9,10};
int length = 10;
for (i = 0; i < 10; i++)
{
nbr = rand() % length; // Generate random index between 0 and length - 1
arr[i] = temp[nbr]; // Copy value from random index in temp to next index in arr
// Now since temp[nbr] is already taken (copied to arr) we should replace it by last available value in temp (temp[lenght])
// and in the next iteration we will create a value between 0 and length -1. This will keep values not yet taken from temp in
// contiguous order
temp[nbr] = temp[length-1];
length--;
}
for (i = 0; i < 10; i++)
{
printf("%5d", arr[i]);
}
return 0;
}
Given an unsorted array A[0...n-1] of integers and an integer k; the desired algorithm in C should calculate the maximum value of every contiguous subarray of size k. For instance, if A = [8,5,10,7,9,4,15,12,90,13] and k=4, then findKMax(A,4,10) returns 10 10 10 15 15 90 90.
My goal is to implement the algorithm as a C programm that reads the elements of A, reads k and then prints the result of the function findKMax(A,4,10). An input/output example is illustrated bellow (input is typeset in bold):
Elements of A: 8 5 10 7 9 4 15 12 90 13 end
Type k: 4
Results: 10 10 10 15 15 90 90
What I've tried so far? Please keep in mind that I am an absolute beginner in C. Here is my code:
#include <stdio.h>
void findKMax(int A[], int k, int n) {
int j;
int max;
for (int i = 0; i <= n-k; i++) {
max = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > max)
max = A[i+j];
}
}
}
int main() {
int n = sizeof(A);
int k = 4;
printf("Elements of A: ");
scanf("%d", &A[i]);
printf("Type k: %d", k);
printf("Results: %d", &max);
return 0;
}
Update March 17th:
I've modified the source code, i.e. I've tried to implement the hints of Michael Burr and Priyansh Goel. Here is my result:
#include <stdio.h>
// Returning the largest value in subarray of size k.
void findKMax(int A[], int k, int n) {
int j;
int largestValueOfSubarray;
for (int i = 0; i <= n-k; i++) {
largestValueOfSubarray = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > largestValueOfSubarray)
largestValueOfSubarray = A[i+j];
}
printf("Type k: %d", k);
}
return largestValueOfSubarray;
}
int main() {
int n = 10;
int A[n];
// Reading values into array A.
for (int i = 0; i < n; i++) {
printf("Enter the %d-th element of the array A: \n", i);
scanf("%d", &A[i]);
}
// Printing of all values of array A.
for (int i = 0; i < n; i++) {
printf("\nA[%d] = %d", i, A[i]);
}
printf("\n\n");
// Returning the largest value in array A.
int largestValue = A[0];
for (int i = 0; i < n; i++) {
if (A[i] > largestValue) {
largestValue = A[i];
}
}
printf("The largest value in the array A is %d. \n", largestValue);
return 0;
}
I guess there is not so much to code. Can anybody give me a hint how to do the rest. I need an advice how to "combine" the pieces of code into a running program.
Since you are a beginner, lets begin with the simplest algorithm.
for every i, you need to find sum of k continous numbers starting from that i. And then find the max of it.
Before that you need to see how to take input to an array.
int n;
scanf("%d",&n);
int a[n];
for(int i = 0; i < n; i++) {
scanf("%d",&a[i]);
}
Also, you will need to call the function findKMax(a,n,k);
In your findKMax function, you have to implement the algorithm that I mentioned.
I will not provide the code so that you may try on your own. If you face any issue, do tell me.
HINT : You need to use nested loops.
You find max value in window many times, but output only the last max value.
The simplest correction - add output in the end of main cycle:
for (int i = 0; i <= n-k; i++) {
max = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > max)
max = A[i+j];
}
printf("Type k: %d", k);
}
The next step - collect all local max values in a single string "10 10 10 15 15 90 90" or additional array of length n-k+1: [10,10,10,15,15,90,90] and print it after the main cycle (I don't know the best approach for this in C)