high low values in array print in between - c

code is used to scan integers into an array the loop is to stop scanning when 0 is input.
after values are scanned in the highest and lowest values inside the array are to be found
after finding high and low , print the values between the the array indexs of high and low
so if input 5,2,8,7,6,12,6,4,5
output should be 2,7,6,12
my program fails after it scans in the input values and 0 is input to end the loop
#include <stdio.h>
int main(){
int high=4;
int low,i;
int array[25];
int count=0;
printf("Please input numbers for array:");
for(i=0;array[i]!=0;i+=1){
scanf("%d",&array[i]);
count+=1;
}
for(i=0;i<count;i+=1){
if(array[i]>array[high]){
high=i;
}
}
low=high;
for(i=0;i<count;i+=1){
if(array[i]<array[low]){
low=i;
}
}
for(i=low;low<=high;i+=1){
printf("%d,",array[i]);
}
}

The for loop checks the condition before each iteration, so in
array[i]!=0
you are checking uninitalized value, before reading in array[i]. If it doesn't happen to find a zero hanging around somewhere in memory, this can go on reading more than 25 values, it can even go on and on till you get a stack overflow.
Also, in the other for loops, you probably meant
i < count
The condition
low<high
is just really not appropriate.
Here is a version that should work more like expected:
#include <stdio.h>
int main(){
int high;
int low,i;
int array[25];
int count=0;
int start;
int end;
printf("Please input numbers for array:");
for (i = 0; scanf("%d", &array[i]), array[i] != 0; i += 1) {
count+=1;
if (i >= 25) {
printf("Unable to handle more than 25 input values\n");
break;
}
}
high = 0;
for (i = 1; i < count; i += 1) {
if (array[i] > array[high]) {
high = i;
}
}
low = 0;
for (i = 1; i < count; i += 1) {
if (array[i] < array[low]) {
low=i;
}
}
if (low < high) {
start = low;
end = high;
}
else {
start = high;
end = low;
}
for (i = start; i <= end; i += 1) {
printf("%d", array[i]);
if (i != end) {
printf(",");
}
else {
printf("\n");
}
}
}

#include <stdio.h>
int main(){
int low, high, array[25];
int i, count=0;
printf("Please input numbers for array:");
for(i=0;i<25;++i){
int data;
scanf("%d", &data);
if(data==0)
break;
array[count++]=data;
}
low = high = 0;
for(i=1;i<count;++i){
if(array[i]<array[low])
low=i;
if(array[i]>array[high])
high=i;
}
for(i=low;i <= high;i++){
printf("%d,", array[i]);
}
}

I've got your code working after some minor changes
#include <stdio.h>
int main()
{
int high=0; // high value assumed to be zero for ease of understanding
int low=0,i; // low value assumed to be zero for ease of understanding
int array[25];
int count=0;
printf("Please input numbers for array:");
for(i=0;;i+=1){
scanf("%d",&array[i]);
count+=1;
if(array[i]==0) // Whenever is zero is read the loop is immediately exited, otherwise looping is continued
break;
}
count--; // decrement one count (count of zero)
for(i=1;i<count;i+=1){
if(array[i]>array[high]){
high=i;
}
}
for(i=1;i<count;i+=1){
if(array[i]<array[low]){
low=i;
}
}
for(i=low;i<=high;i+=1){ //printing from low value upto high value
printf("%d,",array[i]);
}
}

Related

Why is my base case being (erroneously) triggered immediately?

I am trying to implement a merge sort algorithm in C. In the recursive array split function, my base case is occurring infinitely, despite the return statement, and the merge function is never called. Here is my code:
#include <stdio.h>
const int MAX = 1000;
int getArray(int unsorted[MAX], int upperBound)
{
int i;
for(i = 0; i <= upperBound; ++i)
{
printf("Now enter integer number %d: ", i + 1);
scanf("%d", &unsorted[i]);
while((getchar()) != '\n');
}
printf("\n");
return 0;
}
int merge(int unsorted[MAX], int sorted[1000], int lowerLeft, int lowerRight)
{
if(lowerLeft == lowerRight)
return 0;
int j = lowerRight;
for(int i = lowerLeft; i < lowerRight; ++i)
{
if(unsorted[i] <= unsorted[j])
{
sorted[i] = unsorted[i];
++j;
}
else
{
sorted[i] = unsorted[j];
++j;
}
}
return 1;
}
int split(int unsorted[MAX], int sorted[1000], int lowerBound, int upperBound)
{
printf("%d is the lBound and %d is the uBound\n", lowerBound, upperBound);
if(lowerBound == upperBound)
{
printf("\nBase case triggered.");
getchar();
return 0;
}
int middle = upperBound/2;
split(unsorted, sorted, 0, middle);
split(unsorted, sorted, middle + 1, upperBound);
merge(unsorted, sorted, lowerBound, middle);
return 1;
}
int main()
{
int unsorted[MAX];
int sorted[MAX];
int lowerBound = 0;
int upperBound;
printf("First enter the number of integers you wish to sort: ");
scanf("%d", &upperBound);
while((getchar()) != '\n');
printf("\n");
upperBound = upperBound - 1;
getArray(unsorted, upperBound);
split(unsorted, sorted, lowerBound, upperBound);
printf("\n");
for(int c = 0; c < upperBound; ++c)
{
printf("%d, ", sorted[c]);
}
return 0;
}
Why won't the merge function be called after reaching the base case? Sorry if I didn't phrase the question conveniently, hoping someone can help me out here, thanks.
Your base case is being triggered because that's how recursive algorithms work. You keep calling split() over and over again with a lower and lower gap between lowerBound and upperBound, so eventually your base case gets triggered. And that should be a good thing, since triggering the base case lets you know that your input "arrays" (singletons) are sorted and can be merged.
The reason it gets triggered "immediately" is that it must: split() gets called continually until the base case is met, so the first print statement you'll see is the base case one.

Error: CentralTendencies.exe has stopped working, upon clicking Build & Run in codeblocks

This code is to find the mean, median and mode for a given sequence of number.
#include <stdio.h>
#include <math.h>
int main()
{ /*Inputs*/
int n;
int a[n];
/*Outputs*/
float mean;
int median;
int mode;
printf("Enter the size of array: ");
scanf("%d",&n);
for(int i=0; i<n; i++)
{
printf("\nEnter the values of array: ");
scanf("%d",&a[i]);
}
/*arrange in ascending order */
int i=0;
for(i=0; i<n-1; i++)
{for(i=0; i<n-1; i++)
{
if(a[i]>a[i+1])
{
int temp = a[i+1];
a[i+1] = a[i];
a[i] = temp;
}
}
}
/*Mean of the series*/
for(i=0; i<n; i++)
{
int sum = 0;
sum = sum + a[i];
mean = sum/n;
}
/*Median of the series*/
I hope the syntax of typecasting here is right, right?
int m = floor((double)n/2);
if(n%2==0)
{
median = (a[m]+a[m-1])/2;
}
else
{
median = a[m];
}
/*Mode of the series*/
int count;
int b = 0;
for(i=0; i<n-1; i++)
{
for(int t=0; t<n; t++) //Compare a[i] with all the elements of the array
{if(a[i]==a[t])
{
count = 0;
count++;
}
if(b<count) //Update the new value of mode iff the frequency of one element is greater than that
{ // of its preceding element.
mode = a[i];
}
}
}
printf("The value of mean: %f",mean);
printf("\nThe value of mean: %d",median);
printf("\nThe value of mean: %d",mode);
return 0;
}
There were no errors in the code.
I received the following message on the prompt after "CentralT...... working":
Process returned -1073741571 (0xC00000FD) execution time : 47.686 s
Press any key to continue.
In C you cannot resize an array.
This line
int n;
defines n and leaves its value as garbage, a random value, perhaps 0.
Based on what ever n holds this line
int a[n];
defines a as array to have the number of element as per n now has.
Reading into n in this line
scanf("%d",&n);
does not change the number over a's elements.
To fix this, define a only after n has a well defined, valid value:
scanf("%d",&n);
int a[n];
To really make sure n had been set you want to test the outcome of scanf() like for example:
do {
if (1 != scanf("%d, &n))
{
puts("Bad input or failure reading n!\n");
continue;
}
} while (0);

C recursive program to print all prime factors of a given number from the biggest factor to the smallest

i'm trying to write a program that print the prime factors of a given number ,but i need to print them from the biggest factor to the smallest, for example:
for the input 180 the output will be: 5*3*3*2*2,
any suggestions? here is what i got for now :
#include<stdio.h>
void print_fact(int n)
{
if (n==1)
return;
int num=2;
while (n%num != 0)
num++;
printf("*%d",num);
print_fact (n/num);
}
int main ()
{
int n;
printf("please insert a number \n");
scanf("%d",&n);
print_fact(n);
}
for this code the output is :
*2*2*3*3*5
You can simply print the output after the recursive call returns. You need to slightly modify how you display the *, which I leave to you.
#include<stdio.h>
void print_fact(int n)
{
if (n==1)
return;
int num=2;
while (n%num != 0)
num++;
// printf("*%d",num); // remove from here
print_fact (n/num);
printf("%d ",num); // put here
}
int main ()
{
int n;
printf("please insert a number \n");
scanf("%d",&n);
print_fact(n);
}
The output this gives on input 180 is:
5 3 3 2 2
Aside, there are much more efficient ways of actually finding the numbers though.
It is much faster to find them in the ascending order, mathematically speaking. Much, much faster.
The solution, if you don't want to bother yourself with dynamic arrays, is recursion. Find the lowest prime factor, recurse on the divided out number (num /= fac), and then print the earlier found factor, which will thus appear last.
to change the order in which they are printed, you could put the printf statement after the print_fact statement. To get rid of thew leading *, you would probably want to store the results and display them after computation
well, i'm trying to optimize my algorithm
this is my code for now:
functions code
#include "prime_func.h"
int divisors(int x) /* Function To set the maximum size of the future array,
Since there is no way to find the number of primary factors
without decomposing it into factors,
we will take the number of total number divisors
(which can not be greater than the number of primary factors) */
{
int limit = x;
int numberOfDivisors = 0;
if (x == 1) return 1;
for (int i = 1; i < limit; ++i) {
if (x % i == 0) {
limit = x / i;
if (limit != i) {
numberOfDivisors++;
}
numberOfDivisors++;
}
}
return numberOfDivisors;
}
void find_fact(int n, int *arr, int size, int i) //func to find the factors and apply them in allocated array
{
int num = 2;
if (n < 2)
{
printf("error\n");
return;
}
while (n%num != 0)
num++;
arr[i++] = num;
find_fact(n / num, arr, size, i);
}
void print_fact(int *arr, int size) // func to print the array in reverse
{
int i = 0;
int first;
first = FirstNumToPrint(arr, size);
for (i = first; i>0; i--)
printf("%d*", arr[i]);
printf("%d", arr[0]);
}
int FirstNumToPrint(int *arr, int size) // func to find the first number to print (largest prime factor)
{
int i;
for (i = 0; i < size; i++)
if (arr[i] == 0)
return i - 1;
}
int first_prime(int num) // for now i'm not using this func
{
for (int i = 2; i<sqrt(num); i++)
{
if (num%i == 0)
{
if (isprime(i));
return(i);
}
}
}
bool isprime(int prime) // for now i'm not using this func
{
for (int i = 2; i<sqrt(prime); i++)
{
if (prime%i == 0)
return(false);
}
return(true);
}
main code
#include "prime_func.h"
int main()
{
int n,i=0; // first var for input, seconde for index
int *arr; // array for saving the factors
int size;//size of the array
printf("please insert a number \n");// asking the user for input
scanf("%d", &n);
size = divisors(n); //set the max size
arr = (int *)calloc(size,sizeof(int)); //allocate the array
if (arr == NULL) // if the allocation failed
{
printf("error\n");
return 0;
}
find_fact(n, arr,size,i);// call the func
print_fact(arr,size); //print the result
free(arr); // free memo
}
#WillNess #GoodDeeds #mcslane

While loop with user input validation to fill array, then search array for largest number.

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

C Segmentation Fault With Printf() and Scanf()

I'm new to C, and I'm getting a segmentation fault that I can't understand. I have the following program, which attempts to calculates the number of factors of a strictly positive number:
#include <stdio.h>
#include <math.h>
int numberOfFactors (int number, int factor) {
if (number % factor == 0) {
number = number/factor;
return numberOfFactors(number, factor) + 1;
} else {
return 0;
}
}
int check (int x) {
if (x>0) {
return 1;
} else {
return 0;
}
}
int main(void) {
int number;
printf("Please enter a positive integer n such that n >= 1: ");
scanf("%d", &number);
if (check(number)){
int i;
for (i=1; i<=number; i++) {
int factors;
factors = numberOfFactors(number, i);
printf("%d^%d ", i, factors);
}
}
return 0;
}
The segmentation fault occurs immediately after entering an integer and ENTER after these lines in main():
printf("Please enter a positive integer n such that n >= 1: ");
scanf("%d", &number);
What in these lines is causing the segmentation fault, and what can I do to avoid it?
Your recursion doesn't stop if you try to divide out factor one.
Just let factor never be 1:
for (i=2; i<=number; i++) {
int factors;
factors = numberOfFactors(number, i);
printf("%d^%d ", i, factors);
}
I should say WHY it segfaults: It's because every function call pushes the current program counter (the position in your program where you currently stand) and function arguments on the stack (aka call stack), where the stack is a relatively small memory block used for, well, function calling and local variables.
So if you are pushing your stack too hard, it will fall over. End of game, aka segfault ;)
You probably have a problem with this recursion:
int numberOfFactors (int number, int factor) {
if (number % factor == 0) {
number = number/factor;
return numberOfFactors(number, factor) + 1;
} else {
return 0;
}
}
Change your numberOfFactors to something like:
int numberOfFactors (int number)
{
int i=1;
int ret=0;
for(;i<=number;i++) {
if (number%i == 0) {
ret++;
}
}
return ret;
}
And then, change this portion:
if (check(number)){
int i;
for (i=1; i<=number; i++) {
int factors;
factors = numberOfFactors(number, i);
printf("%d^%d ", i, factors);
}
}
To something simpler like:
if (check(number)){
factors = numberOfFactors(number);
printf("%d^%d ", number, factors);
}

Resources