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

Computer Programming 1 ModuleTwo - ATM

Uploaded by

Edward Fordan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Computer Programming 1 ModuleTwo - ATM

Uploaded by

Edward Fordan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

30

[COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


Gordon College- College of Computer Studies

Control Statement

C program statement is executed in an order in which they appear in the program


(sequential). For execution only a part decision-making condition is used in a program, called
control statement. Control statement defines how the control is transferred from one part of
the program to other part. If...else, switch, while, do....while, for loop, break, continue, goto
etc. are examples.

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

The if -else Statement

In if-else construct, if the value of test-expression is


true, then the true block of statements will be executed.
When the value of test-expression if false, then the
false block of statements will be executed. In any case,
after the execution, the control will be automatically
transferred to the statements appearing outside the if –
block. Condition may be true or false, where non-zero
value regarded as true and zero value regarded as
false.
The general form of if-else is as follows:

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”);
}

Output: enter a number:121


odd number

The Nested If-Else Statement

An If-Else statement inside a body of another if-else statement is referred to as a


nested if-else.

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

1st Semester, A.Y. 2022-2023


32

[COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


Gordon College- College of Computer Studies

} 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.
}

The For Loop


A loop is for executing a block of
statements repeatedly until a given condition returns false. Below is the flow diagram of a for loop.
Step 1. The initialization process happens when the counter variable is initialized. Step 2. Condition
is CHECKED, the counter variable is tested for the given condition. If it returns true, the statement
inside the loop body will be executed. Otherwise, the loop will
terminate with the control going out of the loop.
Step 3. When statements inside the loop body are executed
successfully, the counter variable is incremented (++) or
decremented (--).

For Loop syntax:


for (initializationStatement; testExpression; updateStatement)
{
// statement/s inside the body of loop
}

The Nested For Loop

A for-loop inside another for-loop is called a nested


for-loop. Multi- dimensional Arrays implement nested for-
loops.

Nested For Loop Syntax:

for ( initialization; condition; increment ) {

for ( initialization; condition; increment ) {

// statement of inside loop


}

// statement of outer loop


}

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 Loop Syntax:

while (condition)
{
statements;
}

The Do-While Loop

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);

To select the appropriate loop implementation, it would be best to analyze the


problem and check if it requires a pre-test or a post-test loop. Use while or for loop if it
requires pre-test and do-while for post-test.

The Break Statement

Use to immediately stop a loop. A break statement


(break;) inside a loop will directly make the control comes out of
the loop and the loop will terminate.
The break statement is used with if
statement inside the loop and can
also be used in switch case control
structure. A break statement in a
switch case block will prevent the rest
of the subsequent case blocks to be executed.

The Continue Statement


The continue statement (continue;) will let the loop skip

1st Semester, A.Y. 2022-2023


34

[COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


Gordon College- College of Computer Studies

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.

The Switch Statement

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 Case Syntax

switch( expression )
{
case 1:
statement ;
break;
case 2:
statement ;
break;
case 3:
statement ;
break;
default:
statement ;
break;
}
statement;

The expression in the switch can be an integer


or a character expression. Case labels are used to identify each case individually. A case
label should not be the same or it may cause a problem during program execution that
results to undesired output. The case labels must end with a colon (:). Each case is
associated with a block, a grouped multiple statements for a particular case. As the switch is
executed, the value of the test expression is compared with all the defined cases inside the
switch. When a case match is found, the block of statements in
that particular case is executed and control goes out of the
switch after the break statement is encountered. Break will stop
the case once executed and control will fall out of the switch. A
default case is optional, where the test-expression value is not
matched with any of the given cases in the switch, the default
will be executed.
Nested Switch Case
An inner switch embedded in an outer switch is called a
nested switch. The inner case labels should not cause conflicts
with the outer case labels. Use different case labels, common
values may cause conflicts and undesired output.
In a switch statement, an expression must always
execute to a result. Case Labels must be constants and unique.
The case labels must always end with a colon. Break statement must be present in each
case but is removed in a fall through switch implementation.

MODULE 2
35

ACTIVITY 1

Name:_________________ Score/Rating:______________
Course:_______________ Date: ____________________

Answer the following.


1. Show the correct syntax of an if statement? Answer: __________________________

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:_________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________

4. What is the most general way of writing a multi-way decision construct?


Answer:_________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________

5. In if-else, else block executes when?


Answer:_________________________________________________________________
_______________________________________________________________________

6. Which of the decision control structures is the best and the easiest to use and
implement and why?
Answer:_________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________

1st Semester, A.Y. 2022-2023


36

[COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


Gordon College- College of Computer Studies

The C Header Files

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.

Header File Description


stdio.h Input/Output Functions
conio.h console input/output
assert.h Diagnostics Functions
ctype.h Character Handling Functions
cocale.h Localization Functions
math.h Mathematics Functions
setjmp.h Nonlocal Jump Functions
signal.h Signal Handling Functions
stdarg.h Variable Argument List Functions
stdlib.h General Utility Functions
string.h String Functions
time.h Date and Time Functions
complex.h A set of function for manipulating complex
numbers
stdalign.h For querying and specifying the alignment of
objects
errno.h For testing error codes
locale.h Defines localization functions
stdatomic.h For atomic operations on data shared
between threads
stdnoreturn.h For specifying non-returning functions
uchar.h Types and functions for manipulating
Unicode characters
fenv.h A set of functions for controlling the floating-
point environment
wchar.h Defines wide string handling functions
tgmath.h Type-generic mathematical functions
stdarg.h Accessing a varying number of arguments
passed to functions
stdbool.h Defines a boolean data type
Table 1. List of C Language Header Files
Source: https://www.improgrammer.net/wp-content/uploads/2018/02/C-Programming-Language-Header-files-list.pdf

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:

%d or %i: Integer Format Specifier


%c: Character Format Specifier
%f: Floating-Point Format Specifier.
%s: String Format Specifier.
%lf: Double Format Specifier.
%e or %E: Floating-Point Format Specifier ( Exponential ).

The Functions printf() and scanf()


The printf() function is used to display the output and scanf() is used to read the
inputs. Both the printf() and scanf() functions are declared in “stdio. h” header file in C library.
All syntax in C language including printf() and scanf() functions are case sensitive.

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;
}

The printf statement:

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:

1st Semester, A.Y. 2022-2023


38

[COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


Gordon College- College of Computer Studies

printf("The temperature is ");


printf("%d", b);
printf(" degrees\n");

An easier way :

printf("The temperature is %d degrees\n", b);

You can also use multiple %d placeholders in one printf statement:

printf("%d + %d = %d\n", a, b, c);

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:

• int (integer values) uses %d


• float (floating point values) uses %f
• char (single character values) uses %c
• character strings (arrays of characters, discussed later) use %s

The scanf statement:

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:

1. Create a program that adds 2 integer:

Answer:

/* program that adds 2 integer */


#include<stdio.h>
main()
{
int var1, var2, sum;
clrscr();
printf(“Enter 1st integer:\n”);
scanf(“%d”,&var1);
printf(“Enter 2nd integer:\n”);
scanf(“%d”,&var2);
sum=var1+var2;
printf(“The sum of 2 integers is %d”,sum);
getch();
}

2. Create a program that prints HELLO WORLD 3 times.

1st Semester, A.Y. 2022-2023


40

[COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


Gordon College- College of Computer Studies

Answer:

/* program that prints HELLO WORLD */


#include<stdio.h>
main()
{
clrscr();
printf(“HELLO WORLD\n HELLO WORLD\n HELLO WORLD\”);
getch();
}

3. Create a program that computes the volume of the box.

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();
}

4. Create a program that adds and performs subtraction of two numbers:

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();
}

5. Create a program that prints a diamond shape.

MODULE 2
41

Answer:

#include<stdio.h>
main()
{
clrscr();
printf(“ * ”);
printf(“* *”);
printf(“ * ”);
getch();
}

6. Create a program that prints labels of two pages.

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

Using the wrong character case - Case matters in C, so you cannot


type Printf or PRINTF. It must be printf.

Forgetting to use the & in scanf

Too many or too few parameters following the format statement in


printf or scanf

Forgetting to declare a variable name before using it

1st Semester, A.Y. 2022-2023


42

[COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


Gordon College- College of Computer Studies

ACTIVITY 2

Name:_________________ Score/Rating:______________
Course:________________ Date: ____________________

Write C programs to perform the following tasks:

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:

100.0 degrees Celsius converts to 212.0 degrees Fahrenheit

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:

Enter your name: Marc Christopher


Enter your age: 17

The information obtained was:


Name: Marc Christopher Age: 17

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: ____________________

Write C programs to perform the following tasks:

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;

Celsius Degrees = (Fahrenheit Degrees - 32) * 5/9

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.

5. Write a program that computes the volume of a box.

1st Semester, A.Y. 2022-2023


44

[COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


Gordon College- College of Computer Studies

Decision Making and Branching

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;
}

In this example, the else if and else sections


evaluate zero and positive values.

Here is a Boolean expression:

if ((x==y) && (j>k))


z=1;
else

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.

The While Statement Implementation

while (a > =b)


{
printf("%d\n", a);
a = a + 1;
}

This causes the two lines within the braces to be executed repeatedly until “a is greater than
or equal to b” becomes FALSE.

The do-while Structure

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 */
}

You can convert this into a for loop ;

for(x=1; x<10; x++)


{
statement;
}

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)
{

1st Semester, A.Y. 2022-2023


46

[COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


Gordon College- College of Computer Studies

a++;
printf("%d\n",a);
}

The for loop conversion;

for (a=1,b=6; 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:

0 degrees F = -17 degrees C


10 degrees F = -12 degrees C
20 degrees F = -6 degrees C
30 degrees F = -1 degrees C
40 degrees F = 4 degrees C
50 degrees F = 10 degrees C
60 degrees F = 15 degrees C
70 degrees F = 21 degrees C
80 degrees F = 26 degrees C
90 degrees F = 32 degrees C
100 degrees F = 37 degrees C

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))

1st Semester, A.Y. 2022-2023


48

[COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


Gordon College- College of Computer Studies

{
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!

• Try changing the Fahrenheit-to-Celsius program so that it uses


scanf to accept the start, end and increment values of the table
from the user.
• Add a Table Heading in the Output.
• Try to find other solutions to fix the bug in the previous example.
• Create a table that converts pounds to kilograms or miles to
kilometers.

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();

3. Create a program that converts decimal to binary using switch-case statement.

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;

1st Semester, A.Y. 2022-2023


50

[COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


Gordon College- College of Computer Studies

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();
}

5. Create a program that prints letters e to a using while loop.

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();
}

1st Semester, A.Y. 2022-2023


52

[COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


Gordon College- College of Computer Studies

Activity 4

Name:_________________ Score/Rating:______________
Course:___ _____________ Date: ____________________

Write C programs to perform the following tasks:

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.

6. Write a program that computes and displays the factorial of n (input).

7. Write a program that will count from 1 to 20.

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.

Class ID Ship Class


B or b Battle Ship
C or c Cruiser
D or d Destroyer
F or f Frigate

10. Write a program that converts the decimal numbers 1-10 to binary.

MODULE 2

You might also like