Computer Programming 1 ModuleTwo - ATM
Computer Programming 1 ModuleTwo - ATM
Control Statement
The If Statement
This executes sets of command or statements when a condition is satisfied. The syntax
is:
If (condition)
Statement;
The statement is executed only when the condition is true. If the if statement body is consists
of several statements, use pair of curly braces.
In this example, the condition is false then compiler skips the line after the if block.
void main() {
int n;
printf (“ enter a number:”);
scanf(“%d”,&n);
If (n>10)
printf(“ number is greater”);
}
Output:
Enter a number: 9
if (test-expression)
{
True block of statements
MODULE 2
31
}
Else
{
False block of statements
}
Statements;
Program Example:
/* To check even or odd number */
void main() {
int n;
printf (“enter a number:”);
scanf (“%d”, &n);
If (n%2==0)
printf (“even number”);
else
printf(“odd number”);
}
Syntax :
if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}
Else-If Statement
When you need to check multiple conditions within the program, nesting if-else blocks
can be shortened using else-if statement.
Syntax:
if (condition1)
{
// statements to execute if condition1 is true
} REMEMBER THIS!
else if(condition2) 1. else and else-if are optional
{ statements, a program having only “if”
// statements to execute if condition2 is true statement would run fine.
} 2. else and else-if cannot be used
else if (condition3) without the “if”.
{ 3. There can be a number of else-if
statement in a if –else-if block.
// statements to execute if condition3 is true REREME
4. If none of the conditions are met
} then the statements in else block gets
. executed.
. 5 Relational operators and logical
else operators such as AND (&&), OR(||)
{ and NOT(!) can be used inside a
// statements to execute if all the conditions condition to be tested.
return false.
}
Multiple initialization is possible in a for loop. e.g. for (x=1,y=1;x<10 && y<10; x++,
y++). Two variables are initialized separated by a comma. There are two test conditions
MODULE 2
33
using the AND (&&) logical operator to join them. The variable increments part must be
separated using a comma.
The While Loop
The while loop is entry-controlled; condition is evaluated before the loop body is
processed. The body of the loop can contain many statements. If it contains only one
statement then, the curly braces are not required but is considered a good practice to use.
Relational operators and logical operators can be used.
while (condition)
{
statements;
}
The do-while loop is similar to while loop except that the statements inside the loop
body is executed at least once before checking the while condition. It is an exit-controlled
type of loop. Once the control goes out of the loop, the statements outside the loop will be
immediately executed. The key difference between the while and do-while loop is that in
while loop the while is written at the beginning. In do-while loop, the while condition is written
at the end and terminates with a semi-colon (;).
Do-While Syntax
do
{
//Statements
}while(condition test);
the next iteration while inside the loop. Control will jump to the next iteration, skips the
execution of statements in the current iteration inside the loop.
Switch tests the value of a variable and compares it with the cases. Once a match is
found, statements in the case block are executed. A case identifier is use to name the cases
in the switch block. When a case match is not found, a default statement is executed and the
control gets out of the switch block.
switch( expression )
{
case 1:
statement ;
break;
case 2:
statement ;
break;
case 3:
statement ;
break;
default:
statement ;
break;
}
statement;
MODULE 2
35
ACTIVITY 1
Name:_________________ Score/Rating:______________
Course:_______________ Date: ____________________
2. Which of the following statements is not correct about switch and why.
a. The switch statement is a multi-way decision.
b. In switch- case, each case acts like a simple label.
c. Default section will be executed in every case.
d. Every case will continue execution until it reaches break command.
Answer:_________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
3. A variable expressions can be used with switch-case. True or False. Justify your
answer.
Answer:_________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
6. Which of the decision control structures is the best and the easiest to use and
implement and why?
Answer:_________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
A file containing C declarations and macro definitions is called a header file, which is
shared between several source files. To use of a header file in your program, use the C
preprocessing directive ‘#include’. In C, the usual convention is to give header file names
that end with .h.
Header files contain the set of predefined standard library functions that can be
included in C programs. To use various library functions, you have to include the appropriate
header files. There are two kinds of header files: the files that the developer writes and the
files that come with your compiler. When a header file is included in a program, it means that
the program has a copy of the content of the header file. Header files include data types
definitions, function prototypes, and C preprocessor commands. To use the functions printf()
and scanf() in a program, there is a need to include stdio.h.
MODULE 2
37
Format Specifiers
These are used to input and output values with specific format. A way to tell the
compiler what type of data is in a variable, input using scanf() or printing using printf(). These
are the commonly used format specifiers in C:
Program Examples
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter the first value:");
scanf("%d", &a);
printf("Enter the second value:");
scanf("%d", &b);
c = a + b;
printf("%d + %d = %d\n", a, b, c);
return 0;
}
printf("Hello");
This call to printf has a format string that tells printf to send the word "Hello" to standard out.
Contrast it with this:
printf("Hello\n");
The difference between the two is that the second version sends the word "Hello" followed
by a carriage return to standard out.
The following line shows how to output the value of a variable using printf.
printf("%d", b);
The %d is a placeholder that will be replaced by the value of the variable b when the printf
statement is executed. Often, you will want to embed the value within some other words.
One way to accomplish that is like this:
An easier way :
In the printf statement, it is extremely important that the number of operators in the format
string corresponds exactly with the number and type of the variables following it. For
example, if the format string contains three %d operators, then it must be followed by exactly
three parameters and they must have the same types in the same order as those specified
by the operators.
You can print all of the normal C types with printf by using different placeholders/format
specifiers:
The scanf function allows you to accept input from standard in, in general the keyboard.
The scanf function can do a lot of different things, but is unreliable because it does not
handle human errors very well. But for simple programs it is good enough and easy-to-use.
scanf("%d", &b);
The program will read in an integer value that the user enters on the keyboard (%d is for
integers, as is printf, so b must be declared as an int) and place that value into b. The scanf
function uses the same placeholders as printf:
You MUST put & in front of the variable used in scanf. The reasons why will be clear once
you learn about pointers. Forgetting the & sign may crash the program when you run it.
It is best to use scanf to read a single value from the keyboard. Use multiple calls to scanf to
read multiple values. In any real program, you will use the gets or fgets functions instead to
read text a line at a time. Then, there is a need to "parse" the line to read its values.
The printf and scanf functions will take a bit of practice to be completely understood, but
once mastered they are extremely useful.
MODULE 2
39
Try This!
• Modify this program so that it accepts three values instead of two and adds all three
together:
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter the first value:");
scanf("%d", &a);
printf("Enter the second value:");
scanf("%d", &b);
c = a + b;
printf("%d + %d = %d\n", a, b, c);
return 0;
• Try deleting or adding random characters or words in one of the previous programs and
watch how the compiler reacts to these errors.
For example, delete the b variable in the first line of the above program and see what the
compiler does when you forget to declare a variable. Delete a semicolon and see what
happens. Leave out one of the braces. Remove one of the parentheses next to the main
function. Make each error by itself and then run the program through the compiler to see
what happens. By simulating errors like these, you can learn about different compiler
errors, and that will make your typos easier to find when you make them for real.
Examples:
Answer:
Answer:
Answer:
#include<stdio.h>
main()
{
int vol, len, width, height;
clrscr();
printf(“Enter Height;”);
scanf(‘%d”,&height);
printf(“Enter Width;”);
scanf(‘%d”,&width);
printf(“Enter Length;”);
scanf(‘%d”,&len);
vol=len*width*height;
printf(“the volume is %d”,vol);
getch();
}
Answer:
#include<stdio.h>
main()
{
int total, first, second, add, sub;
clrscr();
printf(“Enter 1st number;”);
scanf(‘%d”,&first);
printf(“Enter 2nd number;”);
scanf(‘%d”,&second);
add=first+second;
sub=first-second;
printf(“the sum is %d and the difference is %d”,add,sub);
getch();
}
MODULE 2
41
Answer:
#include<stdio.h>
main()
{
clrscr();
printf(“ * ”);
printf(“* *”);
printf(“ * ”);
getch();
}
Answer:
#include<stdio.h>
main()
{
clrscr();
printf(“ hello this is my first page ”);
getch();
clrscr();
printf(“ hello this is my second page ”);
getch();
}
C Errors to Avoid
ACTIVITY 2
Name:_________________ Score/Rating:______________
Course:________________ Date: ____________________
1. Input n (a positive integer) numbers and work out their sum, average and sum of the
squares of the numbers.
2. Write a program to read a "float" representing a number of degrees Celsius, and print as a
"float" the equivalent temperature in degrees Fahrenheit. Print your results in this format:
3. Write a program to print several lines (such as your name and address). You may use
either several printf instructions, each with a newline character in it, or one printf with several
newlines in the string.
4. Write a program to input and output the name and age of a person. The program output
would look like this:
5. Write a C program that accepts 10 integers and output the product of the numbers.
MODULE 2
43
ACTIVITY 3
Name:_________________ Score/Rating:______________
Course:________________ Date: ____________________
1. Write a program that uses scanf() and printf() statements to prompt for your first name,
last name, street, city, state and zip code then print/output the values in the following format:
Name: ,
Street:
City: State:
Zip:
2.Write a program that will prompt for an input of a temperature in Fahrenheit and will display
as output both the Fahrenheit value and the temperature converted to Celsius. Use the
formula;
3. Given three numbers A, B and C. Write a program to compute and print out the sum, the
average, and the product of these values.
4. Write a program that will ask input of the name, prelim, midterm and final grade of a
student and will output the average.
The if statement and while loop rely on the idea of Boolean expressions. This is a simple
C program demonstrating an if statement:
#include <stdio.h>
int main()
{
int b;
printf("Enter a value:");
scanf("%d", &b);
if (b < 0)
printf("The value is negative\n");
return 0;
}
The program accepts an input of type integer from the user, then tests the input using an if
statement to check if it is less than 0 and prints a message. The (b < 0) portion of the
program is the Boolean expression. C evaluates this expression to decide whether or not to
print the message. If the Boolean expression evaluates to True, then C executes the single
line immediately following the if statement (or a block of lines within braces immediately
following the if statement). If the Boolean expression is False, then C skips the line or block
of lines immediately following the if statement.
Program Example:
#include <stdio.h>
int main()
{
int b;
printf("Enter a value:");
scanf("%d", &b);
if (b < 0)
printf("The value is negative\n");
else if (b == 0)
printf("The value is zero\n");
else
printf("The value is positive\n");
return 0;
}
MODULE 2
45
q=10;
The statement evaluates the expressions, "If the value in variable x equals the value in
variable y, and if the value in variable j is greater than the value in variable k, then set the
variable z to 1, otherwise set the variable q to 10."
C language uses == to test for equality, while it uses = to assign a value to a variable. The
&& in C represents a Boolean AND operation.
This causes the two lines within the braces to be executed repeatedly until “a is greater than
or equal to b” becomes FALSE.
do
{
printf("%d\n", a);
a = a + 1;
}
while (a < b);
The for loop in C is simply a shorthand way of expressing a while statement. For example,
suppose you have the following codes;
x=1;
while (x<10)
{
statement;
x++; /* x++ is the same as x=x+1 */
}
The while loop contains an initialization step (x=1), a test step (x<10), and an increment step
(x++). The for loop lets you put all three parts in one line.
a=1;
b=6;
while (a < b)
{
a++;
printf("%d\n",a);
}
The comma operator lets you separate several different statements in the initialization and
increment sections of the for loop (but not in the test section).
You would like to create a program that prints a Fahrenheit-to-Celsius conversion table. This
can be accomplished with a for loop or a while loop:
#include <stdio.h>
int main()
{
int a;
a = 0;
while (a <= 100)
{
printf("%4d degrees F = %4d degrees C\n", a, (a - 32) * 5 / 9);
a = a + 10;
}
return 0;
}
If you run this program, if will produce a table of values starting at 0 degrees F and ending at
100 degrees F. The output will look like this:
The table's values are in increments of 10 degrees. If you want your values to be more
precise, use floating point values :
#include <stdio.h>
int main()
{
MODULE 2
47
float a;
a = 0;
while (a <= 100)
{
printf("%6.2f degrees F = %6.2f degrees C\n",
a, (a - 32.0) * 5.0 / 9.0);
a = a + 10;
}
return 0;
}
The declaration for a changed to a float, and the %f symbol replaces the %d symbol in the
printf statement. In addition, the %f symbol has some formatting applied to it: The value will
be printed with six digits preceding the decimal point and two digits following the decimal
point.
Now let's say that we wanted to modify the program so that the temperature 98.6 is inserted
in the table at the proper position. That is, we want the table to increment every 10 degrees,
but we also want the table to include an extra line for 98.6 degrees F because that is the
normal body temperature for a human being. The following program accomplishes the goal:
#include <stdio.h>
int main()
{
float a;
a = 0;
while (a <= 100)
{
if (a > 98.6)
{
printf("%6.2f degrees F = %6.2f degrees C\n", 98.6, (98.6 - 32.0) * 5.0 / 9.0);
}
printf("%6.2f degrees F = %6.2f degrees C\n",a, (a - 32.0) * 5.0 / 9.0);
a = a + 10;
}
return 0;
}
This program works if the ending value is 100, but if you change the ending value to 200 you
will encounter a bug in the program. It prints the line for 98.6 degrees too many times. The
codes below will fix the bug.
#include <stdio.h>
int main()
{
float a, b;
a = 0;
b = -1;
while (a <= 100)
{
if ((a > 98.6) && (b < 98.6))
{
printf("%6.2f degrees F = %6.2f degrees C\n", 98.6, (98.6 - 32.0) * 5.0 / 9.0);
}
printf("%6.2f degrees F = %6.2f degrees C\n", a, (a - 32.0) * 5.0 / 9.0);
b = a;
a = a + 10;
}
return 0;
}
Try This!
Program Examples:
1. Create a program that computes final grade and prints the remarks, PASSED
or FAILED.
Answer:
#include<stdio.h>
main()
{
int prelim, midterm, finals, finalgrade;
clrscr();
printf(“Enter Prelim:”);
scanf(“%d”, &prelim);
printf(“Enter Midterm:”);
scanf(“%d”, &midterm);
printf(“Enter Finals:”);
scanf(“%d”, &finals);
finalgrade=(prelim+midterm+finals)/3;
printf(the final grade is %d”,finalgrade);
if(finalgrade>=75)
{
printf(“PASSED\n”);
}
else
{
printf(“FAILED\n”)’
}
getch();
MODULE 2
49
}
2. Create a program that converts decimal to binary using if-else ladder
Answer:
#include<stdio.h>
main()
{
int choice,
clrscr();
printf(“>>>menu<<<\nEnter decimal numbers 1 up to 5:”);
scanf(“%d”,&choice);
if(choice==1)
{
printf(“0001\n”);
}
else if(choice==2)
{
printf(“0010\n”);
}
else if(choice==3)
{
printf(“0011\n”);
}
else if(choice==4)
{
printf(“0100\n”);
}
else if(choice==5)
{
printf(“0101\n”);
}
else
{
printf(“invalid syntax!!!\n”);
}
getch();
Answer:
#include<stdio.h>
main()
{
int choice,
clrscr();
printf(“>>>menu<<<\nEnter decimal numbers 1 up to 5:”);
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“0001\n”);break;
case 2: printf(“0010\n”);break;
case 3: printf(“0011\n”);break;
case 4: printf(“0100\n”);break;
case 5: printf(“0101\n”);break;
default:printf(“invalid syntax\n”);
}
getch();
}
4. Create a program that prints numbers and letters simultaneously using a for-
loop.
Answer:
#include<stdio.h>
main()
{
char letters;
int num;
clrscr();
/*print letters*/
for(letters=’a’;letters<=’z’;++letters)
{
printf(“\t%c\n”,letters);
}
/*for numbers*/
for(num=1;num<=26;num--)
{
printf(“\t%d\n”,num);
}
getch();
}
Answer:
#include<stdio.h>
main()
{
int a;
clrscr();
a=’e’;
while(a>=’a’)
{
printf(“%c”,a);
a++;
}
getch();
}
MODULE 2
51
6. Create a program that prints hello word three (3) times using do-while
structure.
Answer:
#include <stdio.h>
int main(void)
{
int x = 3;
do
{
printf("Hello World!\n");
x = x –1;
} while (x > 0);
getch();
}
Activity 4
Name:_________________ Score/Rating:______________
Course:___ _____________ Date: ____________________
1. This program will compute the average of P1, P2, P3. If the average is equal or less 74,
the remark is failed. If equal to 75, the remark is passed, if greater than 75 the remark is
better, if greater or equal to 81 the remark is best, else the remark is NA.
2. This program will compute the average of three inputs. If the average is less or equal to 74
the remark is poor. Else impressive.
3. This program accepts two integers and displays the sum, prints remarks whether the sum
is equal to 10, less than 10, or greater than 10.
4. Write a program that determines if the age (input) is qualified to vote or not.
5. The initial value of the radius of a circle is equal to one unit and each succeeding radius is
one unit greater than the value before it. Write a program that computes the area of the
circle starting with r = 1.0 to r = 5.0. Print out each radius and the corresponding area of the
circle.
8. Write a program that shows the counting process of integers 1 - 10 and add all the
numbers.
9. Write a program that determines the Class of Ship depending on its class ID.
The Class ID serves as the input data and the Ship Class as output information.
10. Write a program that converts the decimal numbers 1-10 to binary.
MODULE 2