I have already done the sorting part and the copy but I am really struggling to put it together.
Here is only the sorting part because i am not so familiar with it. My main problem is when I start copying the array it only copies the first 2 number then stops and I think its a small problem in the for loop somewhere but i cant find it.
int main ()
{
int number[30];
int number2[30];
int i, j, a, n;
printf("Enter the value of N\n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] < number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The array is copied and sorted like:\n");
for (i = 0; i < n; ++i)
{
printf("%d\n", number[i]);
}
system("Pause");
}
I compiled (MinGW) and ran this exact code and got the following output:
Enter the value of N
10
Enter the numbers
9
1
0
2
8
3
7
5
4
6
The array is copied and sorted like:
9
8
7
6
5
4
3
2
1
0
Press any key to continue . . .
It looks like it is correctly reverse-sorting the input values. Note that this is a fairly common sorting algorithm (https://www.geeksforgeeks.org/bubble-sort/).
Based on this I would argue that the for loop works as is, assuming that you are looking for a reverse sort.
I am not sure what exactly is meant by "copying the array". Array number2 is unused and there are no operations that appear to copy the array number, just operations for loading it, sorting it and printing it.
Related
first of all, I'm just starting to learn C programming on my own so please don't be mad if I'm explaining or doing something wrong, I tried to search similar question to my problem on StackOverflow but I couldn’t find one so please if I'm doing something wrong, take it easy on me I'm only trying to learn.
I have an issue I can't understand, I wrote a sorting list program using the Insertion sort algorithm, that runs differently on different compilers.
when I enter only positive numbers everything works smoothly but if I add some negatives numbers, depending on the compiler, it sometimes works and sometimes does not work at all/ prints a weird result
#include <stdio.h>
#include <string.h>
int main()
{
// gathering sources for sorting an array:
int myArray[5];
int count = 1;
for (int arrayIndex = 0; arrayIndex < 5; arrayIndex++)
{
printf("\nEnter the #%d array element: ", count);
scanf(" %d", &myArray[arrayIndex]);
count++;
}
// calculate the last array index
int myInt = myArray[0];
int arrayLength = ((sizeof(myArray)) / (sizeof(myInt))) - 1;
// printing the unsorted array
printf("\nthe array was: ");
for (int i = 0; i <= arrayLength; i++)
{
printf(" %d ", myArray[i]);
}
// sorting the array using insertion sorting algorithm:
for (int index = 1; index <= arrayLength; index++)
{
int numberCheck = index;
while (index >= 1 && myArray[numberCheck] < myArray[numberCheck - 1])
{
// swap the places:
int temp;
temp = myArray[numberCheck];
myArray[numberCheck] = myArray[numberCheck - 1];
myArray[numberCheck - 1] = temp;
// move the next element
numberCheck--;
}
}
// printing the sorted array:
printf("\nthe sorted array is now: ");
for (int i = 0; i <= arrayLength; i++)
{
printf(" %d ", myArray[i]);
}
return 0;
}
for example if I enter (0,-2,-4,12,5)
on C Online Compiler - Programiz
I get this result :
the array was: 0 -2 -4 12 5
the sorted array is now: -4 -2 0 5 12
but if I enter the same exact code on the Vscode Zsh compiler (I'm using a MacBook and to my knowledge, I didn't change anything on the compiler settings)
I get the result :
the array was: 0 -2 -4 12 5
the sorted array is now: 5 6
I tested out your code and found a few areas where processing of array elements was going out of bounds. Some places, the value of the index was -1 and some places the value was equal to the array length value (e.g. index values that equate to myArray[5] which again is out of bounds).
Following is a copy of your code with a bit of cleanup to illustrate some usual and customary methods for processing "for" loops and processing arrays.
#include <stdio.h>
#include <string.h>
int main()
{
// gathering sources for sorting an array:
int myArray[5];
int count = 1;
for (int arrayIndex = 0; arrayIndex < 5; arrayIndex++)
{
printf("\nEnter the #%d array element: ", count);
scanf(" %d", &myArray[arrayIndex]);
count++;
}
// calculate the last array index
int myInt = myArray[0];
int arrayLength = ((sizeof(myArray)) / (sizeof(myInt))); /* Omittted the subtraction of 1 */
// printing the unsorted array
printf("\nthe array was: ");
for (int i = 0; i < arrayLength; i++) /* Set loop test to be less than array length */
{
printf(" %d ", myArray[i]);
}
// sorting the array using insertion sorting algorithm:
for (int index = 1; index < arrayLength; index++)
{
int numberCheck = index;
//while (index >= 1 && myArray[numberCheck] < myArray[numberCheck - 1]) /* This line of code was allowing numberCheck - 1 to be less than zero */
while (numberCheck > 0 && myArray[numberCheck] < myArray[numberCheck - 1]) /* Revised version of the test */
{
// swap the places:
int temp;
temp = myArray[numberCheck];
myArray[numberCheck] = myArray[numberCheck - 1];
myArray[numberCheck - 1] = temp;
// move the next element
numberCheck--;
}
}
// printing the sorted array:
printf("\nthe sorted array is now: ");
for (int i = 0; i < arrayLength; i++) /* Revised this to not go out of bounds */
{
printf(" %d ", myArray[i]);
}
printf("\n");
return 0;
}
It appears in the program that you are attempting set up for loop and range testing based on a range of "1" to "array length"; whereas, the usual range processing is from "0" to "less than array length". When I did those bits of cleanup, I was able to acquire a properly sorted array from the five values entered.
#Una:~/C_Programs/Console/Sorting/bin/Release$ ./Sorting
Enter the #1 array element: 700
Enter the #2 array element: 343
Enter the #3 array element: 2
Enter the #4 array element: 58
Enter the #5 array element: 400
Array length: 5
the array was: 700 343 2 58 400
the sorted array is now: 2 58 343 400 700
Note the comments I added to hopefully clarify bits for you. Try that out and see if it meets the spirit of your project.
I'm trying to accomplish a simple task in C which is to print out the smallest number from array 1 and smallest number from array 2. Both array elements are imputed by the user.
First one just returns 0 (which in my testing case its supposed to be 1) and the other one returns the correct one (11). I seriously can't understand why and I also tried to google this with no result so that's when I once again decided to seek help here!
int main () {
int masyvas1[10] = {0};
int masyvas2[10] = {0};
for(int i = 0; i < 10; i++){
int x;
printf("Ivesk pirmo masyvo 10 sk: ");
scanf("%d", &x);
masyvas1[i] = x;
}
for(int i = 0; i < 10; i++){
int x;
printf("Ivesk antro masyvo 10 sk: ");
scanf("%d", &x);
masyvas2[i] = x;
}
int mas1maz[2] = {0, 0};
for(int i = 0; i < 10; i++){
if(masyvas1[i] < mas1maz[1]){
mas1maz[1] = masyvas1[i];
}
if(masyvas2[i] < mas1maz[2]){
mas1maz[2] = masyvas2[i];
}
}
printf("testas: %d %d", mas1maz[1], mas1maz[2]);
}
If I enter numbers say from 1 to 10 for the first array and 11 to 20 for the second the program output is: testas: 0 11 which I was expecting it to be testas: 1 11
Thank you in advance!
I would like you to go over your program by trying what is below
int mas1maz[2] = {0, 0};
The Array has 2 elements, try to print each element.
Note: there are only 2 elements but I am printing 3 as you have used mas1maz[2] ( this is grabage= 11)
printf("%d,%d,%d",mas1maz[0],mas1maz[1],mas1maz[2]);
Then you are trying to compare with mas1maz[1]=0, this will result in a minimum always equal to zero.
for(int i = 0; i < 10; i++) {
/*
*/
if(masyvas1[i] < mas1maz[1]) {
mas1maz[1] = masyvas1[i];
}
Here you are tyring to compare mas1maz[2] with garbage=11, this is the reason why you see 11.
if(masyvas2[i] < mas1maz[2]) {
mas1maz[2] = masyvas2[i];
}
What you should try is the following :
for(int i = 0; i<9; i++) {
if(masyvas1[i]>masyvas1[i+1])
{
/*copy to your array*/
mas1maz[0]=masyvas1[i]
}
/* similarly for masyvas2*/
}
see that for an array of length len, indices of the array ranges from 0 to len-1
if(masyvas2[i] < masyvas2[i]){
mas1maz[2] = masyvas2[i];
}
Change your second if as follow. You was checking for smaller number in masmaz1 array and was passing 2 in array parameters which is not compatible. As you have initialized an array for 2 locations 0 and 1 as array locations are started from 0. So change that Second if to compare it with itself for smallest number.
int min;
int max;
int i;
min=max=mas1maz[0];
for(i=1; i<10; i++)
{
if(min>mas1maz[i])
min=mas1maz[i];
}
You should use this after you fill your tables with scanf to find the minimum value
then compare the two different minimums
I am trying to sort an array of structs (A SJF Scheduler). I am using the qsort library function to sort the structs in increasing order according to the attribute bursttime. However, the output is not correct. I've checked some SO questions about the same but they served no use.
struct job
{
int jobno;
int bursttime;
};
typedef struct job job_t;
int mycompare(const void* first, const void* second)
{
int fb = ((job_t*)first)->bursttime;
int sb = ((job_t*)second)->bursttime;
return (fb - sb);
}
int main()
{
int n;
printf("Enter number of jobs: ");
scanf("%d", &n);
job_t* arr = (job_t*)malloc(sizeof(job_t) * n);
for(int i = 1; i <= n; ++i)
{
printf("Enter Burst time for Job#%d: ",i);
scanf("%d", &(arr[i].bursttime));
arr[i].jobno = i;
}
printf("\n");
printf("Order of the Jobs before sort:\n");
for(int i = 1; i <= n; ++i)
{
printf("%d\t", arr[i].jobno);
}
qsort(arr, n, sizeof(job_t), mycompare);
printf("\n");
printf("Order of the Jobs after sort:\n");
for(int i = 1; i <= n; ++i)
{
printf("%d\t", arr[i].jobno);
}
printf("\n");
printf("\n");
return 0;
}
This is my inputfile:
4
7
2
9
4
The output I'm getting is:
Order of the Jobs before sort:
1 2 3 4
Order of the Jobs after sort:
2 1 3 4
The expected order should be: 2,4,1,3. Am I missing anything?
At least this problem
for(int i = 1; i <= n; ++i) // bad
Use zero base indexing.
for(int i = 0; i < n; ++i)
You could change the indexing scheme to start from zero, as others have suggested, and this would certainly be the idiomatic way to do it.
But if you want to use 1-based indexing, you'll need to allocate an extra place in the array (position 0 that will never be used):
job_t* arr = (job_t*)malloc(sizeof(job_t) * (n + 1));
Then you'll need to start your sort at position 1 in the array:
qsort(&arr[1], n, sizeof(job_t), mycompare);
And, of course, you'll have to write your code to index from 1 -- but you've already done that.
The problem is that so many standard functions in C use zero-based indexing that doing anything else is inexpressive. That's a bigger problem than wasting one array position. But, for better or worse, I've had to convert to C a load of code from Fortran, so I've gotten used to working both ways.
I don't know what's happening with this code.
#include<stdio.h>
int main()
{
int ii[5], i;
for (i=1; i<=5; i++)
{
scanf("%d", &ii[i]);
}
printf("----------------------\n");
for(i=1; i<=5; i++)
printf("%d\n", ii[i]);
return 0;
}
After compiling when I provide input as
1 2 3 4 5
then it prints as it is,
but when I provide input in reverse order:
5 4 3 2 1
it keeps on asking up to some more digits and after that it prints out some random digits from given set of input.
How can I fix this?
c uses 0 indexing that means that array indexes start at 0 not 1. A for loop over an array should look like this:
int array[ARRAY_LENGTH], i;
for (i = 0; i < ARRAY_LENGTH; ++i) {
This will ensure that i will go from 0 to ARRAY_LENGTH - 1 and will not go outside the bounds of your array.
These lines:
for(i=1; i<=5; i++)
printf("%d\n", ii[i]);
will Access element 5 of ii where the maximum index is 4. This will cause Undefined Behavior which is likely why you are seeing random numbers appear.
I'm learning C on my own and doing a few exercises. The following code reads in an
array of integers from the user. The integers are printed out when the user types in a "0" or when the array is filled. Now the problem is the output. When I type in "0" after I have typed in 3 digits e.g. 1 2 3 the output is the following: 1 2 3 -858993460 -858993460. I am not sure why I get the value "-858993460" but I have already found a solution to avoid it. Now my question is what the values mean and if there is a smarter solution than mine which is presented below as comments.
#include <stdio.h>
#include <string.h>
#define arraylength 5
int main ()
{
//const int arraylength = 21; //alternative possibility to declare a constant
int input [arraylength] ;
int temp = 0;
//int imax = 0;
printf("Please type in a your digits: ");
for (int i = 0; i < arraylength; i++)
{
scanf("%d", &temp);
if ( temp !=0)
{
input[i]= temp;
//imax= i;
}
else
{
//imax= i;
break;
}
if (i < arraylength-1)
printf("Next: ");
}
for (int i =0; i < arraylength; i++ ) // switch arraylength with imax
{
printf("%d", input[i]);
}
getchar();
getchar();
getchar();
}
This happens because irrespective of when the 0 input is given you print all 5 numbers:
for (int i =0; i < arraylength; i++ )
To fix this you can print only the number(s) user entered before entering a 0 by running a loop from 0 to i:
for (int j =0; j < i; j++ )
Those 2 numbers are the garbage that was left in the memory locations for the last 2 parts of your array. You never initialise those when you only input 3 numbers, so when you go through and print all 5 elements in the array, it prints whatever garbage was in the memory.
You print all integers in array which is size of arraylength = 5. So you get 5 integers in output. As you didn't initialize array, you get uninitilized values as 4th and 5th elements of array. You can use memset(&input, 0, arraylength*sizeof(int)); to set initials values in array to 0.