0% found this document useful (0 votes)
46 views42 pages

Computer Programming For Engineering Applications

Here is the C program to solve the ballistic trajectory problem: #include <stdio.h> #define PI 3.14159 #define g 9.81 int main() { float angle, velocity, distance; printf("Enter firing angle (in degrees): "); scanf("%f", &angle); printf("Enter initial velocity (in m/s): "); scanf("%f", &velocity); angle = angle * PI / 180; if(angle >= 0 && angle <= PI/2) { distance = (velocity*velocity) * sin(2*angle) / g; printf("The horizontal distance = %.3f m\n", distance);

Uploaded by

vincent xu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views42 pages

Computer Programming For Engineering Applications

Here is the C program to solve the ballistic trajectory problem: #include <stdio.h> #define PI 3.14159 #define g 9.81 int main() { float angle, velocity, distance; printf("Enter firing angle (in degrees): "); scanf("%f", &angle); printf("Enter initial velocity (in m/s): "); scanf("%f", &velocity); angle = angle * PI / 180; if(angle >= 0 && angle <= PI/2) { distance = (velocity*velocity) * sin(2*angle) / g; printf("The horizontal distance = %.3f m\n", distance);

Uploaded by

vincent xu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Computer Programming for

Engineering Applications

ECE 175

Intro to Programming
Lecture Set Overview

Branching – if-else statements

Relational, Equality, and Logical Operators

Switch statements

02/13/2021 ECE 175 2


Control Structures

Allow us to control the sequence of program execution

Several types of control structures


Unconditional branching – Continue at a different statement

Conditional branching – Execute a set of statements only if a condition


is met
E.g. if condition = true  Execute a set of statements once

Looping – Execute a set of statement repeatedly until some condition


is met
E.g., while condition = true  repeat this set of statements

02/13/2021 ECE 175 3


false true
pH>7
true false
pH=7 pH<12

“Neutral” “Very true


false
Alkaline”
“Alkaline”
true
pH>2

false “Acidic”
“Very
Acidic”

02/13/2021 ECE 175 4


Conditional Branching
if (condition) switch(variable)
{ {
statements; case value1:
} statements;
else if (condition) break;
{
statements; case value2:
} statements;
else if (condition) break;
{ ...
statements; default:
} statements;
... }
else
{
statements
}

02/13/2021 ECE 175 5


Syntax of the if-else structure
if (condition)
{ if (condition)
statements; {
} statements;
else if (condition1) }
{
statements;
}
else if (condition2) if (condition)
{ {
statements; statements;
} }
... else
else {
{ statements;
statements }
}
02/13/2021 ECE 175 6
Square root of a positive number
Problem: Write a program that asks the user for a number and
returns the square root of the entered number if it is a positive value

Pseudocode:
Begin
Initialize x
print: Enter a positive number
read x
if x > 0
compute square root of x
print: The square root of x is sqrt(x)
else
print: error message
End

02/13/2021 ECE 175 7


Square root problem – If statement
Check if given number is negative before computing the square root

#include <stdio.h>
#include <math.h> // declaration of the math library

int main(void)
{
float num, root; /* declaration of two float variables */

printf("Enter a positive number>");


scanf("%f", &num); // read a float number

if (num > 0) // if the user input is positive


{
root = sqrt(num); // computation of the square root
printf("The root of %.1f is %.1f\n", num, root);
}
else // if user input is less or equal to zero
printf("A real square root does not exist\n");
return(0);
}

02/13/2021 ECE 175 8


Exercise 1: Odd or Even?
Check if an integer entered by the user is odd or even
Step 1: Write pseudo-code (algorithm)
Step 2: Translate it to C code
Pseudocode:
Begin
Initialize x
Enter an integer> 5 print: Enter an integer number
5 is odd read x

//Complete the Pseudocode here


Enter an integer> 104
104 is even

End

02/13/2021 ECE 175 9


Relational and Equality Operators

Operators are usually used in the form


variable operator variable or constant
Operator Meaning Type
< less than relational
> greater than relational
<= less than or equal to relational
>= greater than or equal to relational
== equal to equality
!= not equal to equality

Output is either True(1) or False (0)

02/13/2021 ECE 175 10


