Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
79 views

C Programming

The document provides an overview of 7 lectures on C programming language topics including inputs, data types, selection, repetition, procedures and functions, arrays, and text files. It then provides details on the first lecture which covers variables, operators, input/output using console applications. Key points include declaring variables, using assignment and arithmetic operators, taking user input with scanf, and printing output with printf. Examples are given of simple programs demonstrating these basic concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

C Programming

The document provides an overview of 7 lectures on C programming language topics including inputs, data types, selection, repetition, procedures and functions, arrays, and text files. It then provides details on the first lecture which covers variables, operators, input/output using console applications. Key points include declaring variables, using assignment and arithmetic operators, taking user input with scanf, and printing output with printf. Examples are given of simple programs demonstrating these basic concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

C programming language

Lecture 1(Tuesday 16-06-2020): Inputs, assignment and output.

Lecture 2 (Wednesday 17-06-2020): Data types

Lecture 3 (Thursday 18-06-2020): Selection

Lecture 4 (Friday 19-06-2020): Repetition

Lecture 5 (Saturday 20-06-2020): Procedures and functions

Lecture 6 (Sunday 21-06-2020): Arrays

Lecture 7 (Monday 22-06-2020): Text files and files of records.

Day 1

Programming in C

Lecture 1: Input, assignment and output

Content

•Variables

•Operators in C

•Input and output using a console application

•Summary

•You learned about algorithms is csc207. We now consider how to translate an algorithm into
programs using a high-level programming language.

•Programming is a skill like playing a musical instrument or playing a sport. The more you practice,
the better you will become. Use the worked examples in this course and try out the constructs by
building by building them into an application. You can use your imagination and expand the
examples. You will learn a lot by making small changes and seeing their effect.

Variables

•When you solve a problem, you identify the inputs and outputs and determine the variables. You
can imagine a variable as a box. Each box can usually store one value. Naming a variable is like
labeling the box. When you label a box you write on the outside of the box a description of what you
store in the box. When you name a variable, you should choose a meaningful name that describes
what the variable is going to be used for. This variable name is known as the variable’s identifier.
•Programming languages have rules about what is a valid identifier. They usually allow combination
of alphanumeric characters (letters, numerals, and the underscore character) but no spaces or other
symbols. Usually, identifiers must start with a letter. Some languages are case sensitive e.g. C.

•You should follow generally accepted naming conventions for choosing identifiers so that your
program code can be easily understood by other programmers. Avoid using keywords as identifiers.
Concatenate – join them together – to describe the purpose of a variable and use casing to indicate
the meaning of each word. For example, numberOfEntries (Camel case). There are two type of camel
case: upper and lower camel case in upper camel case, the letter of each word start with a capital
letter while in lower camel case the letter of first word start with a small letter and the following
words start with capital letters.

•Don’t use single letter variable identifiers unless this is really appropriate, but there is no need to
have a variable identifier of more than 20 characters. Choose sensible that will read easily in your
program code.

Operators in C

1) The assignment operator

•To assign a value to a variable, we use an assignment statement. Here is an example to assign the
value 7 to a variable with identifier number1.

number1 = 7;

“C requires a semicolon as a statement separator”

•The value on the right of the assignment operator (=) is stored in the variable named on the left of
the assignment operator. You should read this as ‘number1 becomes equal to 7’.

•Although it is possible to write more than one statement on one line, this is not recommended, as it
makes your program more difficult to understand and maintain.

•Assignment can consist of an expression, a formula, to the right of the assignment operator. This
expression is evaluated when the statement is executed and the value is then stored in the variable
named on the left of the assignment operator.

•If number1 contains the value 7 and number2 contains the value 12, when the following statements
are executed, sum will contain the value 19:

sum = number1 + number2;

•Suppose count contains the value 5, then after this statement has been executed, count will contain
the value 6. You can read this statement as ‘increment count by 1’.

count = count + 1;

Arithmetic operators:
•In C we can perform arithmetic operations by combining the following operators

Operation
 Addition

Arithmetic operator ; +

Example

number1 + number2;

 Subtraction

Arithmetic operator ; -

Example

number1 - number2;

 Multiplication

Arithmetic operator; *

Example

number1 * number2;

 Division

Arithmetic operator; /

Example

number1 / number2;

Modular arithematics:

