I have an assignment which required me to sort any random numbers. The code below is weird. The reason is after clicking running the program, if I type 5 at the beginning, it does not work perfectly, however, it works correctly with other numbers. Please help me to fix this error. I also attached the pictures to prove what I said above.
Image when enter number 5
Image when enter number 10
#include <stdio.h>
int main(){
int howmany,i,temp,swap;
printf("Enter how many numbers you want to sort: \n");
scanf(" %d",&howmany);
int number[howmany];
printf("*** The original numbers *** \n");
for (i=0;i<howmany-1 ;i++){
number[i]=(rand()% 25)+1;
printf("Random number is: %d\n",number[i]);
}
while(1){
swap = 0;
for (i=0;i<howmany-1;i++){
if(number[i]>number[i+1]){
temp = number[i];
number[i]=number[i+1];
number[i+1] = temp;
swap = 1;
}
}
if (swap == 0){
break;
}
}
printf("*** The sorted numbers ***\n");
for (i=0;i<howmany-1;i++){
printf("The sorted number: %d\n",number[i]);
}
}
The issue is because you are reading and printing one less than the actual size of the array. So the last entry of the array will have some junk value which you don't know. But while sorting you are using it and it gets sorted. Sometimes the junk value is lower than the other random values and it gets printed.
I have made the fix. Please check all the for loops.
#include <stdio.h>
int main(){
int howmany,i,temp,swap;
printf("Enter how many numbers you want to sort: \n");
scanf(" %d",&howmany);
int number[howmany];
printf("*** The original numbers *** \n");
for (i=0;i<howmany ;i++){ //Read howmany values and print
number[i]=(rand()% 25)+1;
printf("Random number is: %d\n",number[i]);
}
while(1){
swap = 0;
for (i=0;i<howmany-1;i++){
if(number[i]>number[i+1]){
temp = number[i];
number[i]=number[i+1];
number[i+1] = temp;
swap = 1;
}
}
if (swap == 0){
break;
}
}
printf("*** The sorted numbers ***\n");
for (i=0;i<howmany;i++){ //Print howmany values
printf("The sorted number: %d\n",number[i]);
}
}
Related
Im using online GeeksforGeeks for learning how to code. I just started learning but for some reason the compiler return garbage when the sum of my input exceeds 3616. Can any pro please explain to me why and how to improve my code?
Eg. input: 1 2 3 4 5 0 output:increasing order //sum of input< 3616
input: 1 2 3614 0 output:not increasing order //sum of input> 3616
This was the question:
Write a program check_order.c to read in a list of positive integers. The program is to continue asking for the next positive integer as long as the integers entered are in increasing order. The moment the input data are not in increasing order, or the input value is zero, the input ends. The program should then report whether the input data are in increasing order or not.
You may assume that at least one positive integer will be entered. If there is only one positive integer in the list, we will treat the list as it is in increasing order.
You may write all the code in the main() function.
#include <stdio.h>
int main(void){
int input, input2;
do{
input2 = input;
scanf("%d", &input);
printf("Enter positive integer: %d\n", input);
}
while(input> input2);
if(input< input2){
if(input == 0){
printf("Data are in increasing order.");
}
else{
printf("Data are not in increasing order.");
}
}
else{
printf("Data are in increasing order.");
}
return 0;
}
Resolved. thanks all!!! :)
When you don't initialize input it gets a garbage value. it can be positive or negative- and you can never know which value. To avoid that situation, you have to give an initialize value, so you can almost always be in fully control on your variables. It is alway recommended to set an initialize value to your variables.
#include <stdio.h>
int main() {
int input = 0, input2;
do {
input2 = input;
scanf("%d", &input);
printf("Enter positive integer: %d\n", input);
}
while(input > input2);
if (input < input2) {
if(input == 0) {
printf("Data are in increasing order.");
}
else {
printf("Data are not in increasing order.");
}
}
else {
printf("Data are in increasing order.");
}
return 0;
}
#include <stdio.h>
int main(void){
int inputNumber;
int counter=0;
int totalValue;
int arr[counter];
int avg;
puts("Please enter any number of positive whole numbers you would like to be averaged. Enter ' -1 ' when you are finished for your result.\n");
while(scanf("%d\n", &arr[counter])){
if(arr[counter] = -1){
break;
}
if(arr[counter] > 0){
totalValue += arr[counter];
++counter;
}
else if(arr[counter]<=0){
puts("Please enter a positive number.");
}
else{
}
}
avg = totalValue/counter;
printf("The average of your entered values is: %d", avg);
return 0;
}
I have attempted many things to try and stop it, and although this may come from a lack of knowledge is there really any way to do this other than creating an enormously large array?
I tried using a dynamic array with calloc() but i was met with the same errors. I am unsure what else is available as an option in this method.
The code is supposed to take the average of "n" user inputted values.
You do not need an array.
Quick & dirty but easier that you wanted to do
int number = 0;
int counter = 0;
int total = 0;
while (number != -1)
{
total += number;
++counter;
scanf("%d", &number);
}
printf("average = %d\n", total / (counter - 1) );
I'm having trouble storing the size of each array the user inputs. I need to do this so that I can run different calculations on each set. This is what I'm trying to do now, but it keeps throwing a segmentation fault, and I don't know what I'm doing wrong. The other thing I thought of doing was essentially make one more memory spot with malloc and just store the sizes in another array at the end of the data set arrays. Anyway, here's the code that is giving me a segmentation fault.
int construct_data_sets(int *sets[], int count) {
int set_size;
int j;
j = 0;
printf("Enter the number of elements in data set %d: ", count+1);
scanf(" %d", &set_size);
sets[count] = (int*)malloc((sizeof(int) * set_size));
if (sets[count] == NULL){
printf("Malloc failed!\n");
}
printf("Enter the data for set %d: ", count+1);
while ((j + 1) <= set_size)
{
scanf(" %d", &sets[count][j]);
j++;
}
return set_size;
}
And here's the main, I think the segmentation fault gets thrown when I call construct_data_sets().
int main() {
int command = 0, data_set, set_desired, array_size;
int number = prompt_num_sets();
int *sets[number], i = 0, *sizes[number];
while (i < number)
{
array_size = construct_data_sets(sets, i);
*sizes[i] = array_size;
i++;
}
//printf("The size of the 3rd data set is %d", *sizes[3]);
printf("Data at [data_set][1] = %d\n", sets[data_set-1][1]);
set_desired = select_data_set(number);
while (command != 7) {
printf("Choose what you would like to do:\n");
printf("1. Find the minimum value.\n");
printf("2. Find the maximum value.\n");
printf("3. Calculate the sum of all the values.\n");
printf("4. Calculate the average of all the values.\n");
printf("5. Sort the values in ascending order.\n");
printf("6. Select a different data set.\n");
printf("7. Exit the program.\n");
scanf(" %d", &command);
if (command == 7) {
exit_program();
} else if (command == 6) {
change_term(number, sets);
}
printf("====================================\n");
}
}
Any weird printf statements you may see are just me trying to make sure things are doing what they're supposed to. Let me know if you need more information from me. Thanks.
You have multiple bugs in your code and several stylistic issues. Have you tried running the code in the debugger to see exactly where things are crashing? Have you tried narrowing the code down to a smaller problem?
Your sizes array should have an element type of int instead of int *. You are dereferencing uninitialized memory since you have not allocated anything for the pointers. Your data_set variable is also uninitialized so the array access into sets is also undefined.
You should initialize all of your variables immediately upon definition. Also I would change your code to declare only one variable per statement. The current code is quite difficult to read.
I would also change your initial while loop into a for loop.
Here's a working version that doesn't crash; although, since you haven't included all of the code, I don't know if there are other parts that are broken. I've also had to remove the references to the undefined functions:
#include <stdio.h>
#include <stdlib.h>
int construct_data_sets(int *sets[], int count) {
int set_size;
int j;
printf("Enter the number of elements in data set %d: ", count+1);
scanf(" %d", &set_size);
sets[count] = (int *) malloc((sizeof(int) * set_size));
if (sets[count] == NULL) {
fprintf(stderr, "Malloc failed!\n");
exit(-1);
}
printf("Enter the data for set %d: ", count+1);
for (j = 0; j < set_size; ++j) {
scanf(" %d", &sets[count][j]);
}
return set_size;
}
int main(int argc, char *argv[]) {
int command = 0;
int number = 1;
int *sets[number], i, sizes[number];
for (i = 0; i < number; ++i) {
sizes[i] = construct_data_sets(sets, i);
}
printf("Data at [0][1] = %d\n", sets[0][1]);
while (command != 7) {
printf("Choose what you would like to do:\n");
printf("1. Find the minimum value.\n");
printf("2. Find the maximum value.\n");
printf("3. Calculate the sum of all the values.\n");
printf("4. Calculate the average of all the values.\n");
printf("5. Sort the values in ascending order.\n");
printf("6. Select a different data set.\n");
printf("7. Exit the program.\n");
scanf(" %d", &command);
if (command == 7) {
return 0;
} else if (command == 6) {
return 0;
}
printf("====================================\n");
}
return 0;
}
friend i am new in c ,so i face problem in a ,code, plz if there is any wrong in my logic,take it as a pardon eye,
I am trying to find the element in a two dimensional array, so i have declare a two dimensional array in my code, i will take a user input, the input will compare with data in an full array a column index of two dimensional array, if any data found similar of that column index then it will give the same row data of another column of array. if i give a input in my code it is giving output of the number is not in array index, though the number is in the array index, so i dont understand where is my fault.
plz help me to fix the problem.
here is my code :
#include<stdio.h>
int main()
{
int arr[10][3]={{1,5},
{2,8},
{3,27},
{ 4,64},
{5,125},
{6,216},
{ 7,343},
{8,512},
{ 9,729},
{ 10,1000}};
int i, num;
printf("Enter a number\n");
scanf("%d",&num);
for(i=0;i<10;i++)
{
if (num==arr[i][0])
printf("%d",arr[i][1]);
break;
}
if (num==10)
printf("the number is not there");
return 0;
}
You have an errant semi-colon:
if (num==10);
printf("the number is not there");
That call to printf will run each time because there is no body for the if statement. With better formatting:
if (num==10);
printf("the number is not there");
As #zoska points out, you also have the same bug here:
if (num==arr[i][0]);
I would do the following three changes at the minimum:
Change int arr[10][3] to int arr[10][2]
Change
if (num==arr[i][0]);
printf("%d",arr[i][1]);
to
if (num == arr[i][0]) {
printf("%d",arr[i][1]);
}
Change
if (num==10);
printf("the number is not there");
to
if (i == 10) { // note: 'num' changed to 'i'
printf("the number is not there");
}
Your code should look like this in the future
#include <stdio.h>
int main(void)
{
int arr[10][2] = {
{1,5},
{2,8},
{3,27},
{4,64},
{5,125},
{6,216},
{7,343},
{8,512},
{9,729},
{10,1000}
};
int i, num;
printf("Enter a number\n");
scanf("%d", &num);
for(i = 0; i < 10; i++)
{
if (num==arr[i][0]) {
printf("%d", arr[i][1]);
break;
}
}
if (i == 10) {
printf("the number is not there");
}
return 0;
}
This is a program that gets numbers input. From the numbers given or inputted, store in an array those numbers only that are even. Input will stop/terminates once 5 even numbers are already stored in the array. So here's my code:
#include <stdio.h>
#include <conio.h>
int main()
{
int num[5];
int x, counter, even[5], numEven=0;
for(counter=0; counter<5; counter++){ //loop for getting the numbers from the user
printf("Enter number: ");
scanf("%d", &num[counter]);
if(num[counter]%2==0){ //storing the even numbers
even[numEven] = num[counter];
numEven++;
}
}
printf("\n\nEven numbers: "); //printing even numbers
for(counter=0; counter<numEven; counter++){
printf("%d, ", even[counter]);
}
getch();
return 0;
}
I have confusion in the part where will I stop the inputting when there's already 5 even numbers stored. Is there something missing? Or am I doing the wrong way? I hope I can get help and suggestions with the code. Thank you very much.
#include <stdio.h>
#include <conio.h>
int main()
{
int x, even[5], numEven = 0;
while (numEven < 5)
{
scanf("%d", &x);
if (x % 2 == 0)
{
even[numEven++] = x;
}
}
printf("\n\nEven numbers: "); //printing even numbers
for(x=0; x<numEven; x++)
{
printf("%d, ", even[x]);
}
getch();
return 0;
}
You keep readin inputs till numEven reaches 5. If the read input is an even number store it in the array and increment numEven.
Use a while loop if the number of times the program will ask the user for input is not fixed and dependent on the user's input.
while (numEven < 5) {
printf("Enter number: ");
scanf("%d", &num[counter]);
if (num[counter] % 2 == 0) {
even[numEven] = num[counter];
numEven++;
}
}