[Week 5] Programming Basics 4
[Week 5] Programming Basics 4
int main()
{
int number = 0;
printf("Input a number: ");
scanf("%d", &number);
printf("\n");
}
▪ In C, Boolean is a data type that can hold true or false.
Used for only those two values.
_Bool or bool in stdbool.h are supported but not commonly used.
since C99
Zero is used for false and any non-zero values are accepted as true.
▪ Example:
The two conditions are evaluated first not the && operator.
Precedences of == and >= are both higher than the precedence of &&.
seniorFemale increases by one only when gender is 1 and age is greater than or equal to 65.
Both conditions must be true for execution of the body.
(||)
▪ A binary operator that checks whether either or both operands are TRUE
▪ Example:
The message will be printed out with at least one true condition.
||
▪ Boolean expressions in C
Expressions with relational operators, equality operators, and/or logical operators.
They are evaluated to one (true) or zero (false) in C.
▪ Short-circuit evaluation
The program control stops evaluating conditions with && or || when the result of
the combined condition is determined.
▪ Side-effects of short-circuit evaluation will be shown
#include <stdio.h>
int main()
{
int a = 0, b = 0;
return 0;
}
▪ A unary operator used for reversing the condition
True → False, False → True
if (!(grade == sentinelValue))
//if (grade != sentinelValue) // The same meaning
printf("The next grade is %f\n", grade);
This if statement contains two simple conditions. The condition gender == 1 might be
evaluated, for example, to determine if a person is a female. The condition age >= 65 is
evaluated to determine whether a person is a senior citizen. The two simple conditions
are evaluated first because the precedences of == and >= are both higher than the
precedence of &&. The if statement then considers the combined condition 'gender == 1
&& age >= 65' which is true if and only if both of the simple conditions are true. Finally, if
this combined condition is true, then the count of seniorFemales is incremented by 1. If
either or both of the simple conditions are false, then the program skips the
incrementing and proceeds to the statement following the if.
▪ Logical OR (||) Operator
Now let’s consider the || (logical OR) operator. Suppose we wish to ensure at some point
in a program that either or both of two conditions are true before we choose a certain
path of execution. In this case, we use the || operator as in the following program segment.
The message “Student grade is A” is not printed only when both of the simple conditions are
false (zero). The if statement considers the combined condition 'semesterAverage >= 90 ||
finalExam >= 90' and awards the student an “A” if either or both of the simple conditions are
true.
▪ Short-circuit evaluation
The && operator has a higher precedence than ||. Both operators associate from left to
right. An expression containing && or || operators is evaluated only until truth or
falsehood is known. Thus, evaluation of the condition 'gender == 1 && age >= 65' will stop
if gender is not equal to 1 (i.e., the entire expression is false), and continue if gender is
equal to 1 (i.e., the entire expression could still be true if age >= 65).
This performance feature for the evaluation of logical AND and logical OR expressions is
called short-circuit evaluation.
▪ Logical Negation (!) Operator
C provides ! (logical negation) to enable you to “reverse” the meaning of a condition.
The logical negation operator has only a single condition as an operand (and is therefore
a unary operator).
Placed before a condition when we’re interested in choosing a path of execution if the
original condition (without the logical negation operator) is false, such as in the following
program segment:
if (!(grade == sentinelValue))
printf("The next grade is %f\n", grade);
In most cases, you can avoid using logical negation by expressing the condition differently
with an appropriate relational operator. For example, the preceding condition may also be
written as 'grade != sentinelValue'.
▪ Most computer programs that solve real-world problems are much larger
than the programs we have seen.
f(x) = ax2+bx+c
▪ Inputs and Outputs
▪ Function definition = header + body
▪ Return type
The type of a return value
Return value: a value written after the return keyword
You can specify only one return type.
▪ Function name
Name for calling the function (should be a any valid identifier)
Recommendation: Follow the popular coding style. (Ex: Google Coding Style)
int square(int number) // Header
{
return number * number; // Body
}
▪ Parameter list
shows information that the function expects to receive from the caller.
A parameter consists of a type and a parameter name.
The same as a declaration of a variable without initialization.
There can be multiple parameters.
ex) int PrintNum(int number1, int number2)
int square(int number) // Header
{
return number * number; // Body
}
void print_hello(void)
{
printf("hello\n");
return; // can be omitted
}
void print_hello()
Receives nothing and returns nothing
int main()
Receives nothing and returns an integer
int main(void)
Receives void???
void
… (You can make use of the function square after the prototype)
The functions printf and scanf that we’ve learned are standard library functions.
You can write your own functions to define tasks that may be used at many points in a
program. These are sometimes referred to as programmer-defined functions. The
statements defining the function are written only once, and the statements are hidden
from other functions. Functions are invoked by a function call, which specifies the
function name and provides information (as arguments) that the called function needs to
perform its designated task.
▪ Modularizing Programs in C
A common analogy for this is the hierarchical form of management. A boss (the calling
function or caller) asks a worker (the called function) to perform a task and report back
when the task is done. For example, a function needing to display information on the
screen calls the worker function printf to perform that task, then printf displays the
information and reports back—or returns—to the calling function when its task is
completed. The boss function does not know how the worker function performs its
designated tasks.
▪ Compilation Errors
A function call that does not match the function prototype causes a compilation error.
An error is also generated if the function prototype and the function definition disagree.
For example, if the function prototype had been written as
, the compiler would generate an error because the void return type in the function
prototype would differ from the int return type in the function header.
▪ To call a function, specify the function name with proper parameters.
▪ Return value usage: You can store it to a variable or discard it after using.
at caller
avg:1.6
at callee
a:1.1, b:2.1
double average(double a, double b)
at callee {
ret: 1.6 double ret = (a+b)/2;
return ret;
}
at caller
double x = 1.1, y = 2.1;
double avg = average(x, y); x:1.1, y:2.1
at caller
avg:1.5
at callee
(Implicit type casting, here.
Technically, coercion of arguments)
a:1, b:2
double average(int a, int b)
at callee {
ret: 1.5 double ret = (a+b)/2.0;
return ret;
}
▪ Check the control flow with a function call
Variations with differed types will be shown.
#include <stdio.h>
double avg(int x, int y) {
return (x + y)/2.0;
}
int main() {
int num1, num2;
printf("Input two numbers(ex: 1 2): ");
scanf("%d %d", &num1, &num2);
printf("Average of %d and %d is %f.\n", num1, num2, avg(num1, num2));
return 0;
}
▪ Local Variables
Most of variables you are using and will use are locally valid.
The term ‘locally’ usually and roughly means inside of a block.
int main(void)
int main(void)
{
{
{ int i; }
int i;
{ int i; } // OK
int i; // ERROR
i=1; // ERROR
}
}
at callee
a:1.1, b:2.1
double avg()
{
return (num1 + num2)/2.0;
}
int main()
{
int num1, num2;
return 0;
}
▪ Divisor War is a simple game that a number with more divisors wins the game.
Make a program that receives two integers and shows the results of Divisor War
game.
#include <stdio.h>
return count;
}
▪ Divisor War (continued)
int main()
{
int number1 = 0, number2 = 0;
int count1 = 0, count2 = 0;
printf("Input a number1: ");
scanf("%d", &number1);
printf("Input a number2: ");
scanf("%d", &number2);
count1 = GetNumberOfDivisors(number1);
count2 = GetNumberOfDivisors(number2);
printf("\n");