[go: up one dir, main page]

0% found this document useful (0 votes)
51 views38 pages

Programming For Engineers: Chapter 2 Introduc7on To C Programs

The document introduces the C programming language and provides an overview of programming in C for engineers. It discusses why C is commonly used, outlines the program development cycle of designing, writing, testing and debugging code, and covers basic C programming concepts such as program structure, variables and constants, data types, operators, and assignment statements. The document aims to teach readers how to solve problems computationally and code in C.

Uploaded by

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

Programming For Engineers: Chapter 2 Introduc7on To C Programs

The document introduces the C programming language and provides an overview of programming in C for engineers. It discusses why C is commonly used, outlines the program development cycle of designing, writing, testing and debugging code, and covers basic C programming concepts such as program structure, variables and constants, data types, operators, and assignment statements. The document aims to teach readers how to solve problems computationally and code in C.

Uploaded by

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

Programming

for Engineers

Chapter 2
Introduc7on to C Programs

Why C?
Advantages:
Flexible language
Development of applica7ons from embedded systems and
opera7ng systems to industrial applica7ons

Fast execu7on
Small language, i.e. its vocabulary consists of a few words
with special meanings
Portable; can be run across dierent opera7ng systems
Language that is close to the hardware
First step towards object oriented programming
C features are mostly supported in several object-oriented
languages such as C++, Java, C#

For this subject


You are going to learn:
Approaches to solve problem computa7onally
Grammars of C language

Ul7mately, our aim is to:


Able to code!

Program development cycle

Design the
program

Write the
code

Correct
syntax
errors

Test the
executable
code

Debug the
code

Designing a program
Understand the task that the program needs to
perform
Gathering informa7on/specica7ons

Determine the steps that must be taken to


perform the task
Break down the task into series of steps
(algorithms)
Determine inputs, outputs and processes involved

Example
Write a program to calculate and display the
gross pay for an hourly paid employee
Algorithms:
1. Get the number of hours worked
2. Get the hourly pay rate
3. Mul7ply the number of hours worked by the hourly
pay rate
4. Display the result of the calcula7ons that was
performed in Step 3

Input, outputs and processes

Hours worked
Gross pay
Hourly pay rate

Algorithms and pseudocode


Algorithms needs to be translated into codes
Pseudocode
Flowcharts

Pseudocodes
Informal language that has no syntax rules
Is not meant to be compiled or executed
Can be translated directly to actual codes

Example:
Display Enter the number of hours the employee
worked
Input hours
Display Enter the employees hourly pay rate
Input payRate
Set grossPay = hours * payRate
Display The employees gross pay is $ ,
grossPay

Flowcharts
Start
Display Enter the number of
hours the employee worked
Input hours
Display Enter the employees
hourly pay rate
Input payRate
Set grossPay = hours * payRate
Display The employees gross
pay is $ , grossPay

End

Program Structure

Program Structure - General Form


preprocessing directives
int main()
{
/*declarations*/
/*statements */
return 0;
}

Program Structure
Comments begin with the characters /* and end
with the characters */
Preprocessor direc7ves give instruc7ons to the
compiler
#include <stdio.h>
#define PI 3.142
Preprocessor direc7ves do not end with a
semicolon
Every C program contains one func7on named
main
The body of the main func7on is enclosed by
braces { }

Program Structure
The main func7on contains two types of commands:
declara7ons and statements
Declara7ons and statements are required to end with
a semicolon ;
To exit the program, use a return 0; statement

Program Structure - First C Program


/******************************************************************/
/* Program chapter1
*/
/*
/*

This program computes the sum two numbers

#include <stdio.h>
int main(void)
{
/* Declare and initialize variables. */
double number1 = 473.91, number2 = 45.7, sum;
/* Calculate sum. */
sum = number1 + number2;
/* Print the sum. */
printf(The sum is %f \n, sum);
/* Exit program.
return 0;
}

*/

*/

Constants and Variables

Variables and constant


A variable is a memory loca7on that is assigned a name or
an iden+er
An iden7er is used to reference a memory loca7on.
Rules for selec7ng a valid iden7er
must begin with an alphabe7c character or underscore
may contain only lecers, digits and underscore (no special
characters)
case sensi7ve
can not use keywords as iden7ers
A variable whose value cannot change during the execu7on of a
program is called a constant
const int a =

20;

C Data Types
Integers
short
int
long

Floa7ng-Point Values
float
double
long double

Characters
char

Symbolic Constants
Dened with a preprocessor direc7ve
Compiler replaces each occurrence of the
direc7ve iden7er with the constant value in
all statements that follow the direc7ve
Example:
#define PI 3.141593

Assignment Statements

