[Week 7] Programming Basics 6
[Week 7] Programming Basics 6
Generation
Rand function
Example
i = rand();
i = rand() % 100;
Simulating a dice
- Use the scaling factor of 6.
- Shift the range of numbers produced by adding 1.
face = rand() % 6 + 1;
Rolling a Six-Sided Die
A simple program that prints out 20 numbers in the range of [1, 6].
- We can see a warning without the stdlib header.
- Different scaling factors and shifts will be tested.
#include <stdio.h>
#include <stdlib.h>
int main() {
for (int i = 0; i < 20; i++)
printf("%d ", 1 + rand() % 6);
printf("\n");
return 0;
}
Randomizing the Random Number Generator
- When debugging a program, this repeatability is essential for proving that corrections to
a program work properly.
With different sequences of random numbers, every execution will have a different result which
make it very hard to correct errors.
srand(time(NULL));
- To randomize without entering a seed each time
- This make the program to use the current time, which will be differed on every execution.
- The function time is defined in time.h.
Rolling a Six-Sided Die 2
A simple program that prints out 20 numbers in the range of [1, 6].
- Random sequence on each execution.
- We can set a specific seed for srand function for debugging purposes.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
for (int i = 0; i < 20; i++)
printf("%d ", 1 + rand() % 6);
printf("\n");
return 0;
}
getchar and puts
Characters
Characters can be stored in any integer data type because they’re usually represented as
one-byte integers in the computer.
- Although they are normally stored in variables of type char, ...
Thus, we can treat a character as either an integer or a character, depending on its use.
When assigning a character literal to an integer variable, 'promotion' happens regarding the
data type.
- From 1 byte to 4 bytes
The getchar function (from <stdio.h>) reads one character from the keyboard and returns as
an int the character that the user entered.
- Syntax: int getchar ( void );
- getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.
- Considering the promotion issue, it is recommended to assign the returned values of this function to
an integer type variable.
#include <stdio.h>
int main() {
int c = 'a';
printf("%c\n", c);
c = getchar();
printf("The character (%c) has the value %d.\n", c, c);
return 0;
}
Reading Character Input
#include <stdio.h>
This program counts the number of 'a' from
the user input.
- The parenthesized assignment (c = getchar())
int main()
{
executes first.
int c;
int num_of_a = 0;
- In the program, the value of the assignment c =
while( (c = getchar()) != EOF ) { getchar() is compared with the value of EOF
if(c == 'a') { (a symbol whose acronym stands for “end of file”).
num_of_a++;
} - We use EOF (which normally has the value -1) as the
} sentinel value.
printf("The number of 'a' is %d.\n",
num_of_a);
return 0;
}
Reading Character Input
#include <stdio.h>
This program counts the number of 'a' from
the user input.
- End-of-file (EOF): A system-dependent keystroke
int main()
{
combination to mean "end of file"—i.e., “I have no
int c;
more data to enter.”
int num_of_a = 0;
while( (c = getchar()) != EOF ) { - If the value entered by the user is equal to EOF, the
if(c == 'a') { while loop terminates.
num_of_a++;
} - The variable c is declared as int because EOF has an
} integer value (normally -1).
printf("The number of 'a' is %d.\n",
num_of_a);
return 0;
}
Entering the EOF Indicator
- This notation <Ctrl> d means to press the Enter key then simultaneously press both Ctrl and d.
On other systems, such as Microsoft Windows, the EOF indicator can be entered by typing
<Ctrl> z
This program counts the number of 'a' from the user input.
- What happens when we use 'char' data type for the variable c? Is it OK?
- Check the difference when we use '\n' Instead of EOF. (Ex: Counting the number of '\n'.)
#include <stdio.h>
int main() {
int c;
int num_of_a = 0;
while( (c = getchar()) != EOF ) {
if(c == 'a') { num_of_a++; }
}
printf("The number of 'a' is %d.\n", num_of_a);
return 0;
}
puts
Function puts takes a string as an argument and displays the string followed by
a newline character.
- Syntax: int puts ( const char * str );
- Similar to printf but only for C string
C string can be printed out using printf function with a conversion specifier '%s'.
- %s: a conversion specifier for string data
- You can use '%s' with C strings or variables with string data.
#include <stdio.h>
int main() {
printf("Hi, this statement is using printf\n");
puts("Hi, I'm using puts instead of printf"); // Check that puts is without \n.
return 0;
}
Exercise: ASCII Printer for characters
#include <stdio.h>
int main() {
int c;
/* Fill in here */
return 0;
}
Exercise: ASCII Printer for characters
int main() {
int c;
while( (c = getchar()) != EOF) {
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
printf("Character: %c, ASCII value: %d\n", c, c);
}
}
return 0;
}
Conditional Operator
Conditional Operator
C provides the conditional operator (?:) which is closely related to the if…else statement.
The conditional operator is C’s only ternary operator—it takes three operands.
- The first operand is a condition.
- The second operand is the value for the entire conditional expression if the condition is true.
- The third operand is the value for the entire conditional expression if the condition is false.
(condition)? (value for the true case):(value for the false case)
Conditional Operator
The puts statement performs in essentially the same way as the preceding
if...else statement.
Conditional Operator
The second and third operands in a conditional expression can also be actions to be
executed.
#include <stdio.h>
int main() {
int num;
scanf("%d", &num);
num%2? printf("Odd\n"):printf("Even\n"); // or, printf(num%2? "Odd\n":"Even\n");
// or, if(num % 2) { printf("Odd\n"); }
else { printf("Even\n"); }
return 0;
}
Formatting Floating-
Point Numbers
Formatting Floating-Point Numbers
The conversion specifier %21.2f is used to print the value of the variable amount.
- The 21 in the conversion specifier denotes the field width in which the value will be printed.
- The 2 specifies the precision (i.e., the number of decimal positions).
- Input: 4 - Input: 12
i !
1 1
i ! 3 6
1 1 5 120
3 6 7 5040
9 362880
11 39916800
Exercise: Printing Factorials of odd numbers in Tabular Form
Skeleton Code
#include <stdio.h>
printf("%d", i);
int main() { if(i >= 10) {
int input; printf(" ");
scanf("%d",&input); } else {
printf("i !\n"); printf(" ");
}
for(int i = 1; i <= input; i++) { printf("%d\n", temp);
if(i % 2 != 0) { }
int temp = 1; }
for(int j = 1; j <= i; j++) { return 0;
temp *= j; }
}
Exercise: Printing Factorials of odd numbers in Tabular Form
Solution
#include <stdio.h>
int main() {
int input;
printf("%-6d%d\n", i, fact);
scanf("%d",&input);
}
printf("i !\n");
}