• Normal division returns a result that might not be a whole number, but sometimes we are
interested in the whole number part only. This is known as integer division. Integer division of 17 by
5 gives the result 3.

• The modulo operation gives the remainder after a division. For example the remainder of 17
divided by 5 is 2.

Example of integer division:

int wholeNumberPartnumber1;

wholeNumberPartnumber1 = number1 / number2;

Example of modulo operation:

remainder = number1 % number2;


•C provides a shorthand way to apply an arithmetic operator on a single variable e.g.

x = x * 5;

OR

x *= 5;

•This trick works with all the five basic arithmetic operators. C provides a further shorthand for
incrementing or decrementing a variable by 1.

x++;

x--;

Comments

•It is good programming practice to add comments to source code that explains the purpose of a
statement or set of statements. These comments are ignored by the compiler. Symbols used to
enclose comments which may go over several lines

/* comments go

Here */

Symbols to denote that the rest of the line is a comment

// comments go here

// and again

// if you need more than one line

 Questions to test your understanding of this section

Using the C programming language and sensible variable identifiers, write assignment statements to
calculate the following values:

1.The number of questions answered wrongly so far in a quiz.

2.The percentage of questions answered correctly from those attempted.

3.The percentage of questions attempted out of the total number of questions in the quiz.

4.How many 5000 FCFA notes you will get for an amount of money in FCFA stored in a variable
amount.
Proposed Solutions

q1 numberOfWrongAnswers = numberOfQuestionsTried - numberOfCorrectAnswers;

q2 percentageCorrect = numberOfCorrectAnwers / numberOfQuestionsTried * 100;

q3 percentageTried := numberOfQuestionsTried / totalNumberOfQuestions * 100;

q4 numberOf5ThousandsNotes = Amount / 5;

in q4 you have to make sure numberOf5ThousandsNotes is an integer by declaring (to be seen) as

 int numberOf5ThousandsNotes;

Input and output using a console application


Console application:

•When you first start a console application, the programming environment provides you with a
framework where you type your program statements.

•A console application is a program that runs in a text based window into which the user types and
which displays text output from the computer.

Input from the keyboard

scanf("%d", &number1);

%d is the format specifier

parameters of scanf are each separates by a comma

 When the above statement is executed, the program will pause and wait for input from the
keyboard until the enter key is pressed.

•Other examples:

1) int x,y,z;

scanf("%d%d%d", &x, &y, &z);

2) float y;
Int x;

Scanf(("%f%d",&y, &x);

3) int day, month, year;


scanf("%d/%d/%d", &day, &month, &year);

Output to the console

1-To display a string; Example

printf("hello, world!");

2-To display the content of a variable Example

printf("%d", number1);

3-To display a string and then move the output stream to the next line Example

printf("hello, world!\n");

OR

puts("hello, world!");

4-To display the content of a variable and then move the output stream to the next line Example