Assignment Statements
Used to assign a value to a variable
General Form:
identifier = expression;
Example 1
double sum = 0;
Example 2
int x;
x = 5;
Example 3
char ch;
ch = a;

Assignment Statements
Example 4
int
x =
z =
y =

x, y, z;
y = 0;
2;
z;

Arithme7c Operators

Addi7on
Subtrac7on
Mul7plica7on
Division /
Modulus

+
-
*
%

Modulus returns remainder of division between two integers


Example

5%2 returns a value of 1

Integer Division
Division between two integers results in an
integer
The result is truncated, not rounded
Example:
5/3 is equal to 1
3/6 is equal to 0

Priority of Operators
1 Parentheses Inner most rst
2 Unary operators Right to lei
(+ -)

3 Binary operators Lei to right


(* / %)

4 Binary operators Lei to right


(+ -)

Increment and Decrement Operators


Increment Operator ++
post increment x++;
pre increment ++x;

Decrement Operator - -
post decrement x- -;
pre decrement - -x;

Abbreviated Assignment Operator


operator example equivalent statement

+=
-=
*=
/=
%=

x+=2;
x-=2;
x*=y;
x/=y;
x%=y;

x=x+2;
x=x-2;
x=x*y;
x=x/y;
x=x%y;

Operator precedence

hcp://en.cppreference.com/w/c/language/operator_precedence

Standard Input and Output

Standard Output
printf func7on
prints informa7on to the screen
requires two arguments
control string
conversion specier
Example:
double angle = 45.5;
printf(Angle = %.2f degrees \n,
angle);


Output:

Angle = 45.50 degrees

Standard Input
scanf Func7on
inputs values from the keyboard
required arguments
control string
memory loca7ons that correspond to the speciers
in the control string, given by &

Example:
double distance;
char unit_length;
scanf("%1f %c", &distance, &unit_length);

It is very important to use a specier that is


appropriate for the data type of the variable

Data type and format specier

hcps://en.wikipedia.org/wiki/C_data_types

Prac7ce!
Assume that the integer variable sum contains the value 65,
the double variable average contains the value 12.368 and
that the char variable ch contains the value 'b'. Show the
output line (or lines) generated by the following statements.

printf("Sum = %5i; Average = %7.1f

\n", sum,

average);
printf("Sum = %4i \n Average = %8.4f \n", sum,
average);
printf("Sum and Average \n\n %d %.1f \n", sum,
average);
printf("Character is %c; Sum is %c \n", ch, sum);
printf("Character is %i; Sum is %i \n", ch, sum);

Library Func7ons

Math Func7ons
fabs(x)
Absolute value of x.
sqrt(x)
Square root of x, where x>=0.
pow(x,y)
Exponentiation, xy. Errors occur if x=0 and y<=0, or if x<0 and
y is not an integer.
ceil(x)
Rounds x to the nearest integer toward (infinity). Example,
ceil(2.01) is equal to 3.
floor(x)
Rounds x to the nearest integer toward - (negative infinity).
Example, floor(2.01) is equal to 2.
exp(x)
Computes the value of ex.
log(x)
Returns ln x, the natural logarithm of x to the base e. Errors
occur if x<=0.
log10(x)
Returns log10x, logarithm of x to the base 10. Errors occur if
x<=0.

Trigonometric Func7ons
sin(x)
Computes the sine of x, where x is in radians.
cos(x)
Computes the cosine of x, where x is in radians
tan(x)
Computes the tangent of x, where x is in radians.
asin(x)
Computes the arcsine or inverse sine of x, where x must be in the
range [-1, 1]. Returns an angle in radians in the range [-/2,/2].
acos(x)
Computes the arccosine or inverse cosine of x, where x must be in
the range [-1, 1]. Returns an angle in radians in the range [0, ].
atan(x)
Computes the arctangent or inverse tangent of x. Returns an angle in
radians in the range [-/2,/2].
atan2(y,x)
Computes the arctangent or inverse tangent of the value y/x. Returns
an angle in radians in the range [-, ].

Character Func7ons
toupper(ch)
isdigit(ch)
islower(ch)
isupper(ch)
isalpha(ch)
isalnum(ch)

If ch is a lowercase letter, this function returns the


corresponding uppercase letter; otherwise, it returns ch
Returns a nonzero value if ch is a decimal digit; otherwise, it
returns a zero.
Returns a nonzero value if ch is a lowercase letter; otherwise,
it returns a zero.
Returns a nonzero value if ch is an uppercase letter;
otherwise, it returns a zero.
Returns a nonzero value if ch is an uppercase letter or a
lowercase letter; otherwise, it returns a zero.
Returns a nonzero value if ch is an alphabetic character or a
numeric digit; otherwise, it returns a zero.

Exercises

You might also like