Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Archived:Random value generation in Open C

From Wiki
Jump to: navigation, search

Archived.pngArchived: This article is archived because it is not considered relevant for third-party developers creating commercial solutions today. If you think this article is still relevant, let us know by adding the template {{ReviewForRemovalFromArchive|user=~~~~|write your reason here}}.

Article Metadata
Tested with
Devices(s): Nokia N93
CompatibilityPlatform Security
Signing Required: Self-Signed
Capabilities: None
Article
Keywords: srand(), rand()
Created: nymanaki (03 Apr 2008)
Last edited: hamishwillee (06 Aug 2012)

Contents

Overview

Random value generation in Open C applications can be done with functions called srand() and rand(). Function srand() sets its argument seed as the seed for a new sequence of pseudo-random numbers. Sequences are repeatable by calling srand() with the same seed value. Function srand() needs to be called only once in a program and this should be done before the first call to rand().

Note: In order to use this code, you need to install the Open C plug-in.

MMP file

The following libraries are required:

LIBRARY libc.lib

Source file

#include <stdio.h>   //printf
#include <stdlib.h> //srand, rand
#include <time.h> //time
 
int LOWER_BOUND = 1;
int UPPER_BOUND = 6;
 
int main (void)
{
int index = 0;
int random_number = 0;
char random_letter = ' ';
time_t now;
 
/* get current time from the system clock */
time(&now);
 
/* set seed for a new sequence of pseudo-random numbers */
srand((unsigned int) now);
 
/* loop 10 rounds to generate different numbers/letters */
for(index = 1; index <= 10; index++)
{
printf("round:%d\n", index);
 
/* get random number between 1 and 6 */
random_number = rand() % (UPPER_BOUND - LOWER_BOUND + 1) + LOWER_BOUND;
printf("random number:[%d]\n", random_number);
 
/* get random character (lowercase letters in the ASCII) */
random_letter = 'a' + rand() % 26;
printf("random letter:[%c]\n", random_letter);
 
printf("- - -\n");
}
 
return 0;
}

Postconditions

10 random numbers (1-6) and 10 lowercase ASCII characters are displayed to standard output.


This page was last modified on 6 August 2012, at 05:00.
58 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×