printf("%d\", number1);

5-To move the output stream to a new lineExample

printf("\n"); OR

puts("");

A simple console application

#include <stdio.h>

int main(void) /* void is a type that means nothing*/

printf("hello, world\n");

return 0;

•In C, the function to print something to the screen is printf, where f stands for “format”, meaning
we can format the string in different ways. Then, we use parentheses to pass in what we want to
print. We use double quotes to surround our text, or string, and add a \n which indicates a new line
on the screen. (Then, the next time we call printf, our text will be on a new line. Finally, we add a
semicolon ; to end this line of code in C.

•Here is how to combine strings and contents of variables into one output stream.

printf("%d + %d = %d\n", number1, number2, sum);


•Assume number1 contain the value 7, number2 contain the value 12, sum contain the value 19.
When the above statements are executed, the console will display

7 + 12 = 19

Declaring and using variables

•C is a strongly typed language i.e. it requires that the datatype of a variable should be declared
before it can be assigned values or before they can be used. This is a desirable feature of a language
as the compiler will check that the operations are performed on correct variable type. In C variables
are declared as follows: type variable identifier

•Example

double number1, number2, sum, average;

int max = 5;

•The datatype is followed by a list of variable identifiers. You can assign an initial value at declaration
time.

A simple console application using variables

#include <stdio.h>

int main(void)

float number1, number2, sum, average;

printf("First number: ");

scanf("%f", &number1);

printf("Second number: ");

scanf("%f", &number2);

sum = number1 + number2 ;

average = sum / 2;

printf("Their sum is: %4.2f \n", sum);

printf("Their average is: %4.2f \n", average);

return 0;

• The number %4.2f formats the real numbers to be displayed using digits with two digits after
the decimal point. If you don’t include this a real number will be displayed in scientific format.
Sequencing instructions

•The calculation 4 * 7 + 3 gives a different result to the calculation 4 *(7 + 3), because the brackets
change the order of evaluation. Similarly, the order in which program statements are executed
affects the outcome. When programming with imperative languages, the statements are executed in
the sequence the programmer determines. Values need to be assigned to variables before the can be
used in calculations, and calculations need to be done before results can be displayed.

Summary of what we have learned today

In this lesson you have covered

•How to write the code to calculate the result of a formula.

•How to write the code to read input from the keyboard and produce output to the screen.

•How to declare variable types

•The importance of the sequence of instructions.

Assignment: Questions

Write programs to do the following:

1.Display the word 'Hello World' on the screen.

2.Display two messages of your choice on the screen, separated by an empty line.

3.Display the sum and average of three numbers entered at the keyboard.

4.Read in two integers and display how many times the first integer divides the second integer.
Display the remainder from this division.

5.The user enters an amount of money as a whole number. The program should calculate and display
how many 2000frs, 1000frs and 500frs notes and 100frs and 50frs are needed to make up this
amount of money. For example 3750frs would give 1x2000frs, 1x1000frs, 1x500frs and 2x100frs,
0x50frs.

Lecture 2: Data types

Content of today's lesson

• Variable declarations

• Constant definitions

• Build-in data types

• User-defined data types


• Logical bitwise operators

• Summary

Lecture 2: Data types

All data is stored and process as a sequence of bit patterns. We need to declare the type of the data
values we want to use so that the processor operates on them correctly. For example, we may wish
to store whole numbers (integers), text (strings) or numbers with fractional parts (real numbers). The
compiler allocates memory space according to the data we want to store. For example, integers may
be stored using four consecutive bytes. Programming languages have common data types build in.
You may wish to declare your own data types.

Solution to question 4 assignment above

#include<stdio.h>

int main(){

int number1, number2, whole, remainder;

printf("Please type in a number: ");

scanf("%d",&number1);

printf("Please type in another number: ");

scanf("%d",&number2);

whole = number1 / number2;

remainder = number1 % number2;

printf("%d / %d = %d Remainder = %d", number1, number1, whole, remainder);

return 0;

Variable declaration

Global variable

•These are variables declared at the public section of a program and accessible from everywhere in
the program. It is not always desirable to use a global variable as its values may get changed
accidentally.

Local variable

•A variable declared in a program block and accessible only within the program block.
•Rather than declaring variables globally, it is good programming style to declare variables locally
within the block where the variable is going to be used.

•When you start writing programs with routines – procedures or functions – you should declare local
variables within the routines. Any variable value that is required by another routine should be passed
as a parameter. A routine or subroutine is a subprogram.

Constant definition

•A constant is a value that does not change throughout the program. It is good programming style to
declare named constants. Don’t use variables because you might change their value by accident. If
you choose a meaningful identifier to label a constant value then your program will be much easier
to understand and maintain.

•Imagine you are writing a mathematical program where you require the value of pi. You know that
pi is approximately equal to 3.1416. If you use wherever required in your program, but later want to
calculate it with more accuracy, then you need to change the value throughout. If you declare pi as a
named constant and initialize its value at the beginning of your program, you only need to change it
in the one place where it is declared.

•It is much more meaningful to see an instruction such as

circumference = radius * 2 * pi. Rather than, circumference = radius * 2 * 3.1416.

How to declare constants in C

1) Using #define Example #define pi 3.14159

NB: define can be placed anywhere in your program but it is good programming practice to place
them before your main function.

2) Using the const keyword Examples const int count = 100;

const float pi = 3.14159;

Remark: If your program tries to modify a constant variable, the compiler will generate an error.

Worked Example

Problem: Write a program that inputs the radius of a circle and outputs its diameter, circumference
and area. pi should be declared as a constant variable with the value 3.14159

Solution:

#include <stdio.h>

const float pi = 3.14159;

int main(void)

{
float radius, diameter, circumference, area;

printf("Input the radius ");

scanf(("%f", &radius);

diameter = 2*radius;

circumference = 2*pi*radius;

area = pi*radius*radius;

printf("Diameter: %.2f\n", diameter);

printf("Circumference: %.2f\n", circumference);

printf("Area: %.2f\n", Area);

return 0;

Build-in data types

1) Whole numbers

 Build-in types: int

Description: The int data type is used for variables that will store integers i.e. signed 32 bits integers

Conversion Specifier: %d

Byte required: 4 bytes

Range: -2^31 to 2^31-1

NB: The conversion specifier is used in scanf and printf when outputting or inputting values of this
type

 Build-in types: unsigned int

Description: Unsigned is a qualifier that you can be applied to certain types (including int), which
effectively doubles the positive range of variables of that type, at the cost of disallowing any negative
values

Conversion Specifier: %d

Byte required: 4 bytes

Range: 0 to 2^32-1

Remark: Unsigned is not the only qualifier that we might see for variable data types. There are also
short and long and const.
 Build-in data types:
2) Real numbers

Description: Real numbers are numbers with a decimal point and a fractional part, such as
19.124578654. C supports a variety of real number types

 Build-in types: float

Description: The float data type is used for variables that will store floating-point values also known
as $real numbers$.

Conversion Specifier: %f

Byte required: 4 bytes

 Build-in types: double

Description: The float data type is used for variables that will store floating-point values also known
as real numbers. The difference is that doubles are double precision. They always take up 8 bytes of
memory.

Conversion Specifier: %f

Byte required: 8 bytes

Remark: With an additional 32 bits of precision relative to a float, doubles allow us to specify much
more precise real numbers.

Question from student in worked out example: Pls sir why %.2f not%4.2f

Answer from teacher: %.2f means we want to represent the results with any number of digits, but
with just 2 digits after the decimal point. %4.2f means we want the results to have 4 digits with 2
after the decimal point.

 Build-in data types


3) Characters and strings
 Build-in types: char

