Why does the array only display garbage value - arrays

The C program(main function)asks the user for the number of elements in an array(which this function works). The C function findSecondSmallest finds the second smallest element of an array(points toward the first index). The C function sortAscending arranges the array elements in ascending order (does not display the inputted elements, just garbage values) and the C function displayArray should display the arranged array in ascending order.
#include<stdio.h>
#include<limits.h>
int initializeArray(int num,int arr[]);
int findSecondSmallest(int num,int arr[]);
int *sortAscending(int num,int arr[]);
void displayArray(int num,int arr[]);
void main(){
int array[50],*arr;
int n = sizeof(array) / sizeof(array[0]);
initializeArray(n,array);
findSecondSmallest(n,array);
arr = sortAscending(n,array);
displayArray(n,arr);
}
int initializeArray(int num,int arr[]){
int i;
printf("Input the number of elements in an array: ");
scanf("%d", &num);
printf("\nEnter %d elements: ", num);
for(i = 0;i < num;i++){
scanf("%d", &arr[i]);
}
}
int findSecondSmallest(int num,int arr[]){
int i,secondSmall,small;
small = secondSmall = INT_MAX;
for(i = 1;i < num;i++){
if(arr[i] < small){
secondSmall = small;
small = arr[i];
}else if(arr[i] < secondSmall && arr[i] > small){
secondSmall = arr[i];
}
}
printf("The second smallest element is %d", secondSmall);
}
int *sortAscending(int num,int arr[]){
int i,j,temp;
for(i = 0;i < num;i++){
for(j = i + 1;j < num;j++){
if(arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
void displayArray(int num,int arr[]){
int i;
for(i = 0;i < num;i++){
printf("Element at Array[%d] = %d ", i, arr[i]);
}
}
In need of help

You need to process only the elements that the user input, not the entire array, since the rest of the array is uninitialized.
Change initializeArray() to return the number of elements that the user input. Then use that instead of n when calling the other functions.
initializeArray() wasn't using the parameter num. It should use that to check that the user doesn't enter more elements than the array can hold. So you need to use a different variable for the parameter and the user's input, so you can compare them.
findSecondSmallest() doesn't return anything, so it should be declared void, not int.
sortAscending() is supposed to return a pointer to the array, but it was missing the return statement.
In findSecondSmallest() you can initialize the variables to the first element of the array rather than INT_MAX. Then it makes sense to start your loop from i = 1, since you've already used element 0.
#include<stdio.h>
#include<limits.h>
#include <stdlib.h>
int initializeArray(int num,int arr[]);
void findSecondSmallest(int num,int arr[]);
int *sortAscending(int num,int arr[]);
void displayArray(int num,int arr[]);
int main(void){
int array[50],*arr;
int n = sizeof(array) / sizeof(array[0]);
int num = initializeArray(n,array);
findSecondSmallest(num,array);
arr = sortAscending(num,array);
displayArray(num,arr);
}
int initializeArray(int n,int arr[]){
int i, num;
printf("Input the number of elements in an array: ");
scanf("%d", &num);
if (num > n) {
printf("That's too many elements\n");
exit(1);
}
printf("\nEnter %d elements: ", num);
for(i = 0;i < num;i++){
scanf("%d", &arr[i]);
}
return num;
}
void findSecondSmallest(int num,int arr[]){
int i,secondSmall,small;
small = secondSmall = arr[0];
for(i = 1;i < num;i++){
if(arr[i] < small){
secondSmall = small;
small = arr[i];
}else if(arr[i] < secondSmall && arr[i] > small){
secondSmall = arr[i];
}
}
printf("The second smallest element is %d\n", secondSmall);
}
int *sortAscending(int num,int arr[]){
int i,j,temp;
for(i = 0;i < num;i++){
for(j = i + 1;j < num;j++){
if(arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
void displayArray(int num,int arr[]){
int i;
for(i = 0;i < num;i++){
printf("Element at Array[%d] = %d\n", i, arr[i]);
}
}

Related

Used function to find the sum of the array elements, I am getting garbage value

I wrote a code for finding the sum of array elements using functions. I have written like this(mentioned below). I am getting a garbage value as output.
#include<stdio.h>
int fact(int n, int i) {
int sum = 0, arr[100];
for (i = 0; i < n; i++) {
sum = sum + arr[i];
}
return sum;
}
int main() {
int n, arr[100], i;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int sum = fact(n, i);
printf("%d", sum);
return 0;
}
Pass the array arr to your function instead of re-declaring it inside fact
PS: Change the name of your function to something meaningful like arrSum.
Code:
#include<stdio.h>
int arrSum (int arr[], int n) {
int i, sum = 0;
for (i = 0; i < n; i++) {
sum = sum + arr[i];
}
return sum;
}
int main() {
int n, arr[100], i;
scanf("%d", &n);
if(n < 0 || n > 100)
return -1;
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int sum = arrSum(arr, n);
printf("%d ", sum);
return 0;
}

Error in selection sort with function in C

I am trying to do a selection sort using function called min().
This is my code:
#include <stdio.h>
#include <conio.h>
void main() {
int i, temp, arr[20], n, loc;
int min(int [], int, int);
printf("Enter a range of the array");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter elements");
scanf("%d", arr[i]);
}
for (i = 0; i < n; i++) {
loc = min(arr, i, n);
temp = arr[i];
arr[i] = arr[loc];
arr[loc] = temp;
}
min(int arr[], int i, int n) {
int j, loc, temp;
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
temp = j;
}
}
return (temp);
}
getch();
}
the compiler is giving one error when compiling.
it saying:
Error SELECTIONSORT.C 22: Expression Syntax.
my line number 22 is min(int arr[],int i, int n) according to my compiler Turbo C++.
Please guide me where I am going wrong.
Thanks for any help.
There are multiple problems in your code:
The function min must be defined outside the body of the main() function.
Note that it is considered bad style to declare function prototypes in a local scope. Either define the function before the main() function or put the prototype before the main() function.
Also the prototype for main() without arguments should be int main(void).
In function min, you must initialize temp to i, or use i directly.
You should print the array contents after the sort, otherwise the program has no effect.
Here is a corrected version:
#include <stdio.h>
#include <conio.h>
int min(int [], int, int);
int main(void) {
int i, temp, arr[20], n, loc;
printf("Enter a range of the array: ");
if (scanf("%d", &n) == 1) {
for (i = 0; i < n && i < 20; i++) {
printf("Enter element %d: ", i);
if (scanf("%d", &arr[i]) != 1)
break;
}
n = i; // n is the actual number of inputs
for (i = 0; i < n; i++) {
loc = min(arr, i, n);
temp = arr[i];
arr[i] = arr[loc];
arr[loc] = temp;
}
for (i = 0; i < n; i++) {
printf("%d\n" array[i]);
}
}
getch();
return 0;
}
int min(int arr[], int i, int n) {
int j;
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
i = j;
}
}
return i;
}

Swapping largest and smallest numbers in C

I want to write a program that reads 10 int values from the user and swaps the largest and smallest numbers on the first and second values, then the rest of the numbers should be in the order.
Please check the code and help me what the wrong is.
For instance:
1
9
4
5
6
7
8
2
4
5
New order should be 9 1 4 5 6 7 8 2 4 5
#include <stdio.h>
int main() {
int a[10],i,min,max=0,pos=0;
printf("Please enter 10 int values :\n");
do{
scanf("%d", &a[pos++]);
} while (pos<10);
for (i=0; i<10;i++) {
printf("%i\n",a[i]);
if (max<a[i])
{
max=a[i];
}
if (min>a[i])
{
min=a[i];
}
for (i=0;i<10;i++) {
if (a[i]==max)
a[i]=max;
if (a[i] == min) a[i] = min;
}
printf("The new order is : %d %d %d ", max, min, ...);
return 0;
}
EDIT:
It is the new form
#include <stdio.h>
int main() {
int a[10],i,pos,temp,min = 0,max = 0;
printf("Please enter 10 int values :\n");
do {
scanf("%d", &a[pos++]);
} while (pos < 10);
for ( =1; i<10;i++) {
if (a[i]>a[max])
{
max=i;
}
if (a[i]<a[min])
{
min=i;
}
}
temp=a[max];
a[max]=a[min];
a[min]=temp;
printf("%d %d",a[max],a[min]);
for (i=0;i<10;i++){
if ((i != min) && (i != max)) {
printf("%d ", a[i]);
}
}
printf("\n");
return 0;
}
As others have noted, your code does not properly identify the maximum and minimum values in the array because you are writing min and max back into the array instead of the other way around.
Since you want to swap these values, what you actually want are the indices of the min and max values of the array, and swap those.
It is best to break this code into functions instead of having everything in main. Here is a solution that will do what you want:
#include <stdio.h>
int indexofmax(int *data, int len)
{
int max = 0;
int i;
for(i = 0; i < len; i++)
{
if(data[i]>data[max]) max = i;
}
return max;
}
int indexofmin(int *data, int len)
{
int min = 0;
int i;
for(i = 0; i < len; i++)
{
if(data[i]<data[min]) min = i;
}
return min;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
// user enters in 10 ints...
int max = indexofmax(a, 10);
int min = indexofmin(a, 10);
int i;
swap(&a[min], &a[max]);
for(i = 0; i < 10; i++)
{
printf("%d ", a[i]);
}
return 0;
}
This initialization min=0,max=0 is not right.
Instead have min = INT_MAX and max = INT_MIN.
By setting min=0, you would never get the lowest number in the array if it is greater than 0.
Similarly by setting max=0, you would never get the greatest number in the array if it is lower than 0.
You are gaining nothing by this code:
for(i=0;i<10;i++)
{ if(a[i]==max) a[i]=max;
if(a[i]==min) a[i]=min; }
It is evident that this loop
for(i=0;i<10;i++)
{ if(a[i]==max) a[i]=max;
if(a[i]==min) a[i]=min; }
does not make sense.
Moreover variable min is not initialized while variable max is initialized incorrectly.
int a[10],i,min,max=0,pos=0;
For example the array can contain all negative elements. In this case you will get incorrect value of the maximum equal to 0.
And I do not see where the elements are moved to the right to place the maximum and the minimum to the first two positions of the array.
If I have understood correctly then what you need is something like the following. To move the elements you could use standard function memmove declared in header <string.h>. However it seems you are learning loops.
#include <stdio.h>
#define N 10
int main( void )
{
int a[N] = { 4, 5, 9, 6, 7, 1, 8, 2, 4, 5 };
for (size_t i = 0; i < N; i++) printf("%d ", a[i]);
printf("\n");
size_t min = 0;
size_t max = 0;
for (size_t i = 1; i < N; i++)
{
if (a[max] < a[i])
{
max = i;
}
else if (a[i] < a[min])
{
min = i;
}
}
if (max != min)
{
int min_value = a[min];
int max_value = a[max];
size_t j = N;
for (size_t i = N; i != 0; --i)
{
if (i - 1 != min && i - 1 != max)
{
if (i != j)
{
a[j - 1] = a[i - 1];
}
--j;
}
}
a[--j] = min_value;
a[--j] = max_value;
}
for (size_t i = 0; i < N; i++) printf("%d ", a[i]);
printf("\n");
}
The program output is
4 5 9 6 7 1 8 2 4 5
9 1 4 5 6 7 8 2 4 5
You're not actually altering the array.
In the second loop, you say "if the current element is the max, set it to the max". In other words, set it to its current value. Similarly for the min.
What you want is to swap those assignments.
if(a[i]==max) a[i]=min;
if(a[i]==min) a[i]=max;
Also, your initial values for min and max are no good. min is unitialized, so its initial value is undefined. You should initialize min to a very large value, and similarly max should be initialized to a very small (i.e. large negative) value.
A better way to do this would be to keep track of the index of the largest and smallest values. These you can initialize to 0. Then you can check a[i] > a[max] and a[i] < a[min]. Then you print the values at indexes min and max, then loop through the list and print the others.
int i, temp, min=0, max=0;
for (i=1; i<10; i++) {
if (a[i] > a[max]) max = i;
if (a[i] < a[min]) min = i;
}
printf("%d %d ", a[max], a[min]);
for (i=0; i<10; i++) {
if ((i != min) && (i != max)) {
printf("%d ", a[i]);
}
}
printf("\n");
Just keep it nice and simple, like this:
#include <stdio.h>
#include <stdlib.h>
#define MAXNUM 10
int find_biggest(int A[], size_t n);
int find_smallest(int A[], size_t n);
void print_array(int A[], size_t n);
void int_swap(int *a, int *b);
int
main(void) {
int array[MAXNUM], i, smallest, biggest;
printf("Please enter 10 int values:\n");
for (i = 0; i < MAXNUM; i++) {
if (scanf("%d", &array[i]) != 1) {
printf("invalid input\n");
exit(EXIT_FAILURE);
}
}
printf("Before: ");
print_array(array, MAXNUM);
smallest = find_smallest(array, MAXNUM);
biggest = find_biggest(array, MAXNUM);
int_swap(&array[smallest], &array[biggest]);
printf("After: ");
print_array(array, MAXNUM);
return 0;
}
int
find_biggest(int A[], size_t n) {
int biggest, i, idx_loc;
biggest = A[0];
idx_loc = 0;
for (i = 1; i < n; i++) {
if (A[i] > biggest) {
biggest = A[i];
idx_loc = i;
}
}
return idx_loc;
}
int
find_smallest(int A[], size_t n) {
int smallest, i, idx_loc;
smallest = A[0];
idx_loc = 0;
for (i = 1; i < n; i++) {
if (A[i] < smallest) {
smallest = A[i];
idx_loc = i;
}
}
return idx_loc;
}
void
print_array(int A[], size_t n) {
int i;
for (i = 0; i < n; i++) {
printf("%d ", A[i]);
}
printf("\n");
}
void
int_swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}

C error: expected declaration or statement at end of input

Alright, so from what I've seen, it seems these errors usually show up whenever there's a semicolon missing, or a misplaced curly-brace or something of that nature. I'm surely just missing it somehow, but I'm not able to find where the error is, or if it is due to an error of that sort. This error in pointing toward line 235, so the end of the last function.
This is the code
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAX 100
void display_menu();
int check_option(int option);
int check_size(int size);
void initialize_2Darray(int x[][MAX], int size);
void print_2Darray(int x[][MAX], int size);
void initialize_1Darray(int y[], int size);
void print_1Darray(int y[], int size);
int search_min(int x[][MAX], int r, int c, int size);
int count_match(int x[][MAX], int y[], int size, int r);
int closest_row(int x[][MAX], int y[], int size);
void sort_1Darray(int y[], int size);
void sort_2Darray(int x[][MAX], int size);
int main()
{
int size, r, c, option;
int exit = 0; //exits program when = 1
int x[MAX][MAX], y[MAX];
srand(time(NULL));
printf("Enter the size: ");
scanf("%d", &size);
while(check_size(size) == 0) {
printf("\nInvalid input, enter the size of the array again: ");
scanf("%d", &size);
}
while(exit != 6) {
initialize_2Darray(x, size);
initialize_1Darray(y, size);
display_menu();
scanf("%d", &option);
while(check_option(option) == 0) {
printf("Invalid option, enter again: ");
scanf("%d", &option);
}
//Search Min Operation
if(option == 1) {
print_2Darray(x, size);
printf("Enter the row: ");
scanf("%d", &r);
printf("\nEnter the col: ");
scanf("%d", &c);
printf("The smallest number present in row %d and col %d is %d", r, c, search_min(x, r, c, size));
}
//Count Matches Op.
else if(option == 2) {
printf("Count Matches Operation\n\n2D array\n");
print_2Darray(x, size);
printf("\n1D array\n");
print_1Darray(y, size);
printf("\nEnter the row: ");
scanf("%d", &r);
if(count_match(x, y, size, r) > 0)
printf("There are %d matches from 1D array present in 2D array", count_match(x, y, size, r));
else
printf("There are no numbers from 1D array present in 2D array");
}
//Closest Row Op.
else if(option == 3) {
printf("\nClosest Row Operation\n\n2D array\n");
print_2Darray(x, size);
printf("\n1D array\n");
print_1Darray(y, size);
printf("Row closest to the 1D array is row %d", closest_row(x, y, size));
}
//Sort 1D Array Op.
else if(option == 4) {
printf("Sort 1D Array Operation\n\n1D Array before sorting:\n");
print_1Darray(y, size);
sort_1Darray(y, size);
printf("\n\n1D Array after sorting:\n");
print_1Darray(y, size);
}
//Sort 2D Array Op.
else if(option == 5) {
printf("\nSort 2D Array Option\n\n2D Array before sorting:\n");
print_2Darray(x, size);
sort_2Darray(x, size);
printf("\n\n2D Array after sorting:\n");
print_2Darray(x, size);
}
//Exit
else if(option == 6)
exit = 6;
}
return 0;
}
void display_menu()
{
printf("\nArray operations, your options are:\n\n1: Search Min\n2: Count Matches\n3: Closest Row\n4: Sort 1D Array\n5: Sort 2D Array\n6: Exit\nEnter the operation you want to perform: ");
}
int check_option(int option)
{
if(option > 0 && option < 7)
return 1;
else
return 0;
}
int check_size(int size)
{
if(size > 0 && size <= 100)
return 1;
else
return 0;
}
void initialize_2Darray(int x[][MAX], int size)
{
int i, s; //counters
for(i=0; i < size; i++) {
for(s=0; s < size; s++) {
x[i][s] = rand()%10;
}
}
}
void print_2Darray(int x[][MAX], int size)
{
int i, s; //counters
for(i=0; i < size; i++) {
printf("\n");
for(s=0; s < size; s++) {
printf("%d ", x[i][s]);
}
}
printf("\n");
}
void initialize_1Darray(int y[], int size)
{
int i, r;
for(i=0; i < size; i++) {
r = rand()%10;
y[i] = r;
}
}
void print_1Darray(int y[], int size)
{
int i;
//Prints array values until (s)ize is reached
for(i=0; i < size; i++) {
printf("%d ", y[i]);
}
}
int search_min(int x[][MAX], int r, int c, int size)
{
int i, j; //counters
int min = 9;
for(i=0; i < size; i++) {
if(x[r][i] < min) {
min = x[r][i];
}
}
for(j=0; j < size; j++) {
if(x[j][c] < min) {
min = x[j][c];
}
}
return min;
}
int count_match(int x[][MAX], int y[], int size, int r)
{
int i, j, count;
for(i=0; i < size; i++) {
for(j=0; j < size; j++) {
if(y[i] == x[r][j])
count++;
}
return count;
}
int closest_row(int x[][MAX], int y[], int size)
{
int l, i, j; //counters
int sum = 0;
int dif = 0;
int row, totaldif; //best matching row & total dif
for(l=0; l < size; l++) {
for(i=0; i < size; i++) {
for(j=0; j < size; j++) {
dif = abs(y[j] - x[i][j]);
sum += dif;
}
if(sum < totaldif) {
totaldif = sum;
row = i;
}
sum = 0;
}
}
return row;
}
void sort_1Darray(int y[], int size)
{
int a, b, temp;
//Loops through the array, swapping values until in proper order of ascension
for(a = 0; a < size; a++) {
for(b = 0; b < size-1; b++) {
if(y[b] > y[b+1]) {
temp = y[b+1];
y[b+1] = y[b];
y[b] = temp;
}
}
}
}
void sort_2Darray(int x[][MAX], int size)
{
int a, b, c, temp;
//Loops through the array, swapping values until in proper order of ascension
for(c=0; c < size; c++) {
for(a = 0; a < size; a++) {
for(b = 0; b < size-1; b++) {
if(x[a][b] > x[a][b+1]) {
temp = x[a][b+1];
x[a][b+1] = x[a][b];
x[a][b] = temp;
}
}
}
}
}
Run your code through indent. It can help you find this sort of problem very quickly.
Here's the output from your code. As you can see, the problem is caused by a missing brace at the end of count_match():
int
count_match(int x[][MAX], int y[], int size, int r)
{
int i , j, count;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
if (y[i] == x[r][j])
count++;
}
return count;
}
/*** CLOSING BRACE MISSING HERE ***/
int closest_row(int x[][MAX], int y[], int size){
int l , i, j;
//counters

Pass array and number of its values to a function in C

I need to pass and integer array and number of values in the array to the sort(array[], count) function. It should return the number of swaps, not comparisons, made by the bubble sort. This code compiles and runs but I do not get the right output. Sometimes it has me continuously entering values despite the while(i < counter).
#include <stdio.h>
int sort(int array[], int count);
int main(void){
int numArray[100];
int counter, value;
printf("Enter array length \n");
scanf("%d", &counter);
int i = 0;
while(i < counter){
scanf("%d", &numArray[i]);
i++;
}
i = 0;
while(i < counter){
sort(numArray, counter);
i++;
}
i = 0;
while(i < counter){
printf("Values: %d\n", numArray[i]);
i++;
}
return 0;
}
int sort(int array[], int count){
int i, j, temp;
int swaps = 0;
for(i = 0; i < count-1; ++i){
for(j=0; j<count-1-i; ++j){
if(array[j] > array[j+1]){
temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
swaps++;
}
}
}
return swaps;
}
As your code is now, you only need to call sort(numArray, counter) once and "catch" the returned value:
int totalSwaps = sort(numArray, counter);
And print the result once:
printf("the number of swaps in bubblesort is: %d", totalSwaps);

Resources