Understanding Random Number Generation and String I/O in C Programming
60 likes | 178 Vues
This chapter explores random number generation and string input/output functions in C programming, as taught in ECE 103 at PSU. It covers essential library functions, such as `srand()` and `printf()`, which are crucial for manipulating random numbers and strings. Learn how to use `char *` pointers to handle strings and utilize formatting in outputs. Examples demonstrate the functionality, including generating random integers, formatting strings, and outputting to the console or storing in character arrays.
Understanding Random Number Generation and String I/O in C Programming
E N D
Presentation Transcript
ECE 103 Engineering ProgrammingChapter 51Random Numbers Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed by Professor Phillip Wong @ PSU ECE
Syllabus • srand() • sand()
Random Number Generator C has library functions to input and output strings. Use #include <stdio.h> In the following table, char * is a pointer to a character array that contains a string. RNG Functions 2
String I/O Functions C has library functions to input and output strings. Use #include <stdio.h> In the following table, char * is a pointer to a character array that contains a string. String I/O Functions 3
srand intprintf (const char * format, …) Writes formatted output to the console. Use the %s format specifier for strings. %s expects the address of a char array which contains a string. Example: char name[] = "Jane Doe"; printf("[%s]\n", name); →[Jane Doe] printf("[%s]\n", &name[0]); →[Jane Doe] printf("[%s]\n", &name[5]); →[Doe] 4
rand intsprintf (char * s, constchar * format, …) Performs a formatted print and saves it to a string. Works like printf except the output is stored in string s. Nothing is printed to the console. Example: char str[50]; intx = 4; sprintf(str,"x=%d y=%f", x, 1.5f); printf("title = %s\n", str); 5