Description: A variable of this type stores a single ASCII character e.g. symbol = '&';

Conversion Specifier: %c

Byte required: 1 bytes

Range: -128 to 128

Remark:

•The string data type is used for a variable that will store a series of characters, which programmers
typically call string.
•Strings include things such as words, sentences, paragraphs, and the likes.

•There is no string data type in C, but arrays of characters of characters can be used as a
replacement.

•C’s conversion specifier for strings is %s

Worked Example:

#include <stdio.h>

int main(void)

char name[20];

printf("Please input your name: ");

scanf(("%f", name); // OR gets(name);

printf("Hello %s\n", name);

return 0;

Build-in data types

4) Boolean data type

•The Boolean data type is used for variables that will store a Boolean value. More precisely, they are
capable only of storing one of two values: true or false.

•There is no build in Boolean data type in C, but 0 is false and any other integer value is true.

#include <stdio.h>

int main(void)

int value;

printf("Input a value: ");

scanf("%f", &value);

if(value){

printf("The number inputted is different from zero");

} else {
printf("The number inputted is zero ");

return 0;

Build-in data types

5) void data type

•It’s a type but not a data type.

•Functions can have a void which just mean they don’t return a value.

•The parameter list of a function can also be void. It simply means the function takes no parameter.

•For now, think of void as a placeholder for “nothing”

Questions to check your understanding

1-in what variable type will you best store the following values?

a.A person’s age.

b.A person’s weight in kilograms.

c.The radius of a circle.

d.The cost of an item.

e.The gender of a student.

f.The name of a country.( hint: the name of a country is a sequence of characters, hence string.
Which is an array of characters in C)?

2-Determine appropriate variable names for the values in 1) above.

3-Write declarations for the variables in 2) above.

User-defined data types

Sometimes we want to work with types that are not build into the programming language we are
using. We can declare our own types. A type needs to be defined before we can declare variables of
that type.

Question; Ok sir in naming the variable s types is the range considered somehow? Ok sir in naming
the variable s types is the range considered somehow?

Answer; Yeah It really depends on the problem you are solving. If you will store very large values,
then using a type or a qualifier that can enable you do that will be good.
User-defined data types

1) Records

•A record is a data structure that groups together a number of variables, which need not be of the
same type and have no associated ordering. The variables of a record are called fields.

•To use a records, we declare the structure as a type, then we declare variables of that type.

