Program to run function - c

I have a question for my assignment:
Write a function called second which takes, as parameters, an array of
positive integers and also an integer representing the size of the
array. The function returns the value of the second largest integer in
the array. If the largest integer in the array repeats, then the
second largest integer is also the largest. For example, if we have
{1, 2, 3, 4, 5, 5 }, the second largest integer is
5. The function should not change the contents of the array in any way. You can assume that the size of the array is at least two.
What I've done:
int second(const int arr[], int size)
{
int num1,num2;
int i;
if(arr[0]>arr[1])
{
num1=arr[0];num2=arr[1];
}
else
{
num1=arr[1];num2=arr[0];
}
for (i=2; i<size; i++)
{
if (arr[i]>num1)
{
num2=num1;
num1=arr[i];
}
else if (arr[i] > num2)
{
num2=arr[i];
}
}
return num2;
}
I have no idea how to type a program that can run the above function and display the integer '5'

The function should not change the contents of the array in any way.
Use a temporary array to perform all the operations. Simply copy the elements from the old array to the new temp array.
Write a function called second which takes, as parameters, an array of
positive integers and also an integer representing the size of the
array
Case 1: if the array is unsorted
You could just sort the elements(ascending order) and return the second last element.
Case 2: If the array is sorted
Just return the second last element.
There are lots of sorting algorithms like quicksort and mergesort which give you a better runtime but you could use bubble sort as well if there is no constraint on time complexity.
Additional Hint:
int second(const int arr[], int size)
{
int temp[size]; //<-----use a temporary array as you're not allowed to modify the original array
int i;
for(i=0;i<size;i++)
{
//copy the elements
}
//sort the temp array in ascending order
return temp[size-2]; //<----return the second last elements
}

I am not looking at your function second. I will leave that to you as an exercise.
To run this function, you will need to make a main program which will create this array and call this function.
#include <stdio.h>
int second(const int arr[], int size);
int main(void)
{
int arr[] = {1,2,3,4,6,7};
int N = sizeof(arr)/sizeof(arr[0]);
printf ("%d ", second(arr, N));
}
You can add your code below the code here and compile.

Related

Probable error in array declaration for sorting array of length 1M

I am required to use Selection Sort to sort out arrays of the lengths of 100K, 150K, 200K and 1M and display the time required to sort out each array, and the number of element to element comparisons.
I did this by making an array having the elements as the lengths of the arrays. Then I ran a for loop with said array and passed the element being used as the size of the unsorted array to be created and created a randomly generated array.
I then use a function call to sort.
The program ran with no problem for my first 3 array lengths ( 100K, 150K and 200K ), however it did not run at all for 1M array length sorting.
I was not able to figure out at which point of the program was it stopping execution. I first thought that the problem lies with my integer declarations as some of them were storing quantities as big as a million. For this I put printf statements periodically to understand where the flow of the program was getting interrupted and it was surprisingly the array declaration ( this is what it seems like to me, not sure though ).
I have attached the code and output that I got.
Code:
// C program for implementation of selection sort
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
long long int counterS = 0; //counter for number of element to element comparisons
void swap(int *xp, int *yp) //swap function
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], long long int n)
{
long long int i, j, min_idx; //used long long int cuz they reach upto 10^6 order
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx])
min_idx = j;
++counterS; //increments each time a comparison occurs
}
// Swap the found minimum element with the first element
swap(&arr[min_idx], &arr[i]);
}
}
// Driver program to test above functions
int main()
{
clock_t tic1, toc1;
int sz[4]={100000,150000, 200000, 1000000}; //array having array lengths
int k;
for(k=0;k<4;k++){
printf("1st check: It's the long long int declaration\n"); //1st check to get to know where it went wrong
long long int size = sz[k];
printf("2nd check: It's the array declaration\n"); //2nd check to know where it went wrong
int arr[size];
printf("3rd check: It's not the array declaration\n"); //3rd check to know where it went wrong
long long int i;
for(i=0;i<size;i++)
arr[i]=rand()%100;
long long int n = sizeof(arr)/sizeof(arr[0]);
printf("4th check: It's the random array generation\n"); //4th check to know where it went wrong
tic1 = clock();
selectionSort(arr, n);
toc1 = clock();
double time_taken = (double)(toc1-tic1)/CLOCKS_PER_SEC;
printf("5th check: It's the function call\n"); //5th check to know where it went wrong
printf("Selection Sort - time = %lf seconds, element by element comparisons = %lld\n",
time_taken, counterS );
}
return 0;
}
Output:
1st check: It's the long long int declaration
2nd check: It's the array declaration
3rd check: It's not the array declaration
4th check: It's the random array generation
5th check: It's the function call
Selection Sort - time = 11.458000 seconds, element by element comparisons = 4999950000
1st check: It's the long long int declaration
2nd check: It's the array declaration
3rd check: It's not the array declaration
4th check: It's the random array generation
5th check: It's the function call
Selection Sort - time = 59.196000 seconds, element by element comparisons = 16249875000
1st check: It's the long long int declaration
2nd check: It's the array declaration
3rd check: It's not the array declaration
4th check: It's the random array generation
5th check: It's the function call
Selection Sort - time = 120.349000 seconds, element by element comparisons = 36249775000
1st check: It's the long long int declaration
2nd check: It's the array declaration
Define your large array outside any function.
int large[1000000];
int main(void) {
int sz[4] = {100000, 150000, 200000, 1000000};
for (int k = 0; k < 4; k++) {
// use the first sz[k] elements of large
}
}
Since everything else is working i would say you dont have enough bits to allocate a continious array of 1M size on the go, so as others commented i would suggest malloc() .
Others in your class may have this working because on their machine there is enough stack space to allocate 1M on the go. See if malloc() solves it and then you will know for sure.