Relational Operator Examples
Sample data: power = 1024; MAX_POW = 1024;
item = 1.5; MIN_ITEM = -999.0;
x = -5; y = 7;
letter ='M'; num=999 ; testnum = 0;

Operator Condition Value


< power < MAX_POW 0 (false)
> item > MIN_ITEM 1 (true)
<= x <= 0
>= x >= y
== letter == 'M'
!= (num%3) != testnum

02/13/2021 ECE 175 11


Exercise 2: Write a C conditional statement for the followings

a) Check whether the distance between (x1,y1) and (x2,y2) is less than 10
Note: assuming that there are values in all these variables by initialization or a user will enter them.
double x1, y1, x2, y2;

b) To check whether the volume of sphere is greater than the volume of a cube
Note: assuming that there are values in all these variables by initialization or a user will enter them.
double r_sphere, side_cube;

02/13/2021 ECE 175 12


Logical Operators
Logical operators are used to check multiple conditions at the same time
Three different logical operators:
&& and
|| or
! not

Examples

while(ans != 'n' && ans != 'N')


{ … }

if (x < 0 || x > 25)


{
y = x + 5;
}

02/13/2021 ECE 175 13


Logical Operator Truth Tables
Operand 1 !Operand1
False (0) True (1)
True (1) False (0)

Operand 1 Operand 2 Operand 1 && Operand 2


False (0) False (0) False (0)
False (0) True (1) False (0)
True (1) False (0) False (0)
True (1) True (1) True (1)

Operand 1 Operand 2 Operand 1 II Operand 2


False (0) False (0) False (0)
False (0) True (1) True (1)
True (1) False (0) True (1)
True (1) True (1) True (1)

02/13/2021 ECE 175 14


Exercise 3: Evaluate the Following Relational Operators
The answer is either 1 (True) or 0 (False)

int y1, y2, y3, y4;


Int x = 7;
char letter = 'b';

y1 = (x >= 5 && x%2 == 0);

y2 = (x >= 5 || x%2 == 0);

y3 = (!(x > 0));

y4 = (letter >= 'g' || letter <= 'z')

y5 = (letter >= 'g' && letter <= 'z')

02/13/2021 ECE 175 15


Exercise 4:
 In physics, the ballistic trajectory of a projectile is the path that a thrown object will take under the
action of gravity, neglecting all other forces, such as friction from air resistance. Write a C program
that
- lets a user enter angle of elevation (in degrees) and initial velocity (meter/sec)
- if the angle of elevation is between 0 and 90 degrees, computes the
horizontal distance that it travels (in meters) using the equation below
- else display a message

where is an angle of elevation (in radians)


Enter firing angle (in degrees): 45
distance is a horizontal distance that it travel
Enter initial velocity (in m/s): 20
v is a projectile velocity (m/s)
g = 9.81 m/s2
The horizontal distance = 40.775 m  

Enter firing angle (in degrees): 60


Enter initial velocity (in m/s): 100
The horizontal distance = 882.799 m

Enter firing angle (in degrees): 120


The firing angle must be between 0 and 90 degree
02/13/2021 ECE 175 16
Enter firing angle (in degrees): 45
Exercise 4: modify the code Enter initial velocity (in m/s): 20
The horizontal distance = 40.775 m  
Enter firing angle (in degrees): 120
The firing angle must be between 0 and 90 degree Enter firing angle (in degrees): 60
Enter initial velocity (in m/s): 100
The horizontal distance = 882.799 m
#include <stdio.h>
#include <math.h>

#define GVALUE 9.81


#define PI 3.14159
int main(void)
{
double angle, velocity, distance;

printf("Enter firing angle(in degrees): ");


scanf("%lf", &angle);

printf("Enter initial velocity(in m / s): ");


scanf("%lf", &velocity);

distance = velocity*velocity*sin(2 * (angle*PI/180)) /GVALUE;

printf("The horizontal distance = %.3lf m\n", distance);

02/13/2021 ECE 175 17


Exercise 4 Solution
#include <stdio.h>
#include <math.h>

#define GVALUE 9.81


#define PI 3.14159
int main(void)
{
double angle, velocity, distance;

printf("Enter firing angle(in degrees): ");


scanf("%lf", &angle);

if( (angle >= 0) && (angle <= 90)){


printf("Enter initial velocity(in m / s): ");
scanf("%lf", &velocity);
distance = velocity*velocity*sin(2 * (angle*PI/180)) /GVALUE;
printf("The horizontal distance = %.3lf m\n", distance);
}
else{
printf("The firing angle must be between 0 and 90 degree\n");

}
}

02/13/2021 ECE 175 18


Exercise 5: Write C expression(s) for the followings

a) x and y are greater than z