•To work with individual fields of a record, we use the dot notation: recordVariableName.fieldName

•You can declare arrays of records and fields of records.

Worked Example:

#include <stdio.h>

typedef struct

char name[20];

char gender;

int level;

float height;

} tstudent;

int main(void)

tstudent aboutStudent;

printf("Input student’s name: ");

gets(aboutStudent.name);

printf("Input student’s gender: ");

scanf("%c", &aboutStudent.gender);

printf("Input student’s level: ");

scanf("%d", &aboutStudent.level);

printf("Input student’s height: ");

scanf("%d", &aboutStudent.height);

return 0; }
Remark:

•name , gender, level and height are the fields of the record type tstudent

•typedef is the keyword used to define new datatypes in C.

Note: aboutStudent is a record of type tstudent

User-defined data types

2) Enumerated types

•An enumerated type defines an ordered set of values. Each value is given an ordinal value, starting
from zero. Members of an enumerated type can be used as loop control variables, in case statements
and as array subscripts.

Worked Example 1:

#include <stdio.h>

typedef enum{sun, mon, tues, wed, thu, fri, sad} tdays;

int main(void)

tdays day1, day2;

day1 = wed;

day2 = sun;

printf("Wednesday = %d ", day1);

printf("Sunday = %d ", day2);

return 0;

Worked Example 2:

#include <stdio.h>

typedef enum{false, true} bool;

int main(void)

bool finished;

finished = true;
return 0;

Remark: enumerated types can be used in a loop (to be seen in another lesson)

Logical bitwise operator:

•Sometimes we may want to manipulate individual bits in a bit pattern. In the following examples, a
contains 13(00001101 in binary) and b contains 17 (00010001 in binary).s

Operator: NOT a

Operator in c: ~a

*Result: 11110010

Explanation: The not operator inverts each bit of a, so each 0 becomes 1 and 1 becomes 0

Operator: a AND b

Operator in c: a & b

*Result: 00000001

Explanation: The operator sets a bit to 1 if the corresponding bit in a and b are both 1, otherwise it
sets it to 0.

Operator: a OR b

Operator in c: a | b

*Result: 00011101

Explanation: The or operator sets a bit to 1 if either of the corresponding bits in a and b are 1,
otherwise it is set to 0

Operator: a XOR b

Operator in c: a ^ b

*Result: 00011100

Explanation: The xor operator sets a bit to 1 if only one of the corresponding bits in a and b is 1
otherwise it is set to 0.

Summary:

In this lesson you have covered


•Global variables: declared at the beginning or public section of a program. Accessible from
anywhere in the program.

•Local variables: declared in a program, accessible only within that program.

•Constants: values that do not change throughout a program.

•Build-in data types: integer, byte, real, Boolean, character and string.

•User-defined data types: records, and enumerated types.

•Logical bitwise operatore. NOT, AND, OR, XOR.

Question: sir, at one point you used scanf and at another you used gets. Are they exactly the same
when applied?

Answer: gets and puts are good when you are dealing with strings, especially when you suspect
user input will have spaces. printf doesn't work well with spaces in data of type string.

Answer for assignment above question 5 :

#include<stdio.h>

int main(){

int amount, remainder, twoThousands, oneThousands, fiveHundreds, hundreds, fifties;

printf("Please enter a sum of money as a whole number: ");

scanf("%d",&amount);

twoThousands = amount / 2000;

remainder = amount % 2000;

oneThousands = remainder / 1000;

remainder = remainder % 1000;

fiveHundreds = remainder / 500;

remainder = remainder % 500;

hundreds = remainder / 100;

remainder = remainder % 100;

fifties = remainder / 50;

remainder = remainder % 50;

printf("For %d FCFA you need the following:\n", amount);

printf(" %d X 2000 FCFA\n", twoThousands);


printf(“ %d X 1000 FCFA\n", oneThousands);

printf(" %d X 500 FCFA\n", fiveHundreds);

printf(" %d X 100 FCFA\n", hundreds);

printf(" %d X 50FCFA\n", fifties);

return 0;

Lecture 3: Selection

Content of today's lesson

•Boolean Expressions

•Simple if statements

•if-then-else statement

•Nested if statement

•Switch statement

•Summary

Conditional expressions allow your program to make decisions and take different forks (paths) in the
road, depending on the values of variables or user input. C provides a few different ways to
implement conditional expressions (also known as branches) in your program.

Boolean Expressions

1) Relational operators

•Expressions with relational (comparison) operators are known as Boolean expressions. When a
Boolean expression is evaluated, it returns a Boolean value, True or False.

In C

Equal to ==

Less than <

Greater than >


Not equal to !=

Less than or equal to <=

Greater than or equal to >=

2) Boolean operators

•More complex Boolean expressions can be formed using Boolean operators, or logical operators:
NOT, AND, OR.

Description: Number equal to 1

Mathematics: Number = 1

In C: Number == 1

Description: Number not equal to 1

Mathematics: Number ≠ 1

In C: Number != 1

Description: Age 17 or under

Mathematics: Age ≤ 17

In C: Age <= 17

Description: Age 17 or more but less than 25

Mathematics: 17 ≤ Age <25

In C: (Age >= 17) && (Age < 25)

Description: Age under 21 or over 65

Mathematics: Age < 21 OR Age > 65

In C: (Age < 21) || (Age > 65)

Questions to evaluate your understanding

Write programs to evaluate these Boolean expressions

1-Number is equal to zero.


2-Number is non-zero.

3-Number is less than or equal to zero.

4-Number is between 1 and 20 exclusive.

5-Number is between 1 and 20 inclusive.

6-Number is either between 1 and 10 or between 100 and 120 exclusive.

Note: | and & are bitwise or and and respectively (check the last lesson on datatypes), while ||
and && are logical or and and respectively. In other words | and & operate on the bits 1 and 0,
while || and && operate on the Boolean values true and false.

Simple if statement

•The basic structure of a simple if statement in C is (Syntax):

if (boolean-expression)

•If boolean-expression evaluates to true, all lines of code between the curly braces will execute in
order from top-to-bottom.

•If *boolean-expression evaluates to false, those lines of code will not execute.

•The simple if statement is used when we want to execute a statement or group of statements only
if a certain condition is met.

Consider the following program (age.c):

/**

* age.c

* Tell you things that you are old enough to do depending on your age

*/

#include <stdio.h>

int main(){

int age;
printf("How old are you? ");

scanf("%d",&age);

if(age >= 3)

printf("You don't need diapers\n");

system("pause");

return 0;

The program age.c was given by the lecturer

Activity:

1. Compile the code and run it. The code asks for your age. Depending on how old you are, it will
tell you things that you are old enough to do.Currently, it only does the first message. Your task is to
make the code

print out the rest:

If you are 3 or older than "you don't need diapers"

If you are 16 or older than "you can drive"

If you are 17 or older than "you can see an R rated movie"

If you are 18 or older than "you can vote"

If you are 21 or older than "you can gamble"

If you are 25 or older than "you can rent a car"

If you are 50 or older than "you can retire"

2. If the age is less than 3, make the code tell you:

"Sorry, you are not old enough for anything yet"

3. If the age is equal to 0, make the code tell you:

"Welcome to the world!"

Note the solution of Activity was given by teacher and titled ageSolution.c

Questions 1.11

Write programs to do the following:

1-Display a message if two numbers read from the keyboard are the same.
2-Display a message if the first of two numbers read from the keyboard is greater than the second.

If-then-else statement

•The basic structure of a simple if-then-else statement in C is (Syntax):

if (boolean-expression)

else

•If boolean-expression evaluates to true, all lines of code between the first set of curly braces will
execute in order from top-to-bottom.

•If boolean-expression evaluates to false, all lines of code between the second set of curly braces will
execute in order from top-to-bottom.

•When we want to execute a statement or group of statements if a certain condition is met, but
another group of statements if the condition is not met, we can use the if-then-else statement.

•In the example below, we want to decide whether to turn on the airconditioner or turn it off,
according to the entered room temperature:

Worked Example: Air-Conditioner Program(acp.c)

#include <stdio.h>

int main(void)

int temp;

// Prompt user for integer

printf("Please enter temperature of this room: ");

scanf("%d", &temp);

// Check if temperature is above 22

if (temp > 22)


{

printf("Please turn on air-conditioner\n");

else

printf("Please turn off air-conditioner\n");

return 0;

Question(1.11) 2 is different from question 1 i.e. I expected two programs from you.

See acp.c before proceeding

•In this example: if the temperature is greater than 22, then display the first sentence: Please turn
on air-conditioner

•else, if the condition is not met (less than or equal to 22) , then display this line: Please turn off air-
conditioner

Nested if statements

•A statement in the in the then part or the else part of an if statement may also be an if statement. It
is possible to extern the if statement to handle multiple conditions.

•The basic structure of a simple if-then-else statement in C is (Syntax):

if (boolean-expr1)

// first branch

else if(boolean-expr2)

// second branch

else if(boolean-expr3)
{

// third branch

else

// fourth branch

•As you would expect, each branch is mutually exclusive i.e. you can only ever go down one of the
branch.

Worked Example: Air-Conditioner Program(acp2.c)

#include <stdio.h>

int main(void)

int temp;

// Prompt user for integer

printf("Please enter temperature of this room: ");

scanf("%d", &temp);

// Check if temperature is above 22

if (temp > 22)

printf("Please turn on air-conditioner\n");

else if (temp < 18)

printf("Turn off air-conditioner\n");

}
else

printf("Do nothing\n");

return 0;

Questions:

Write a program that ask for three numbers to be typed in at the keyboard, then display the largest
one.

Switch statement

•C’s switch() is a conditional statement that permits enumeration of discrete cases, instead of relying
on Boolean expressions.

•Nested if statements can get very cumbersome and sometimes a switch() is preferable. a switch()
statement presents a list of options that the variable may match. As long as there is no match,
control skips to the next option. When a match is found, the associated statements are executed.

•The Restaurant program will illustrate the use of the switch of statement:

Worked Example: Restaurant Program (restaurand.c)

#include <stdio.h>

int main(void)

int meal;

// Prompt user for integer

printf("Welcome to the C Restaurand\n");

printf("1 - Chicken (5000frs)\n");

printf("2 - Fish (700frs)\n");

printf("3 - Meat (800frs)\n");


printf("4 - Salad (200frs)\n");

printf("5 - Orange Juice (100frs)\n");

printf("6 - Milk (100frs)\n");

printf("Please enter your selection: ");

scanf("%d", &meal);

switch (meal)

case 1:

printf("You have ordered Chicken, this will take 15 minutes\n");

break;

case 2:

printf("You have ordered Fish, this will take 12 minutes\n");

break;

case 3:

printf("You have ordered Meat, this will take 18 minutes\n");

break;

case 4:

printf("You have ordered Salad, this will take 5 minutes\n");

break;

case 5:

printf("You have ordered Orange Juice, this will take 2 minutes\n");

break;

case 6:

printf("You have ordered Milk, this will take 1 minutes\n");

break;

default:

printf("Wrong Entry\n");
}

return 0;

Note: It’s important to break; between each case, or you will “fall through” each case unless that is
desired behavior.

?: statement

int x;

if (expr)

x = 5;

else

x = 6;

int x;

x = (expr) ? 5 : 6;

•These two snippet of code act identically.

•The tenary operator (?: ) is mostly a cute trick, but is useful for writing trivially short conditional
branches. Be familiar with it, but know that you won’t need to write it if you don’t want to.

Summary

in this lesson you have covered

•Writing Boolean expressions using relational and Boolean operators.

•How to code a simple if statement.

•How to code an if-then-else statement.

•How to code a nested if statement.


•How to code a switch if statement.

•How to code a ?: statement.

Questions

Write programs to do the following:

1-Ask the user for a month number, then display the name of the month; for example, the input 9
should produce a display of September.

2-Ask the user for a year, then display whether that year is a leap year. Hint: use the modulo
operator.

3-Ask the user for a month number, then display the number of days in that month. For example, the
input 9 should display 30.

4-Ask the user for a month number and a year then display the number of days in that month, taking
into account leap years.

5-Input a hexadecimal number numeral then display the decimal equivalent.

Lecture 4

The lecture was given by lecturer and titled Lecture 4 Repetition.pdf and it also had source code file
titled src4.rar.

Lecture 5

The lecture was given by lecturer and titled Lecture 5 procedures and functions.pdf and it also had
source code file titled src5.rar.

Lecture6

The lecture was given by lecturer and titled Lecture 6 Arrays.pdf and it also had source code file
titled src6.rar.

Lecture7

The lecture was given by lecturer and titled Lecture 7 Text files and files of records.pdf and it also
had source code file titled src7.rar.

You might also like