convert an array to multi dimensional C without using pointer

First of all, I would like to know if its possible. If so, please checkout my code and tell me what is wrong.
int m[n]; // this is where I pass the values to a array
for(int i=0;i<n;i++) {
scanf("%d",&a);
m[i]=a;
}
int v[n][b]; // this is where I pass the values from a array to a 2d array
for(int i=0;i<n;i++) { // but for some reason it doesnt work
for(int j=0;j<b;j++) {
v[i][j]=m[i];
}
}
}
The output is :
something like this
v[0][0]:0
v[0][1]:0
v[1][0]:1
v[1][1]:1
....
but I want something like this:
v[0][0]:0
v[0][1]:1
v[1][0]:2
v[1][1]:3
without repeating the values
P.S- if I need to use pointers you can also explain me that way but I would prefer the first one.
In assigning to v[i][j], you are constantly reassigning whatever value was in m[i].
Instead try:
v[i][j] = m[i*n + j];
This is only going to work if the array m has n*b elements.
i*n represents the row you're working on, and j is the column. Or vice-versa, it's up to you how you imagine it.
#include <stdio.h>
int main(){
int m[6]; // this is where I pass the values to a array
int i;
int j;
int k;
int a;
for(i=0;i<6;i++) {
scanf("%d",&a);
m[i]=a;
}
k=0;
int v[2][3]; // this is where I pass the values from a array to a 2d array
for(i=0;i<2;i++) { // but for some reason it doesnt work
for(j=0;j<3;j++) {
v[i][j]=m[3*k+j]; // 3 is the maximum i value [n of your code]
}
k++;
}
return 0;
}
Just used OP's code and changed:
1) Defined all integer variables.
2) the int inside the for removed to be compatible code with every c compiler (OP doesn't really need this changes)
3) Added a variable k that been increased with the changes of outer loop variable and used it in the command v[i][j]=m[3*k+j]; to give the appropriate m value to the new array. (3 been explained in the comment of the same line)
See #Pablo's comment for not using k
Assuming you have at least as many elements in your 1D array as your 2D array and you want to fill in your 2D array in row major order, it suffices to just increment an index for your 1D array every time you read an element from it.
int v[n][b];
int k = 0;
for(int i=0;i<n;i++) {
for(int j=0;j<b;j++) {
v[i][j]=m[k++];
}
}

Counting sort in C apparently works but binarysearch doesn't

I am looking for help regarding the implementation of a counting sort function in the CS50 Course in week 3.
An int Array has to be sorted.
I tested various unsorted arrays and my counting sort function seems to sort the array just correctly, yet my search functions won't work on the sorted array after.
Could someone give me a hint?
void countsort( int array[], int size) {
int count=0;
int zahl=0;
int max=65536;
int countarr [max];
int finalarr [size];
memset (countarr, 0, sizeof(countarr));
for(int i=0;i<size;i++) {
zahl=array[i];
countarr[zahl]++;
}
for(int i=0;i<max;i++) {
while(countarr[i]>0) {
finalarr[count]=i;
countarr[i]--;
count++;
}
}
array=finalarr;
for(int i=0;i<size;i++){
printf(" %i ",array[i]);
}
}
This is my search algorithm used after the array is sorted, it works with sort algorithms from other people.
bool binarysearch(int value, int values[], int n){
int start=0,
end=n,
mid=0,
midpos=0;
while(end>0) {
midpos=(start+end)/2;
mid=values[midpos];
if(mid==value) return true;
if(mid<value) start=++midpos;
if(mid>value) end=--midpos;
}
return false;
}
In binarysearch, the loop condition while(end>0) is wrong.
If we search for a value which is greater than at least one of the elements of the array, end will never be zero.
Try changing it to while(end>=start), which literally means that the considered interval is non-empty.
In countsort, the line array=finalarr; does not copy the whole array.
Instead, the local variable array becomes a pointer to finalarr.
The contents of the original array remain unchanged, and the sorted array is gone when you exit the function.
This explains why your binary search works (better) with other sort functions.
Try changing finalarr[count]=i; to array[count]=i; and get rid of finalarr completely, putting the values into array right away.
Alternatively, you can use memmove instead of that line.

give me a hand to understand this code

i have to write a c code that finds minimum of an array using recursion.i found this in the internet, but i don't understand it very well, can someone help me understand it?
#include <stdio.h>
int a[100],i;
void read(int i,int n)
{
if(i>=n)
return;
printf("element %d",i);
scanf("%d",&a[i]);
read(i+1,n);
}
int rec(int a[],int n)
{
int min;
if(n==1)
return a[0];
else {
min=rec(a,n-1);
if(min<a[n-1])
return min;
else
return a[n-1];
}
}
void main()
{
int i,j,n,a[100];
printf("enter n :");
scanf("%d",&n);
read(0,n);
printf("\n%d",rec(a,n));
getch();
}
if n=1, then min. is a[0] as there is only one element.
if n>1, then it is calling rec with the array and n-1 as the length each time. So, there will be a time when n=1 and returns a[0]. Then it will compare a[0] with a[1]. And return the minimum. Then it will compare the returned value minimum with a[2] and return the smaller value....and so on.
It calculates the minimal value in the array. Look at it that way:
Suppose you're given an array with 10 numbers. A magician tells you the the minimal value of that last 9 elements is 5. You now take the first element and compare it to 5. if it's smaller you return it, otherwise you return 5. The magician is the recursive call to the array with the last n-1 numbers.
rec(a, n) return the minimum value in {a[0], ..., a[n-1]}
Now we discuss two cases:
If n = 1, then rec(a,n) should be a[0], since there is only one value
Otherwise, rec(a,n) should be the minimum value of rec(a,n-1) (that is, the minimum value in {a[0],..,a[n-2]}) and a[n-1], which is what the following code do:
min=rec(a,n-1);
if(min<a[n-1])
return min;
else
return a[n-1];
int rec(int a[],int n)
{
int min;
if(n==1)
return a[0];
else {
min=rec(a,n-1);
if(min<a[n-1])
return min;
else
return a[n-1];
}
}
This function will go through all of your array elements, then compare them one by one, and each time return the smaller one, giving you the minimum of your array :
example : for a = {10,2,4,5}
rec will start from 5 and just calls itself with the previous elem until he's at the first : 10
then will return 10
will compare 10 with 2 and return 2 because 2 < 10
will compare 2 with 4 and return 2 because 2 < 4
will compare 2 with 5 and return 2 because 2 < 5
This program reads a size of an array the user wants to input, next it calls "read" which reads array elements of the given size recursively and fills in global array "a". Next it tries to find a minimal value of the local "a" array using recursive function "rec", that is initialized with garbage by the fact of being of "auto" variable type and types this value to the terminal screen. Next it waits for the user to type any character.

Array in c programming

I need help with this one:
Implement function int array_reader(int *array, int size) that reads integer values using scanf into pre-allocated array. Parameter size gives the maximum length of the array, and the maximum number of values to be read. If user does not give a valid integer (as can be seen from return value of scanf), the array ends, even if the maximum size was not yet reached. The function returns the final size of the array at the end, which can be smaller that the incoming size parameter, if the user finished the input with non-valid integer.
Below is an example how this function can be tested:
int array[10];
int n = array_reader(array, 10);
printf("%d numbers read\n", n);
I have done (but it is not ready yet):
int array_reader(int *array, int size)
{
int array[10];
scanf("%10d", &array[10]);
if (scanf("%10d", &array[10]) =! 10)
{
break;
}
}
Can you help me to continue? Thanks.
There is no function in standard C that can read into an array from a user like that, you have to loop over the array, reading values one by one.
You also have a few other problems:
You make a local variable array that shadows the argument, so you read only into that local array and not the one passed as the argument.
when you use 10 as index you are indexing out of bounds for the array. Indices range from zero to size - 1.
You don't return anything, even though you tell the compiler you would. That means that the assignment in the calling function will assign an unknown value.
The break statement does nothing outside of a loop.
The scanf function returns the number of values it converted, not the number of characters it read. So if you're scanning for only one item then scanf will return either 1, 0 or EOF.
For example like this
int array_reader(int *array, int size){
int count = 0;
do{
if(1!=scanf("%d", array++))
break;
++count;
} while(count < size);
//To be clear the buffer when there is bad input?
return count;
}
Thanks for answers!
You can make it also with for loop? Like this:
int array_reader(int *array, int size){
for(int count = 0; count < size; count++){
if(1!=scanf("%d", array++))
break;
else
return count;
}
}

Resources