b) x is equal to 1 or -1

c) x is greater than z but less than y (assume z < y)

d) |x| > 10 (|x| is absolute value of x)

e) variable char ltr is in the range of ‘a’ and ‘z’, inclusive


(variable ltr is lowercase)

02/13/2021 ECE 175 19


Examples of Logical Operators Combinations
Checking for lowercase letters
#include<stdio.h>
// Checking if a letter lowercase

int main(void)
{
char ltr; // declaration of a char variable

printf("Enter a lowercase letter");


scanf("%c", &ltr);

if (ltr >='a' && ltr <='z') // if lowercase


{
printf("%c\n",ltr); // print ltr
}
else
printf(”Wrong input\n");

return(0);
}
02/13/2021 ECE 175 20
Operator Precedence
Note: Parentheses ( ) are executed first from left to right

Operator Highest
! + - & (unary operators)
* / %
+ -
< <= >= >
== !=
&&
|| Lowest

02/13/2021 ECE 175 21


Activity: - Ask the user to enter a number and
- print it if it a multiple of 7 and 5

Step 1: Write pseudo-code (algorithm)


Step 2: Translate it to C code
Enter an integer> 35
Pseudocode:
35 is a multiple of 5 and 7
Begin
Initialize x
print: Enter an integer number Enter an integer> 100
read x 100 is NOT a multiple of 5 and 7

//Complete the Pseudocode here

End
02/13/2021 ECE 175 22
Activity: Step 2 (C program)
Printing multiples of 5 and 7

#include <stdio.h>
// Printing multiples of 5 and 7

int main(void)
{
int i; // declaration of an integer variable
printf("Guess a multiple of 5 and 7:");
scanf("%d", &i); // awaiting for an integer from the user

if(i%5 == 0 && i%7 == 0)


printf("%d is a multiple of 5 and 7\n", i);
else
printf("%d is NOT a multiple of 5 and 7\n", i);

return(0);
}

02/13/2021 ECE 175 23


Syntax of the if-else Block Command

if (condition)
{
statements;
}
else if (condition)
{
statements;
}
else if (condition)
{
statements;
}
...
else
{
statements
}

02/13/2021 ECE 175 24


Example: Table
show the relationship between noise levels and
human perceptions of noises.
Loudness in dB Perception
50 or lower quiet
51-70 intrusive
71-90 annoying
91-110 very annoying
above 110 uncomfortable
Your program lets a user enter loudness in dB with integer value and display a message

if (noise_dB <= 50)


printf("%d dB noise is quiet.\n", noise_dB);
else if (noise_dB <= 70)
printf("%d dB noise is intrusive.\n", noise_dB);
else if (noise_dB <= 90)
printf("%d dB noise is annoying.\n", noise_dB);
else if (noise_dB <= 110)
printf("%d dB noise is very annoying.\n", noise_dB);
else
printf("%d dB noise is uncomfortable.\n", noise_dB);

02/13/2021 ECE 175 25


Be careful about the order of conditions in a multiple-alternative decision
if (noise_dB <= 50) if (noise_dB <= 110)
printf("quiet\n"); printf("very annoying\n");
else if (noise_dB <= 70) else if (noise_dB <= 90)
printf("intrusive\n”); printf("annoying\n");
else if (noise_dB <= 90) else if (noise_dB <= 70)
printf(“annoying\n"); printf("intrusive\n");
else if (noise_dB <= 110) else if (noise_dB <= 50)
printf(“very annoying\n"); printf("quiet\n");
else else
printf("uncomfortable\n"); printf("uncomfortable\n");

What get printed if noise_dB = 70? What get printed if noise_dB = 70?

Solution: intrusive Solution: very annoying

Note: the above is an INcorrect way of writing


if statement for this problem given in slide 25

02/13/2021 ECE 175 26


Do the below programs give the same answer for the same input value?

if (noise_dB <= 50) if (noise_dB <= 50)


printf("quiet\n"); printf("quiet\n");
else if (noise_dB <= 70) if (noise_dB <= 70)
printf("intrusive\n”); printf("intrusive\n”);
else if (noise_dB <= 90)
if (noise_dB <= 90)
printf(“annoying\n");
printf(“annoying\n");
else if (noise_dB <= 110)
if (noise_dB <= 110)
printf(“very annoying\n");
printf(“very annoying\n");
else
else
printf("uncomfortable\n");
printf("uncomfortable\n");
What get printed if noise_dB = 85? What get printed if noise_dB = 85?
Solution: annoying
Solution: annoying
very annoying
Note: the above is an INcorrect way of writing
if statement for this problem given in slide 25

02/13/2021 ECE 175 27


Activity : Write a C program for the following
=> Let a user enter one character -> store it in a variable letter.
=> If the entered character is UPPERcase, print the character and its lowercase.
=> If the entered character is lowercase, print the character and its
UPPERcase => If the entered character is neither UPPERcase nor lowercase,
only print that character.

Sample code execution: Red is a user input


Enter a character: A
Aa

Enter a character: m
mM

Enter a character: ^
^

02/13/2021 ECE 175 28


Solution

#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>

int main(void){

char letter;
printf("Enter a character: ");
scanf("%c", &letter);

if (letter >= 'a' && letter <= 'z')


printf("%c%c\n", letter, letter - 32);
else if (letter >= 'A' && letter <= 'Z')
printf("%c%c\n", letter, letter + 32);
else
printf("%c\n", letter);

return(0);
}

02/13/2021 ECE 175 29


02/13/2021 ECE 175 30
Nested If statements
Checking multiple conditions in a sequential manner

false true
pH>7
true false
pH=7 pH<12

“Neutral” “Very true


false
Alkaline”
“Alkaline”
true
pH>2

false “Acidic”
“Very
Acidic”

02/13/2021 ECE 175 31


#include <stdio.h>
int main(void){
int pH; // integer variable
printf("Give the acidity of the solution:");
scanf("%d", &pH); // reading the acidity to pH variable

if (pH > 7)
{
if (pH < 12)
printf("alkaline\n");
else // pH >= 12
printf("very alkaline\n");
}
else // pH < or = 7
{
if (pH == 7)
printf("neutral\n");
else
{
if (pH > 2)
printf("acidic\n");
else // if pH is less or equal to 2
printf("very acidic\n");
}
}
return 0;
}
02/13/2021 ECE 175 32
#include <stdio.h>

int main(void)
{
int pH; // integer variable
printf("Give the acidity of the solution:");
scanf("%d",&pH); // reading the acidity to pH variable

if ( (pH > 7) && (pH < 12)) {


printf("alkaline\n");
}
else if (pH >= 12)
printf("very alkaline\n");
}
else // if pH is less or equal to 7
{
if (pH == 7)
printf("neutral\n");
else // pH is not equal to 7
{
if (pH > 2) // pH < 7 but > 2
printf("acidic\n");
else // pH < or = 2
printf("very acidic\n");
}
}
return(0);
}

02/13/2021 ECE 175 33


Same example using if-else if-else structure
#include <stdio.h>

int main(void)
{
int pH; // integer variable
printf("Give the acidity of the solution:");
scanf("%d", &pH); // reading the acidity to pH variable

if (pH > 7 && pH < 12)


printf("alkaline\n");
else if (pH >= 12)
printf("very alkaline\n");
else if (pH == 7)
printf("neutral\n");
else if (pH > 2) // pH is < 7 but > 2
printf("acidic\n");
else // pH is less or equal to 2
printf("very acidic\n");

return(0);
}

02/13/2021 ECE 175 34


The switch structure
switch(variable)
{
case value1:
statements;
break;
case value2:
statements;
break;
...
default:
statements;
}

break; stops the execution of the switch


Stops the execution of the loop

break; <- required in switch, otherwise the default case will be executed as well
02/13/2021 ECE 175 35
#include<stdio.h>
int main(void){ switch Block Command
int watts;
printf("Enter the bulb wattage (in Watts):");
scanf("%d", &watts); // user input stored in watts

switch (watts)
{
case 15: // if watts = 15
printf("The bulb's brightness is 125 lumens\n");
break; // terminate
case 25: // if watts = 25
printf("The bulb's brightness is 215 lumens\n");
break; // terminate
case 40: // if watts = 40
printf("The bulb's brightness is 500 lumens\n"); // print 500
break; // terminate
case 60: // if watts = 60
printf("The bulb's brightness is 880 lumens\n"); // print 880
break; // terminate
case 75: // if watts = 75
printf("The bulb's brightness is 1000 lumens\n"); // print 1000
break; // terminate
case 100: // if watts = 100
printf("The bulb's brightness is 1675 lumens\n"); // print 1675
break; // terminate
default: // default case if the user inputs a value outside the table
printf("The bulb's brightness is unknown\n"); // unknown brightness
}
return(0);
02/13/2021 } ECE 175 36
One way equivalence of if-else-if with case

switch(var) if (var == value1)


{ {
case value1: statements_1;
statements_1; }
break; else if (var == value2)
case value2: {
statements_2; statements_2;
break; }
... ...
default: else
statements; {
} statements
}

02/13/2021 ECE 175 37


Switch and if-else equivalence
#include<stdio.h>

int main(void)
{
int watts;

printf("Enter the bulb wattage (in Watts):");


scanf("%d", &watts); // user input stored in watts

if (watts == 15) // if watts = 15


printf("The bulb's brightness is 125 lumens\n"); // print 125
else if (watts == 25) // if watts = 25
printf("The bulb's brightness is 215 lumens\n"); // print 215
else if (watts == 40) // if watts = 40
printf("The bulb's brightness is 500 lumens\n"); // print 500
else if (watts == 60) // if watts = 60
printf("The bulb's brightness is 880 lumens\n"); // print 880
else if (watts == 75) // if watts = 75
printf("The bulb's brightness is 1000 lumens\n"); // print 1000
else if (watts == 100) // if watts = 100
printf("The bulb's brightness is 1675 lumens\n"); // print 1675
else
printf("The bulb's brightness is unknown\n"); // unknown brightness

return(0);
}
02/13/2021 ECE 175 38
Difference of switch with if-else
The if statement is more general than switch statement

Case labels can contain only integer or char values


Double, float and string values not permitted

Programming practice
Use switch statements when label contains a reasonable number of
integer( or char) values

02/13/2021 ECE 175 39


Exercise (more): Write C program for the flowchart below given that your program
- lets a user enter a person age and/or sts
- Displays a status of that person.

02/13/2021 ECE 175 40


Exercise (more): Write C program for the following
•Given
  a quadratic equation: , find the roots (values x) of this equation
given coefficient values a, b, c
Note: a user will enter values of a, b, c
No complex number answer

Sample code execution 1: Red entered by a user


First, analyze the problem This program is to find root(s) of y = ax^2 + bx + c
Inputs: Enter value of a, b and c (a b c):0 0 5
your equation: y = 5.00 has no root
Outputs:
Sample code execution 2:
Algorithm (Write a pseudo-code): This program is to find root(s) of y = ax^2 + bx + c
Enter value of a, b and c (a b c):0 4 5
root of y = 4.00x + 5.00 is -1.250
Test cases:
Sample code execution 3:
1) a = 0, b = 0, c = 5 This program is to find root(s) of y = ax^2 + bx + c
Enter value of a, b and c (a b c):1 4 5
2) a = 0 , b = 4, c = 5 there is no real-valued answer
3) a = 1, b = 4, c = 5 Sample code execution 4:
4) a = 1, b = -1, c = -6 This program is to find root(s) of y = ax^2 + bx + c
Enter value of a, b and c (a b c):8 -44 20
5) a = 8, b = -44, c = 20 roots of y = 8.00x^2 + -44.00x + 20.00 are 5.000 and 0.500

02/13/2021 ECE 175 41


Idea: find root(s) of y = ax2 + bx +c
When a = 0 and b = 0 => y = c
there is no value of x (no root)
When a = 0 => y = bx + c
the answer is x = -c/b

When all a, b, c are NOT 0


if(b^2 – 4ac > = 0)
x = ( -b + sqrt(b^2 – 4ac) )/ (2a)
x = ( -b - sqrt(b^2 – 4ac) )/ (2a)
else
there is no real-valued answer

02/13/2021 ECE 175 42

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy