I am a new person on stackoverflow. I have stuck in a problem when I try to make a program with C language that will print out a maximum element in an one-dimensional array by using functions. I decided print out my element in in many ways. I have try to put "printf" in the "checkmax" fuction, in "main" function and make a function
"printmax" just for print my elements but none of these ways seem like work well.I need some helps.
int checkmax(int a[], int n)
{
int max=a[0];
for(i=0;i<n;i++);
{
if(a[i]>max) max=a[i];
}
return max;
//printf("max = %d", max);
}
/*void printmax()
{
if(checkmax(a,n)==max) printf("max = %d", max)
}*/
int main()
{
int n;
printf("Enter number of elements => ");
scanf("%d",&n);
int *a=(int*)calloc(n,sizeof(int));
inputarray(a,n);
checkmax(a,n);
//printf("max = %d", max);
getchar(); getchar();
}
You have i undeclared in the for loop.
Also this for(i=0;i<n;i++); means that you have an empty for loop because of the semicolon at the end. If you fix these you should be fine.
e.g.
for(int i=0;i<n;i++) {
if(a[i]>max) max=a[i];
}
There are a few errors we should address.
First, you are trying to use local variables as global ones. E.g. trying to use max in printmax() when it was defined locally in checkmax().
Second, your for loop does nothing due to the semicolon at the end. Also make sure to do int i = 0 instead of i = 0, since i was not declared before entering the loop.
Third, if you are getting errors from calling printf(), you should make sure that you included stdio.h at the top of your file: #include <stdio.h>
(the printf() in checkmax() also needs to be before return max;)
Solution:
Remove the declaration of max, a, and n in their functions, and instead declare them at the top of your file,
#include <stdio.h>
int max = 0, n = 0;
int a[] = {0};
...
fix the for loop,
for(int i = 0; i < n; i++){
...
}
and remove printmax(). The function is useless, since you print max in checkmax().
Related
I've started learning C. I'm doing functions right now.
In these exercise they want me to ask for a value that means an error. If they input the number 8, it means that it's error "8", if value 6 error is "6"(the error part don't matter). I should call a fuction to store this error and other functio to go trought it and see if any value ("error"), Was stored more than once.
I started by asking for how many errors the user will introduce, soo I could run a loop "N" times to ask for the value.
Then I made a function called aviso(means warning ~ error), to store them in a array.
When the function reaches the last value of "error" it calls other function to count if the numbers are repeated .
My main problem right now is how to store the values in the array and keeping them. Every time I introduce a value in the array it happear other like: array[0] = 7 the output is like array[0] = -32134123.
So my function is not storing any value in the array.
My code is very messy right now, please any suggestions are welcome since I'm clearly very new at C.
Excuse my code I just "try" to translate some names to english.
`
#include <stdio.h>
#include <stdlib.h>
// Function Incomplete since my array is not sotring values
int alertwarning(int array[]){
for(int i = 0; i < sizeof(array)/sizeof(int); i++){
}
}
int warning(int num , int n, int count){
int check = count - 1 , array[n];
if(count <= n){
array[check] = num;
}
if(count == n){
alertwarning(array);
for(int i = 0; i < sizeof(array)/sizeof(int); i++){
}
}
return 0;
}
int main(int argc, char *argv[]) {
int num, count, n;
printf("|Warning System!|(Only values equal or above 0 are acepted!)\n");
printf("\nIntroduce how many warnings are being stored: ");
scanf("%d", &n);
fflush(stdin);
int array[n];
do{
printf("\nIntroduce a value equal or bigger then 0: ");
scanf("%d", &num);
fflush(stdin);
//system("cls");
if(num < 0){
printf("|Please introduce a valuer equal or above 0!|\n");
system("pause");
}
else if(num >= 0){
count++;
}
warning(num, n, count);
}while( count < n);
return 0;
}
`
I tried to store the array inside the main() and it worked but it was required to do it in other function to complete this exercise. I don't know if the function just don't save the values of the last time it was called.
how to store the values in the array and keeping them. Every time I introduce a value in the array it happear other like: array[0] = 7 the output is like array[0] = -32134123.
So my function is not storing any value in the array.
I tried printf to see where I go wrong with the few knowledge I own. When they are called they work but the next time they are called I think they reset the values of the array.
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)];
This a dot_product function of 2 vectors of the same length.
I don't understand how to build the array because how the machine will know which input goes to which input (for example i want a={1,2,3} but the input of 123 will come a[0]= 123)...
How do I make end of array[index] input and how do I make end of the whole array.
#include <stdio.h>
#include <stdlib.h>
#define MAXINPUT 100
int dot_product(int v[], int u[], int n)
{
int result = 0;
int i;
for (i=0; i < n; i++)
result += v[i]*u[i];
return result;
}
int main(){
int v1[MAXINPUT];
int v2[MAXINPUT];
int count = 0
int i,print;
printf(" first vector:");
for(i=0;i<MAXINPUT;i++){
scanf("%d", &v1[i]);
count +=1;
}
printf(" second vector:");
for(i=0;i<MAXINPUT;i++)
scanf("%d", &v2[i]);
print = dot_product(v1, v2, count);
printf("v1*v2:%d",print);
return 0;
}
The first problem I observe here is with
count +=1;
where count is an uninitialized automatic local variable, which makes it's initial value indeterminate. Attempt to use that value invokes undefined behavior.
You should be initializing count to 0.
That said, here, you're depending on the user to input the second array with exact same dimension of that of the first one. In case that does not happen, your program will blow up, as you did not initialize the arrays, again.
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 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.