I'm learning to how to use command line arguments to get a number to decide how many elements are in an array to organize. The random number generator is supposed to take the user's number and generate that many random numbers, then sort them with the bubble sort.
But the number cannot be less than 2 or greater than 10,000.
I keep getting Segmentation fault (core dumped) or I'm able to enter any number (including a number less than 2 or greater than 10,000) and it does nothing.
I'm sure it is the first part of the code that is wrong, not the subprograms and definitions, but I don't know how to fix it.
#include <stdio.h>
int randu(void);
void bubble(int *, int);
void swap(int *, int *);
int main(int argc, char *argv[]) {
int num1;
if (argc<2) {
printf("Number must be between 2 and 10000.\n");
printf("Enter a number to sort.\n");
scanf("%d", &num1);
}
if (argc>10000) {
printf("Number must be between 2 and 10000.\n");
printf("Enter a number to sort.\n");
scanf("%d", &num1);
}
sscanf(argv[1], "%d", &num1);
int main(void) {
int x[num1], i;
for(i=0;i<num1;i++)
x[i]=randu();
printf("Here are %d numbers\n", num1);
for (i=0;i<num1;i++)
printf("%d\n",x[i]);
}
}
int randu(void) {
static int seed=17;
seed=(25179*seed+13849)%65536;
return seed;
}
void bubble(int a[], int num1){
int i,j;
for (i=0;i<num1-1;i++)
for(j=num1-1;i<j;j--)
if(a[j-1]>a[j])
swap(&a[j-1],&a[j]);
}
void swap(int *a, int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
There are a number of issues with your code
1) The use of argc is wrong. argc is not the value of an argument. It is the number of arguments (including program name).
2) There is a nested main inside main. Don't do that.
3) You never call the bubble sort function. Add it.
So a minor rewrite of your program:
int randu(void);
void bubble(int *, int);
void swap(int *, int *);
int main(int argc, char *argv[]) {
int num1;
if ((argc < 2) ||
(sscanf(argv[1], "%d", &num1) != 1) ||
(num1 < 2) ||
(num1 > 10000)) {
printf("You must give a number in range 2-10.000 as input\n");
return 0;
}
int x[num1], i;
for(i=0;i<num1;i++) {
x[i]=randu();
}
printf("Here are %d numbers\n", num1);
for (i=0;i<num1;i++) {
printf("%d\n",x[i]);
}
// Call the sort function
bubble(x, num1);
printf("Here are %d numbers sorted\n", num1);
for (i=0;i<num1;i++) {
printf("%d\n",x[i]);
}
return 0;
}
int randu(void) {
static int seed=17;
seed=(25179*seed+13849)%65536;
return seed;
}
void bubble(int a[], int num1){
int i,j;
for (i=0;i<num1-1;i++)
for(j=num1-1;i<j;j--)
if(a[j-1]>a[j])
swap(&a[j-1],&a[j]);
}
void swap(int *a, int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
"prog 5" gives the output:
Here are 5 numbers
48676
38117
52608
17049
29820
Here are 5 numbers sorted
17049
29820
38117
48676
52608
Related
Since I've had several members tell me to post the whole program I'm gonna post the whole program so you can exectue it.
In this program I want to be able to register car parts and change the inventory balance.
Now to the issue. Every function itself worsk well, the problem starts when I call searchIt() function to changeIn() function. I need searchIt() so I can search the item before modifying its inventory balance.
Issues:
Whenever I serach for an item and change inventory on that item, it changes on every item.
In menu if I choose (3)change inventory balance and then serach for an item that does not exist it does not tell me "Wrong item number" instead it exits the program.
The inventory balance goes to negative numbers.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXELENGTH 20
#define MAX 100
struct car{
int itemNmr;
char name[MAXELENGTH];
int inventory;
};
typedef struct car Car;
void registerArticle(Car a[], int *pN);
void print(Car a[], int n);
void changeIn(Car a[], int n);
int searchIt(Car a[], int n);
Car createIt(int itemNmr, char name[],int inventory){
Car c;
c.itemNmr = itemNmr;
strcpy(c.name, name);
c.inventory = inventory;
return c;
}
int main(){
Car reg[MAX];
int choice;
int nrOfIt=0;
while(1){
printf("(1)Register new pars\n(2)Display all parts\n(3)Change inventory\n(4)Search\n(5)Exit\n");
scanf("%d", &choice);
switch(choice){
case 1: registerArticle(reg, &nrOfIt);
break;
case 2: print(reg,nrOfIt);
break;
case 3: changeIn(reg,nrOfIt);
break;
case 4: searchIt(reg,nrOfIt);
break;
case 5: printf("Exit");
return 0;
default: printf("Try again!");
break;
}
} return 0;
}
void registerArticle(Car a[], int *pN){
int inventory;
int itemNmr;
char name[MAXELENGTH];
while(1){
printf("Item number(0 to exit): ");
scanf("%d%*c", &itemNmr);
if(itemNmr==0){
return;
}
printf("Name: ");
scanf("%s%*c", name);
printf("Inventory: ");
scanf("%d%*c", &inventory);
a[*pN]=createIt(itemNmr,name,inventory);
(*pN)++;
}
}
void print(Car a[], int n){
if(n==0){
printf("the list is empty\n");
}else{
for(int i=0;i<n;i++){
printf("%d\t\t%s\t\t%d\n", a[i].itemNmr, a[i].name, a[i].inventory);
}
return;
}
}
int searchIt(Car a[], int n){
while(1){
int itemN;
printf("Type item number: ");
scanf("%d", &itemN);
if(itemN==0){
break;
}
int found =0;
for(int i=0;i<n;++i)
{
if(itemN==a[i].itemNmr)
{
printf("%d\t\t%s\t\t%d\n", a[i].itemNmr, a[i].name, a[i].inventory);
return i;
break;
}
}
if(!found)
{
printf("Wrong item number!");
}
}
return 0;
}
void changeIn(Car a[], int n){
int input;
int i;
searchIt(a,i);
printf("Increase or decrease by: ");
scanf("%d", &input);
for(i=0;i<n;i++)
a[i].inventory += input;
if(a[i].inventory<0)
a[i].inventory = 0;
}
```
This:
void changeIn(Car a[], int n)
{
int input;
int i;
searchIt(a, i);
passes an uninitialized register-length to searchIt(), probably causing it to go way out of bounds. Then it throws away the return value of searchIt(), and then uses the still uninitialized i to index into the array. Not good. It should be:
void changeIn(Car a[], int n)
{
int input;
const int i = searchIt(a, n);
Edit:
As you pointed out in a comment, yes the loop in changeIt() makes no sense; you don't want to change more than one element so there is no need to loop. Looping is for expressing repetition and there's no need for that here.
It should just be:
a[i].inventory += input;
if (a[i].inventory < 0)
a[i].inventory = 0;
#include<stdio.h>
void add(int a,int b)
{
int c=a+b;
printf("\nSum=%d",c);
}
void hello(char *name)
{
printf("Hello %s",*name);
}
int main()
{
int a,b;
char name[20];
void (*ptr)(int,int)=&add;
void (*hello)(char*)=hello;
printf("Enter your Name:");
scanf("%s",&name);
hello(&name);
printf("Enter the two values\n");
scanf("%d%d",&a,&b);
ptr(a,b);
return 0;
}
i want to take input from user then pass it to function but i am unable to do so.
Here is what my complier shows as error: https://i.stack.imgur.com/DVYL6.png
You don't need to access the array address, it will be implicitly converted to char* when you pass it to the functions (both to scanf and hello).
I don't see the use of the functions pointers, so in order to simplify the code, I would rewrite it like this:
#include <stdio.h>
void add(int a, int b)
{
printf("Sum = %d\n", a + b);
}
void hello(char *name)
{
printf("Hello %s\n", name);
}
int main()
{
int a = 0, b = 0;
char name[20];
printf("Enter your Name:\n");
scanf("%s", name);
hello(name);
printf("Enter the two values\n");
scanf("%d%d", &a ,&b);
add(a, b);
return 0;
}
If you insist of using the pointers, this is how main should be written:
int main()
{
int a = 0, b = 0;
char name[20];
void (*add_ptr)(int, int) = &add;
void (*hello_ptr)(char *) = &hello;
printf("Enter your Name:\n");
scanf("%s", name);
hello_ptr(name);
printf("Enter the two values\n");
scanf("%d%d", &a, &b);
add_ptr(a, b);
return 0;
}
I have a problem in my program which should prompt the user to enter number and the program will heapify them. The program runs but shows a runtime error after inserting the first number.
I tried to fix it multiple times but in vain.
If anyone could point to the precise error in the code it would be much appreciated. Thanks in advance. =)
Anyways, here's the code:
#include <stdio.h>
void insert_node(int arr[], int max){
if(max<15){
printf("Type the number to insert: ");
scanf("%d", arr[max]);
max++;
}
else
printf("Error. The heap is full!");
}
void printheap(int arr[], int max){
int count;
if(max>=1){
printf("\nPrinting the Heap:");
for(count==0;count<=max;count++)
printf(" %d", arr[count]);
}
}
void heapSort(int arr[], int max) {
int i=0,temp,lc,rc;
while(i!=max-1){
lc=2i+1;
rc=2i+2;
if(arr[i]<arr[lc]){
temp=arr[i];
arr[i]=arr[lc];
arr[lc]=temp;
}
else if(arr[i]<arr[rc]){
temp=arr[i];
arr[i]=arr[rc];
arr[rc]=temp;
}
i=i+1;
}
}
int main(int argc, char *argv[]){
int arr[15];
int max=0;
char ch;
while(ch!='n' && ch!='N'){
printheap(arr,max);
insert_node(arr,max);
if(max>1)
heapSort(arr,max);
printf("\nInsert another key (y:yes/n:no)? ");
scanf("%c", &ch);
}
return 0;
}
I'm 2nd year computer engineer and still in learning process of C language. I'd like to undesrtand how to dynamically alocate an array by using function instead of allocate inside the main.
Here is the code that works when I allocate array inside main.
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <time.h>
#define ESC_KEY 27
#define NUM_1_KEY 49
#define NUM_2_KEY 50
void find_two_largest(int a[], int n, int *largest, int *second_largest);
void arrayInit(int *,int *, int, int);
void randGenArray(int [], int);
void inputArray(int[], int);
void result(int, int);
void loading(void);
int menu(void);
int main(void)
{
system("color f5");
int n,i,largest,largest_2, *a;
arrayInit(a,&n, 2, 10);
if(menu())
randGenArray(a,n);
else
inputArray(a,n);
find_two_largest(a,n,&largest,&largest_2);
result(largest,largest_2);
return 0;
}
void find_two_largest(int a[], int n, int *largest, int *second_largest)
{
int i=0,j=0;
system("cls");
loading();
*largest = 0;
*second_largest = *largest;
for (i=1;i<n;i++){
if(*largest<a[i])
*largest=a[i];
}
for(j=1;j<n;j++){
if(*largest==a[j])
continue;
else{
if(*second_largest<a[j])
*second_largest=a[j];
}
}
return;
}
void randGenArray(int a[], int n)
{
srand(time(NULL));
int i;
for(i=0; i<n; i++){
a[i]=rand()%100;
Sleep(10);
printf("\n>> Integer %d: %d", i+1, a[i]);
}
printf("\n\n\nPress any key to continue...");
getch();
return;
}
void inputArray(int a[], int n)
{
int i;
for(i=0; i<n; i++){
printf("\n Please enter integer %d: ", i+1);
scanf("%d",&a[i]);
}
return;
}
int menu(void)
{
char _char;
printf("\n Please choose one of the following options:\n 1.Fill array manually\n 2.Fill array by random numbers\n\n ");
while(1)
{
_char = getch();
switch(_char)
{
case ESC_KEY:
printf("\n\n Thank you for using our software!\n\n");
exit(0);
case NUM_1_KEY:
system("cls");
return 0;
case NUM_2_KEY:
system("cls");
return 1;
default:
break;
}
}
}
void arrayInit(int *a,int *n, int min, int max)
{
printf("\n Please enter a length of the array: ");
do{
scanf("%d", n);
if (*n<min||*n>max)
printf("\nThe ranged is limited. Please enter the value between %d and %d.\n", min, max);
} while(*n<min||*n>max);
a = (int*)calloc(*n,sizeof(int));
return;
}
void loading(void)
{
printf("\n Loading");
printf(".");
Sleep(300);
printf(".");
Sleep(300);
printf(".");
Sleep(300);
system("cls");
return;
}
void result(int l, int l2)
{
system("cls");
printf("\n Largest = %d Second Largest = %d",l,l2);
Sleep(500);
printf("\n\n\n Thank you using our software! ;D\n\n");
return;
}
But if you cut and paste this line from arrayInit to main and change *n to n - it will work!
a = (int*)calloc(*n,sizeof(int));
I'm sorry for asking about so stupid and obvious things but I didn't figure it out by myself. Thank you for any advice.
Here is a simple program which will show you how to do that -
#include <stdio.h>
#include <stdlib.h>
void create(int **p,int n); // function taking arguments as int ** and n is number of elements
int main(void) {
int *a;
int n=5,i; // declare and initialize n
create(&a,n); // pass address of a to function
for(i=0;i<n;i++){
a[i]=i; // store value of i in a[i]
printf("%d\n",i); // print a[i]
}
free(a); // free the allocated memory
return 0;
}
void create(int **p, int n){
*p=calloc(n,sizeof(int)); // allocate memory to *p (type- is int *)
}
Working Code
You must change your function return type
void * arrayInit(int *n, int min, int max)
{
printf("\n Please enter a length of the array: ");
do{
scanf("%d", n);
if (*n<min||*n>max)
printf("\nThe ranged is limited. Please enter the value between %d and %d.\n", min, max);
} while(*n<min||*n>max);
return calloc(*n,sizeof(int));
}
And call it from main in this way: a = arrayInit(&n, 2, 10);
I have been working on this simple code for hours now, and I have no idea what is wrong! I need to display number of alphabetical letters and the number of decimal digits in standard input. So far I have this:
#include<stdio.h>
#include<ctype.h>
int isalpha(int);
int isdigit (int);
int main()
{
int c;
while((c=getchar())!=EOF)
printf("The number of letters is %d and the number of digits is %d.\n", isalpha(c), isdigit(c));
return 0;
}
int isalpha(int one)
{
int ch;
int i;
i=0;
scanf("%d", &ch);
if(isalpha(ch))
i++;
return i;
}
int isdigit(int two)
{
int a;
int k;
k=0;
scanf("%d", &a);
if(isdigit(a))
k++;
return k;
}
Program crashes whenever I try to run it and I have no clue what part of the code is wrong. Although I don't have much experience in this field yet, so any help is highly appreciated! Thank you in advance.
Just use the existing API's gently and get the count as shown below
int alp = 0;
int dig = 0;
while ((c = getchar()) != EOF)
{
if (isalpha(c)
alp++;
else if (isdigit(c))
dig++;
}
printf("The number of letters is %d and the number of digits is %d.\n", alp,dig);
PS: Take care to flush the newline char if you have \n in the input
The example by recursive call
//gcc -O2 count_alpha_num.c -o count_alpha_num
#include <stdio.h>
#include <ctype.h>
void count_alpha_num(FILE *fp, int *alpha, int *num){
int ch;
if(EOF==(ch=fgetc(fp)))
return ;
if(isalpha(ch))
++*alpha;
else if(isdigit(ch))
++*num;
count_alpha_num(fp, alpha, num);
}
int main(void){
int a_c = 0, n_c = 0;
count_alpha_num(stdin, &a_c, &n_c);
printf("The number of letters is %d and the number of digits is %d.\n", a_c, n_c);
return 0;
}
Examples of Mutually recursive
#include <stdio.h>
#include <ctype.h>
void count_num(int loaded, int ch, int *alpha, int *num);
void count_alpha(int loaded, int ch, int *alpha, int *num){
if(ch==EOF)
return ;
if(isalpha(ch)){
++*alpha;
count_alpha(0, getchar(), alpha, num);
} else {
if(loaded)//Already been inspected by 'count_num'
count_num(0, getchar(), alpha, num);
else
count_num(1, ch, alpha, num);
}
}
void count_num(int loaded, int ch, int *alpha, int *num){
if(ch==EOF)
return ;
if(isdigit(ch)){
++*num;
count_num(0, getchar(), alpha, num);
} else {
if(loaded)
count_alpha(0, getchar(), alpha, num);
else
count_alpha(1, ch, alpha, num);
}
}
int main(void){
int a_c = 0, n_c = 0;
count_alpha(0, getchar(), &a_c, &n_c);
printf("The number of letters is %d and the number of digits is %d.\n", a_c, n_c);
return 0;
}