In this code I'm generate random number in specific range, but I want the out put of array must be
m1,m1,m3,m1 ..
I mean adding the word "host" to every number that is generate randomly, how can do this please?
this is code
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
int a[50];
srand(time(NULL));
a[i] = rand() % (3 + 1 - 1) + 1 ;
printf( " %d\n", a[i]);
}
In your code, ais an integer array, so it cannot hold a string value anyway.
In case, you just want to only print the value, use host in the format string in printf() itself, like
printf( "No. of random selected node = host%d\n", a[i]);
In case, you want the value to be generated and used, in some way, take a buffer and use snprint() to populate the content.
snprint(buf, 8, "host%d", a[i]);
the above will put values like host101, host103 etc. in the buf, as a string. Remember, buf has to be large enough to hold the supplied size (8, in this case.)
Note: Never use magic numbers like 8 in above code, that's just for illustration, use a MACRO definition, at least.
Related
I am currently trying to make a small game in the c programing language for a portfolio. I am new to c so I don't know all of the ticks. Currently, I am trying to assign values to enum's though I don't know if that is correct.
// C program for generating a
// random number in a given range.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "Test.h"
enum mods{
Cha, Str, Dex, Con, Int, Wis // <-this line is the only line that is my code (of this document I have more that will reference this document) the rest I learned from others
};
// Generates and prints 'count' random
// numbers in range [lower, upper].
void printRandoms(int lower, int upper,
int count)
{
int i;
for (i = 0; i < count; i++) {
int num = (rand() %
(upper - lower + 1)) + lower;
printf("%d ", num);
}
}
// Driver code
int main(enum mods Str)
{
int lower = 6, upper = 18, count = 1;
// Use current time as
// seed for random generator
srand(time(0));
printRandoms(lower, upper, count);
printf("My enum Value : %d\n", (int)Str);
return 0;
*edit Sorry for the confusion. I want to be able to reference this product of this line of code over and over again in the main sheet/program. I want it to be a random start so it isn't the same game every time. How do I do that? (for an example of the end product:
if (Str >= 10)
printf("pass skill check to lift the log\n");
else
printf("you drop the log on your foot and take 1d4 damage\n");
enum (health -1d4[will make actual code for this but not yet])
what I need answered
how to make each of the enum mods = a random number at the start of the program to be referenced in the main program
)
If I understood you correctly, you want the mod values to be randomly generated.
Use the enum values as array indices into an array big enough to hold all your mod attributes. Like this, for example:
enum mods = { Cha, Str, Dex, Con, Int, Wis, Mod_Max };
int mod_values[Mod_Max];
Keeping Mod_Max (or whatever you'd like to call it) as the last element of the enum, this will give you simple way to refer to the size of the array. Populating the array with values:
for (int i = 0; i < Mod_Max; i++) {
mod_values[i] = ...;
}
And getting a value of a given "mod" would simply be (for example Str):
mod_values[Str];
EDIT: This way, lets you further modify the mod values down the line, rather than having them as constants
I believe you're asking how to have values for each element in your enum. Well all you have to do is simply assign said value-
enum mods { foo = 77, bar = 42, baz = 3 };
Then you can access said values like so-
enum mods mod_enum = foo;
printf("%d", mod_enum);
The above will print 77
You can also directly use the value of one of the elements from said enum
printf("%d\n", bar);
The above prints 42
Read more about enums
I am currently trying to learn about using pointers and functions together in C, which I don't think is easy.
I am trying to print the last element in an array, it actually does the opposite and prints the first element.
I know people normally use for loops, but I can't figure out how to do that with exactly this kind of problem and therefore I thought that I would try it out with an if statement instead.
Edit:
Why is if statement not working in this case? It seems logic that it should work...
My main.c file:
#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
#define Size 7
int main(void)
{
int array1[] = { 11, 88, 5, 9, 447, 8, 68, 4 };
maxValue(array1, Size);
return 0;
}
My functions.h file:
#pragma once
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
int maxValue(const int *, int);
#endif
My functions.c file:
#include "functions.h"
#include <stdio.h>
#include <stdlib.h>
int maxValue(const int *array1, int Size)
{
int max = array1[0];
if (max < array1[Size]) {
Size++;
max = array1[Size];
}
printf("Max value: %d \n", max);
}
Why is if statement not working in this case? It seems logic that it should work...? Because here
if (max < array1[Size]) { }
Size is defined as 7 and you are comparing array1[0] with array1[7] i.e 11 < 4 -> false, hence it doesn't enter into if block, so the last printf executes and that prints max. But its not a correct logic if if blocks becomes true then further Size++ will cause accessing out of bound array elements which cause undefined behavior.
int maxValue(const int *array1, int Size)
{
int max = array1[0];
if (max < array1[Size]) { /* 11 < 4 false, skips if block */
//Size++; /* this is wrong as Size++ here and next accessing array1[Size] cause UB due to accessing out of bound array element */
max = array1[Size];
}
printf("Max value: %d \n", max); /* max is stills array1[0] i.e 11 */
}
Let's simulate what the CPU does when it enters the maxValue function with those arguments. 1. The variable max is assigned the value of array1[0], which is 11.
2. If max (11) is less than array1[7] (4). It is not, so the if block is not executed.
3. Print max: print 11.
Another thing: Your program causes undefined behaviour. Let's take an example where array1[0] is 3, instead of 11. The if block will be executed (3 < 4), so:
Size is incremented to 8.
max is assigned array1[8]. Since the last index in array1 is 7 (that is how you declared the array), you are accessing a memory adress which you are not supposed to access. This is undefined behaviour.
The names maxValue() and max are misleading and confusing what you are trying to do. lastValue() and last would make much more sense.
However what you are trying to do makes no sense in C because arrays are of known length, so you can access the last element directly:
int array1[] = { 11, 88, 5, 9, 447, 8, 68, 4 };
int array_length = sizeof(array1) / sizeof(*array1) ;
printf("Lastvalue: %d \n", array1[array_length - 1] ) ;
However you cannot do this in a function because arrays are not first class data types in C and when passed to a function will "degrade" to a simple pointer without any information regarding the size of the array pointed to. The calling function having the size information must pass that too (as you have done, but then appeared to get very confused):
void printLast( int* array, int length )
{
printf( "Lastvalue: %d \n", array1[length - 1] ) ;
}
It is difficult to see why you thought you might need any other code or what your maxValue() function is intended to achieve. The "logic" which you say "should work" is thus:
If value of the first array element is less than the value of the last array element, then print the undefined value one past the end of the array; otherwise print the first element of the array.
If you wanted to print the last element, then you simply print it, the value of the first element has nothing to do do with it. Either way you should not index past the end of the array - that value is undefined.
This question already has answers here:
Pointer to string changes its value unexpectedly
(4 answers)
Closed 4 years ago.
I would like to create an array in C and then assign to every value in that array the string "[ ]".
This is what I have in mind:
char Array[N];
for(int i = 0; i < N; i++)
{
Array[i]="[ ]";
}
What is the correct approach to doing that?
Bellow is a sample working code you customize to your taste:
#include<stdio.h>
#include<string.h> // for strcpy: use to copy one string into another
// set a symbolic constant
#define N 10
int main(int argc, char **argv)
{
// declare the array
char Array[N][4]; // 4, because "[ ]" is 3+1 long
for(int i=0; i < N; i++){
strcpy(Array[i], "[ ]");
}
// print out the content for test purpose
for(int i=0; i < N; i++){
printf("Array[%d] = %s\n", i, Array[i]);
}
return 0;
}
This question already has an accepted solution but I'd like to provide a bit more context that will help people who are used to higher-level languages like Java and C++ understand why these steps are needed when writing this algorithm in C vs. in a newer language.
For starters, not every C compiler will allow you to create an array with a size determined by a variable (this is called a Variable Length Array, or VLA--you can read more about them here: How do I declare a variable sized array in C?). Unfortunately you can't even declare a const variable for the number of terms you want in your array (read more about that here: Can a const variable be used to declare the size of an array in C?). So that's why you're stuck typing the literals everywhere in the program or using preprocessor commands like I've demonstrated.
Next, the length of a char array in C is the number of chars it can hold. However, since each of your terms is 3 characters long plus the null character at the end you need the array to be 4 times longer than the number of terms. You can use two See the code below for how to declare this.
Finally, you need to #include the string.h header file in order to be able to work with strings in C.
#include <stdio.h>
#include <string.h>
int main(){
#define N_TERMS 6
#define L_TERM 4
char term[L_TERM] = "[ ]";
char Array[N_TERMS * L_TERM] = ""; //array should be the size of the product of number of terms and length of term
for(int i = 0; i < N_TERMS; i++){
strcat(Array, term); //strcat adds the second string to the end of the first
}
printf("%s", Array); //prints the entire string
return 0;
}
A char is one character. Which would be in single quotes not double quotes. "[ ]" is three character. [, the space and ] are together three characters. Each index in a char array can only hold one character at a time, so the [ or the space or the ] or some other character.
Hi I have made a very simple program that should work but it don't:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(int argc, char *argv[]) {
int usedNumbers[256];
memset(usedNumbers,0,256);
srand(time(NULL));
for(int i=0; i<256; ++i){
while(1){
int r = rand()%256;
if( !usedNumbers[r] ){
usedNumbers[r] = 1;
break;
}
printf("Test: %03d -> %03d\n", i, r);
}
}
return 0;
}
The idea of the program is to print numbers from 0 to 255 on the screen in the random order but the program stops on 84th number on 32 computers and 144th number on 64 bit computers. If i only move the "int usedNumbers[256];" above the function like that:
#include <string.h>
int usedNumbers[256];
int main(int argc, char *argv[]) {
Program works as it supposed to.
Why is it that?
I am using the newest GNU/GCC compiler and C11 standard.
The usedNumbers inside main is a local variable and these are not zero-initialized (i.e. they can contain garbage). Since you only use memset(..., 256), only the first 256 bytes are zero-initialized, and the rest (e.g. half or three quarters of the array -- or more, depending on the size of int) is not.
The usedNumbers outside main is a global variable, however, and these are completely zero-initialized, even without memset. So there, you really have an empty array with no garbage in it, and that is why that works as expected.
So do:
memset(usedNumbers, 0, sizeof(usedNumbers));
and both versions should produce the same, expected result.
Write a program that will create an integer array with 1000 entries. After creating the array, initialize all of the values in the array to 0. Next, using the rand function, loop through the array and save a random number between 1 and 10 (inclusive) in each entry of the array.
This is for my homework due tomorrow but I need some help with it since I'm barely a beginner at code.
This is the only code I've made so far with single dimensional arrays
#include <stdio.h>
#include <stdlib.h>
int mean(int array[], int size);
int main()
{
int i;
int array[5]={5, 1, 3, 2, 4};
for (i=0; i<5; i++)
{
printf("%d", array[i]);
}
printf("\nThe mean is %d", mean(array,5));
return 0;
}
int mean(int array[], int size)
{
int i, sum = 0;
for (i=0; i<5; i++)
{
sum=sum + array[i];
}
return sum/5;
}
Not sure why you wrote a program to calculate the mean, given that there's nothing in the requirements about that.
However, you just have to think about the steps. Note that the following example do not perfectly match what you need, they're there just to show you the method, not to be cut and pasted into your assignment.
First, you can create an array of size (for example) seven with the statement:
int value[7];
You can then set all elements to a given value with:
for (size_t idx = 0; idx < sizeof(value) / sizeof(*value); idx++)
value[idx] = 42;
(although, at the level of your assignment, it's probably better to use 7 rather than the sizeof expression).
In order to generate random numbers, you first include the requisite header and, as the first thing in main(), set the seed to something "random":
#include <stdlib.h>
#include <time.h>
:
srand (time (0));
Then, at the time when you need to generate a random number from one to fifty inclusive, you can use:
int rnum = rand() % 50 + 1;
(keeping in mind the distribution won't be perfect but it should be more than good enough for the intended purpose here).
Whatever loop you chose above to initialise the array elements to 42 (or zero) can also be used to set them to random values.
That should be enough to get you started.