So there is this project in Data Structures that i have to deal with this semester and it requires that i have to code in C . The problem is that i am a little bit rusty in C and i am dealing with basic problems. One of the problems is that i have to write a simple program in C that implements BubbleSort . The BubbleSort algorithm has to be a seperate function and call it in the main program . Here is my effort . The problem is that it doesnt type the sorted array . I hope you can help me .
THE CODE :
int calculateRand()
{
int num;
num = (rand())%(UPPER-LOWER+1)+LOWER;
return num;
}
void swap(int *xp, int *yp)
{
int temp=*xp;
*xp=*yp;
*yp=temp;
}
void BubbleSort(int S[], int n)
{
int up=n;
int i,j;
while(up>1)
{
j=0;
for(i=1; i<up-1; i++)
{
if(S[i]>S[i+1])
{
swap(&S[i], &S[i+1]);
j++;
}
}
}
for(i=0; i<n; i++)
{
printf("%d\n", S[i]);
}
}
int main()
{
int n,i;
printf("Parakalw dwste mia timh sto n: \n");
scanf("%d", &n);
int S[sizeof(n)];
printf("O mi taxinomimenos pinakas einai o exis \n");
for(i=0; i<n-1; i++)
{
S[i]=calculateRand();
printf("%d\n", S[i]);
}
printf("O pinakas meta thn taxinomisi einai \n");
BubbleSort(S[sizeof(n)], n);
return 0;
}
So if we start from the top there is a problem in the calculateRand() function as you do not declare the UPPER and LOWER variables or pass them as parameters to function.
Swap function is ok.
In the BubbleSort() function you need to decrease the up variable value after the for loop.
while(up>1)
{
for(i=1; i<up-1; i++)
{
if(S[i]>S[i+1])
{
swap(&S[i], &S[i+1]);
j++;
}
}
up--;
}
Also at this point you should start iterating from 0 instead of 1 since arrays start from index 0. So for(i=0; i<up-1; i++) is the correct way to go.
Lastly in the main() function when you're declaring the array variable S you shouldn't pass the sizeof(n) since n is an integer and size of an integer is 4. Instead you want to use n as it is int S[n];
For loop to populate the array should go up to n not n-1 if you want to fill all elements of the array. However if you change this you'll need to make the similar change in the BubbleSort() function.
And finally in the BubbleSort() function call you are passing the last element of the array which is an integer whereas function expects you to pass an array. It should look like this BubbleSort(S, n); instead.
sizeof(n) has nothing to do with the value of the variable n. It's the the size of the variable n, i.e. mostly 4 bytes for the modern architectures.
Modern variants of C permit variable size arrays thus
int S[n];
would have been legit. Otherwise
int *S = (int *)malloc(n*sizeof(int));
will help.
When you call BubbleSort , your argument should be S not S[sizeof(n)];
Related
I've written a function to rotate an array,
I've checked and it works when code is in one block I.E. everything
is coded under main(), but when I divide the code so that the rotation is done under a different function I can't get it to work (it truncates instead of rotating).
I'm pretty sure it's something to do with the array pointer.
sorry complete noob
please help:
#include<stdio.h>
void rotate(int *arr,int length);
int main()
{
// this code creates an array via input
int length;
int i;
int num;
printf("enter length of array\n");
scanf("%d",&length);
int arr[length];
for (i=0;i<length;i++) {
printf("enter number\n");
scanf("%d",&num);
arr[i]=num;
}
// just prints original
for(i=0;i<length;i++){
printf("original arr[%d]=%d\n",i,arr[i]);
}
//runs rotate function
rotate(arr,length);
return 0;
}
//the rotate function inputs rotation amount and uses nested for loop to
execute
void rotate(int *arr,int length)
{
int n;
printf("by how many do you want to rotate array?");
scanf("%d",&n);
int i;
int j;
int temp;
for (j=0;j<n;j++)
{
temp=arr[0];
for (i=0;i<length-1;i++)
{
arr[i]=arr[i+1];
}
arr[length-1]=temp;
printf("rotated arr[%d] = %d\n",i,arr[i]);
}
}
my output looks like this:
enter length of array
5
enter number
1
enter number
2
enter number
3
enter number
4
enter number
5
original arr[0]=1
original arr[1]=2
original arr[2]=3
original arr[3]=4
original arr[4]=5
by how many do you want to rotate array?
3
rotated arr[4] = 1
rotated arr[4] = 2
rotated arr[4] = 3
RUN FINISHED; exit value 0; real time: 9s; user: 0ms; system: 0ms
In C you need to declare the function before "main" function, or do the declaration and definition both above the main function. Also do share your error message, for help.
Also, in C language you can't really create dynamic arrays like that( i.e. taking an integer value and then defining the size of array using it "int array[integer] " is wrong of doing it, if the value of integer is being given during runtime)
Read http://www.mathcs.emory.edu/~cheung/Courses/255/Syllabus/2-C-adv-data/dyn-array.html , or any other tutorial about dynamic arrays in C and how to use malloc and calloc.
According to me the problem is in your last print statement in rotate method which is inside the loop.
you must loop through the whole array again to print the rotated array.
like this.
void rotate(int *arr,int length)
{
int n;
printf("by how many do you want to rotate array?");
scanf("%d",&n);
int i;
int j;
int temp;
for (j=0;j<n;j++)
{
temp=arr[0];
for (i=0;i<length-1;i++)
{
arr[i]=arr[i+1];
}
arr[length-1]=temp;
}
for(i=0;i<length;i++){
printf("original arr[%d]=%d\n",i,arr[i]);
}
}
this will work.
And also, Always define functions at the top in c.
So, I have this code which I need to turn into a function:
int main(void) {
int i=0,seed;
printf("\n\nEnter seed integer value: ");
scanf("%d", &seed);
printf("\nSeed value is:%d\n\n",seed);
srand(seed);
int a[5][5];
int x,y;
printf("Matrix A:\n");
for(x=0;x<5;x++) {
for(y=0;y<5;y++) {
a[x][y] = rand() %51 + (-25);
printf("%d ",a[x][y]); }
printf("\n"); }
printf("\n\n");
So basically, it produces a 2D 5x5 array of random numbers. This works fine, however my next task is applying a function to this code, with the function name of:
void generate_matrices(int a[5][5])
I have tried multiple times, the closest I got to a successful code was:
#include <stdio.h>
#include <stdlib.h>
void generate_matrices(int a[5][5]);
int main(void) {
int a, seed;
printf("\n\nEnter seed integer value: ");
scanf("%d", &seed);
srand(seed);
printf("\nSeed value is:%d\n\n",seed);
generate_matrices(a);
return 0;
}
void generate_matrices(int a[5][5]) {
int y,z;
printf("Matrix A:\n");
for(y=0;y<5;y++) {
for(z=0;z<5;z++) {
a[y][z] = rand() %51 + (-25); }
printf("%d ",a[y][z]); }
printf("\n");
}
But this returns the error, "expected 'int(*)[5]' but arguement is of type 'int'.
All/any help is muchly appreciated. To be fair on my part, I have done 90% of the code. This is the only bit I need help with so that I can apply this to the rest of my code.
Cheers!
You have declared a as a single integer on this line int a, seed;
When you call the function with generate_matrices(a); you are passing a single integer instead of a pointer to an array.
Change your declaration line to int a[5][5], seed;
generate_matrices(a); will pass a pointer to the first element in your 5 * 5 array, to the function.
You should really print the results in main and not in the function, then you will know that the array has been modified and is available for use in the body of your program.
You have used unconventional placement of braces '}' and this makes it harder to see what belongs in each part of your for loops.
You have the print statements in the wrong places - as a result only part of the matrix is printed.
This is what it should be (just the results - in main):
printf("Matrix\n ");
for (y = 0; y < 5; y++) {
for (z = 0; z < 5; z++) {
printf("%d\t ", a[y][z]);
}
printf("\n");
}
If you use int a[5][5] and call the function with generate_matrices(a);
a function void generate_matrices(int a[5][5]) {...} compiles without error
#include<stdio.h>
#include<stdlib.h>
void modify(int b[5][5]);
int main()
{
srand(4562);
int i,j,arr[5][5];
modify(arr);
for(i=0;i<5;i++){
for(j=0;j<5;j++){
printf("%d ",arr[i][j]=rand() %51 + (-26)); }
}
return 0;
}
void modify(int b[5][5])
{
int i,j;
for(i=0;i<5;i++) {
for(j=0;j<5;j++) {
b[i][j]; }
}
}
So this is the closest I have come to completing it. It produces the number of elements I want, also within the range I want. However its not producing the 5x5 grid I need. Where have I gone wrong?
EDIT: I'm not going for neatness at the moment, I just want to get the program working how I want it too and then i'll neaten it up.
EDIT 2: Never mind, realised what I didn't include. Its fine now. Thanks for the help.
I cant seem to find out where i'm going wrong in C. its on line 37 it says assignment to expression with array type any help or advice would be great thanks.
I was wondering also is it something to do with not adding in the brackets to show that they're arrays on line 37 but when i put them in it displays more errors
/*
This program uses pass by reference to calculate the values after two arrays are multiplied by each other
16/02/2015
Jake Young
*/
#include <stdio.h>
#define size 5
//Prototype
int multiply_function(int *[], int *[]);
main()
{
int array1[size];
int array2[size];
int i;
int answer[size];
//get users input for array1
printf("Please enter %d values into array1:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array1[i]);
}//end for loop
//get users input for array2
printf("Please enter %d values into array2:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array2[i]);
}//end for loop
//call function()
answer=multiply_function(&array1, &array2); // line 37
//Print out the results from array1 multiplied by array2
printf("Array1 multiplied by Array2 is the following:\n");
for(i=0; i<size; i++)
{
printf("%d multiplied by %d is %d\n", array1[i], array2[i], answer[i]);
}//end for loop
}//end main()
multiply_function(int *array1[], int *array2[])
{
int *answer[size];
int i;
for(i=0; i<size; i++)
{
//calculate multiplication
*answer[i]= *array1[i]* *array2[i];
}//end for loop
return(*answer);
}//end function()
int multiply_function(int *[], int *[]);
This doesn't make any sense. You intend to pass arrays of integers to the function, not arrays of pointers. You'll have to study how arrays should be passed to functions.
main()
This form is not standard. Unless you are programming a "bare metal" embedded system, you should use int main (void).
answer=multiply_function(&array1, &array2);
This doesn't make any sense. You declared the function to return an int. Again, study how arrays are passed to and from a function. Furthermore, you can't copy arrays with the assignment operator: you have to use memcpy() or similar functions.
multiply_function(int *array1[], int *array2[])
The function definition is different than the prototype: that is always bad practice. Apart from that, the function doesn't make any sense, as already mentioned.
int *answer[size];
This doesn't make any sense, you are declaring an array of pointers where you want an array of integers.
return(*answer);
Returning a pointer to a local variable in C is always a bug. And you can't return arrays like this. And there is no need for the parenthesis.
OK, you should really invest some more time to study arrays, pointers and fundamentals of functions in C.
Apart from grammatical problems in the code, the fundamental problem in this code is the answer[] array. it is defined both in main() and the multiply_function(). What you must do is to pass this array to the multiply_function() and have the function fill in the array.
I'm giving the solution below, with the hope that you'll compare it to your version and study the differences and continue to learn the basics of C:
#include <stdio.h>
#define size 5
//Prototype
int multiply_function(int *, int *, int *);
main()
{
int array1[size];
int array2[size];
int i;
int answer[size];
//get users input for array1
printf("Please enter %d values into array1:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array1[i]);
}//end for loop
//get users input for array2
printf("Please enter %d values into array2:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array2[i]);
}//end for loop
//call function()
multiply_function(array1, array2, answer);
//Print out the results from array1 multiplied by array2
printf("Array1 multiplied by Array2 is the following:\n");
for(i=0; i<size; i++)
{
printf("%d multiplied by %d is %d\n", array1[i], array2[i], answer[i]);
}//end for loop
}//end main()
multiply_function(int *array1, int *array2, int *answer)
{
int i;
for(i=0; i<size; i++)
{
//calculate multiplication
answer[i]= array1[i] * array2[i];
}//end for loop
return(*answer);
}//end function()
I want to make a program that uses a function I created where it swaps all the elements of an array X (that has the length of N) with some number K, only if that element is greater than K. Where am I going wrong here?
#include <stdio.h>
#include <stdlib.h>
int swap_K(int *, int);
int main()
{
int N,i,K;
printf("Enter N: ");
scanf("%d",&N);
printf("Enter K: ");
scanf("%d",&K);
int X[N];
for (i=1; i<=sizeof(X)/sizeof(int); i++){
printf("Enter %d. element: ",i);
scanf("%d",&X[i]);
}
swap_K(X,K);
for (i=1; i<=sizeof(X)/sizeof(int); i++){
printf("%d",X[i]);
}
}
int swap_K(int *X, int K)
{
int i;
for (i=1; i<=sizeof(X)/sizeof(int); i++){
if (X[i]>K)
X[i]=K;
}
return X;
}
In swap_K(int *X, int K), sizeof(X) is sizeof(int *), not the size of the array.
In C, a pointer is not really the same as an array.
To fix it, use N instead of sizeof(X)/sizeof(int) everywhere, esp. inside swap_K().
1) Arrays start with index 0.
2) In your main function you don't need to use sizeof(X)/sizeof(int) in for loop as you already know it is equal to N.
3) When you pass the array to the function, you are sending the base address of the array which decays into pointer, so in swap_K function, sizeof(X) will return sizeof(int) which is 4(generally).
To overcome this you should send the size of your array from main function. For example: swap_K(X,K,N);
4) You don't need to return X from swap_K as you are sending the base address of X from main function.
For example:
#include <stdio.h>
#include <stdlib.h>
int swap_K(int *, int, int);
int main()
{
int N,i,K;
printf("Enter N: ");
scanf("%d",&N);
printf("Enter K: ");
scanf("%d",&K);
int X[N];
for (i=0; i<N; i++)
{
printf("Enter %d. element: ",i);
scanf("%d",&X[i]);
}
swap_K(X,K,N);
for (i=0; i<N; i++)
{
printf("%d",X[i]);
}
}
int swap_K(int *X, int K,int N)
{
int i;
for (i=0; i<N; i++)
{
if (X[i]>K)
X[i]=K;
}
//return X; //This is not required
}
Your loop is incorrect
for (i=1; i<=sizeof(X)/sizeof(int); i++)
It should be
for (i=0; i<N; i++)
There are several problems with the code posted:
arrays in C are 0-indexed, so the for loops should ALWAYS iterate from 0 to N - 1. Iterating past N is a buffer overflow
the pointer to the array is just the pointer to the first element of the array. The swap function can't know if the pointer passed to it is part of an array or a single value. With this in mind it will need to take another argument which tells what is the size of the passed in array as pointer. Iteration inside the loop will use that value instead of sizeof(X) / sizeof(int) = 1
you're defining X as a variable sized array which is allocated entirely on the stack. Introducing a reasonably large N will crash your program. It would be better to allocate the array in the heap if you don't know what the size of the input will be.
I have been asked to write a lottery program in c++ not sure if i am using function correctly please help
//function prototypes
int myNumbers();
void displayNums();
#include <stdio.h>
#define NUMS 6
#define WIN 7
// function myNumbers takes input from user
int myNumbers(int numbers[]) //implememt function
{
int i;
int numbers;
int input[NUMS];
printf ("Please enter your lucky numbers\n");
for (i=0;i<NUMS;i++)//loop through array to take input
{
scanf("%d",&input[i]);
}//end for loop
return (numbers);
}//end function myNumbers
Each of your functions declares a new array, rather than using the array passed to it as an argument.
void displayNums(int print[])
{
int i;
int output;
int numbers[NUMS];
output = myNumbers(numbers);
printf("Your numbers are %d \n", output);
}
Note that nowhere is the print argument used, and you're using int numbers[NUMS] instead. Remove that declaration and use print. (Also please consider naming your argument something other than print; this name is confusing and does not accurately describe what the variable stores.)
you are not using arrays properly to communicate the numbers, see the function
int myNumbers(int userPick[]) //implememt function
{
int i;
int numbers;
int input[NUMS];
printf ("Please enter your lucky numbers\n");
for (i=0;i<NUMS;i++)//loop through array to take input
{
scanf("%d",&input[i]);
}//end for loop
numbers = *(input+i);
return (numbers);
}//end function myNumbers
it reads the number to a local array and returns *(input+i) which will be a random number since your read array is from input+0 to input+i-1. you should pass array or pointer to global array.
Even in case of display() function you are passing one array and using some other array inside display() function.
you should use a common array to communicate values. you can create a array in global scope and use it in all functions or create a array in main() and pass pointer to it to other functions and use the same array in other functions. learn how to pass arrays between functions and use arrays
Your functions looks erroneous:
int myNumbers(int userPick[]) // 1. userPick is not used anywhere
{
int i;
int numbers; // 2. initialize this variable to 1 first
int input[NUMS];
printf ("Please enter your lucky numbers\n");
for (i=0;i<NUMS;i++)
{
scanf("%d",&input[i]);
}//end for loop
numbers = *(input+i); // 3. is this suppose to be inside the loop ?
return (numbers);
}//end function myNumbers
And in
void displayNums(int print[])//implement function
{
int i;
int output;
int numbers[NUMS];
output = myNumbers(numbers);
printf("Your numbers are %d \n",output);
}//end function displayNums
You don't use print but create a new array numbers
Most of your code is erroneous. It won't compile. Here's some sample code. Work with it to implement the rest
#include <stdio.h>
#define NUMS 6
void displayNums(int nums[])
{
int i;
printf("Your numbers are:\n");
for(i = 0; i < NUMS; i++)
printf("%d ", nums[i]);
printf("\n");
}
void myNumbers(int nums[])
{
printf("Please Enter your lucky numbers\n");
int i;
for(i = 0; i < NUMS; i++)
scanf("%d", &nums[i]);
}
int main()
{
int numbers[6];
myNumbers(numbers);
displaynums(numbers);
//do the rest of the stuff here
return 0;
}
Going through a C tutorial might be helpful? Check out http://c.learncodethehardway.org/book/ for a nice intro to the language.