0% found this document useful (0 votes)
11 views103 pages

C Overview

The document provides an overview of the C programming language, including essential chapters and learning outcomes. It covers key concepts such as data types, variable declarations, control structures, and input/output operations, along with examples and guidelines for writing C code. Additionally, it emphasizes the importance of proper coding practices and the use of comments for documentation.

Uploaded by

AbdullahLwayme
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)
11 views103 pages

C Overview

The document provides an overview of the C programming language, including essential chapters and learning outcomes. It covers key concepts such as data types, variable declarations, control structures, and input/output operations, along with examples and guidelines for writing C code. Additionally, it emphasizes the importance of proper coding practices and the use of comments for documentation.

Uploaded by

AbdullahLwayme
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/ 103

1

ICS 104 - Introduction to


Programming in Python and C
Overview of C Language
• Chapter 2: Sections 1-6
• Chapter 3: Section 1
• Chapter 4: Sections 1-4 and 7
• Chapter 5: Sections 1-8
2
Overview of C Language
• Reading Assignment from
"Problem Solving and Program Design in C"

• Chapter 2: Sections 1-6


• Chapter 3: Section 1
• Chapter 4: Sections 1-4 and 7
• Chapter 5: Sections 1-8
3
Overview of C Language
• Learning Outcomes
• become familiar with the general form of a C
program and the basic elements in a program.
• understand the use of data types and the differences
between the data types int, double and char.
• learn how C evaluates arithmetic expressions and
how to write them in C.
• develop C code using Control structures, conditions,
relational and logic operators.
• develop C code using The while, for and do-while
loops.
4
Why Learn C?
• Many companies and software projects do their
programming in C.
• C Produces optimized programs that run fast.
• Low-Level access to computer memory via pointers.
• Can be complied to run on a variety of computers.
5
C Language Compiler - Online
• You may use the online C compiler in
https://www.onlinegdb.com/online_c_compiler
6
C Language Example
7
C Language Example
/*
* Converts distance in miles to kilometers.
*/
#include <stdio.h> /* printf, scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constant */

int
main(void)
{
double miles, /* input - distance in miles. */
kms; /* output - distance in kilometers */

/* Get the distance in miles. */


printf("Enter the distance in miles> ");
scanf("%lf", &miles);

/* Convert the distance to kilometers. */


kms = KMS_PER_MILE * miles;

/* Display the distance in kilometers. */


printf("That equals %f kilometers.\n", kms);

return (0);
}
8
Preprocessor Directives
• Preprocessor directives are commands that give
instructions to the C preprocessor.
• Preprocessor is a system program that modifies a C
program prior to its compilation.
• Preprocessor directives begins with a #
• Example: #include or #define
9
#include
• #include is used to include other source files into your
source file.
• The #include directive gives a program access to a
library.
• Libraries are useful functions and symbols that are
predefined by the C language (standard libraries).
• Example: You must include stdio.h if you want to use
the printf and scanf library functions.
• #include<stdio.h> insert their definitions to your
program before compilation.
10
#define
• The #define directive instructs the preprocessor
to replace each occurrence of a text by a particular
constant value before compilation.
• #define replaces all occurrences of the text you
specify with value you specify
• Example:
#define KMS_PER_MILES 1.60
#define PI 3.14159
11
The “main” Function
12
The “main” Function
• The heading int main(void) marks the beginning of
the main function where program execution begins.
• Every C program has a main function.
• Braces ({,}) mark the beginning and end of the body of
function main.
• A function body has two parts:
• declarations - tell the compiler what memory cells are
needed in the function
• executable statements - (derived from the algorithm)
are translated into machine language and later executed
by the compiler.
13
Reserved words
• A word that has special meaning to C and can not be
used for other purposes.
• These are words that C reserves for its own uses
(declaring variables, control flow, etc.)
• For example, you couldn’t have a variable named
return
• Always lower case
• Appendix H has a list of them all (ex: double,
int, if , else, ...)
14
Reserved words
• Appendix H has a list of them all (ex: double,
int, if , else, ...)
15
Standard Identifiers
• Identifier - A name given to a variable or an operation
• In other words, Function names and Variable names
• Standard Identifier - An identifier that is defined in the
standard C libraries and has special meaning in C.
• Example: printf, scanf
• Standard identifiers are not like reserved words; you
could redefine them if you want to. But it is not
recommended.
• For example, if you create your own function called
printf, then you may not be able to access the
library version of printf.
16
User Defined Identifiers
• We choose our own identifiers to name memory cells that
will hold data and program results and to name operations
that we define (more on this in Chapter 3).
• Rules for Naming Identifiers:
• An identifier must consist only of letters, digits, and
underscores.
• An identifier cannot begin with a digit.
• A reserved word cannot be used as an identifier.
• A standard identifier should not be redefined.
• Valid identifiers: letter1, inches, KM_PER_MILE
• Invalid identifiers: 1letter, Happy*trout, return
17
Few Guidelines for Naming Identifiers
• Uppercase and lowercase are different
• LETTER != Letter != letter
• Avoid names that only differ by case; they can lead to
problems to find bugs
• Choose meaningful identifiers that are easy to understand.
Example: distance = rate * time
• means a lot more than x = y * z
• All uppercase is usually used for constant macros (#define)
• KMS_PER_MILE is a defined constant
• As a variable, we would probably name it KmsPerMile
or Kms_Per_Mile
18
Variables Declarations
• Variable – The memory cell used for storing a program’s
data and its computational results
• Variable’s value can change.
• Example: miles, kms
• Variable declarations
• Example: double miles
• Tells the compiler to create space for a variable of
type double in memory with the name miles.
• C requires you to declare every variable used in the
program.
19
Data Types
• Data Types: a set of values and a set of operations that
can be performed on those values
• int: Stores integer values – whole numbers
• 65, -12345
• double: Stores real numbers – numbers that use a
decimal point.
• 3.14159 or 1.23e5 (which equals 123000.0)
• char: An individual character value.
• Each char value is enclosed in single quotes. e.g. 'A', '*'.
• Can be a letter, a digit, or a special symbol
• Arithmetic operations (+, -, *, /) and compare can be
performed in case of int and double. Compare can be
performed in char data.
20
Executable Statements
• Executable Statements: C statements used to write or code the
algorithm. C compiler translates the executable statements to
machine code.
• Assignment Statements
• Input/Output Operations and Functions
• printf Function
• scanf Function
• return Statement
21
Hello World! Example
#include <stdio.h>
int main() {
// printf() displays the string inside
quotation
printf("Hello, World!");
return 0;
}
22
Key Points for Python Programmers
• The #include works like import in Python (not really,
but the analogy works for now) so in this case the
input/output stream library is brought in.
• The int main() begins the declaration of the main
function, which in C indicates the first function to be
executed, i.e., "begin here".
• In Python, main was the start of the program by convention
only.
• The curly braces { and } delimit the beginning and end of a
block of code (compound statement), in this case the
beginning and end of the function main .
• Python identifies blocks through indentation.
23
Assignment Statements
• Assignment statement - Stores a value or a
computational result in a variable

kms = KMS_PER_MILE * miles;

• The assignment statement above assigns a value to


the variable kms. The value assigned is the result of
the multiplication of the constant KMS_PER_MILE
by the variable miles.
24
Effect of kms = KMS_PER_MILE * miles;
25
More on Assignments
• In C the symbol = is the assignment operator
• Read it as ”becomes”, ”gets”, or ”takes the value of”
rather than ”equals” because it is not equivalent to the
equal sign of mathematics. In C, == tests equality.
• In C you can write assignment statements of the form:
sum = sum + item;
where the variable sum appears on both sides of the
assignment operator.
This statement instructs the computer to add the current
value of sum to the value of item; the result is then stored
back into sum.
26
Effect of sum = sum + item;
27
Input/Output Operations and Functions
• Input operation - data transfer from the outside world
into computer memory
• Output operation - program results can be displayed to
the program user
• Input/output functions - special program units that do
all input/output operations
• printf = output function
• scanf = input function
• Function call - in C a function call is used to call or
activate a function
• Calling a function means asking another piece of code to
do some work for you
28
The printf Function

function name function arguments

printf("That equals %f kilometers.\n", kms);

format string print list


place holder
29
Placeholders
• Placeholder always begins with the symbol %
• It marks the place in a format string where a value will
be printed out or will be inputted (in this case, kms)
• Format strings can have multiple placeholders, if you are
printing multiple values
Placeholder Variable Type Function Use
%c char printf/scanf
%d int printf/scanf
%f double printf
%lf double scanf
• newline escape sequence – '\n' terminates the current line
30
Displaying Prompts
• When input data is needed in an interactive
program, you should use the printf function to
display a prompting message, or prompt, that tells
the user what data to enter.

printf("Enter the distance in miles> ");


31
The scanf Function
• When user inputs a value, it is stored in variable miles.
• The placeholder type tells the function what kind of data to store
into variable miles.
function name
function arguments

scanf("%lf", &miles);

format string variable list


place holder
• The & is the C address of operator. The & operator in front
of variable miles tells the scanf function the location of
variable miles in memory.
32
Effect of scanf("%lf", &miles);
33
return Statement
return(0);
• Transfers control from your program to the operating
system.
• return(0) returns a 0 to the Operating System and
indicates that the program executed without error.
• It does not mean the program did what it was supposed to
do. It only means there were no syntax errors. There still
may have been logical errors.
• Once you start writing your own functions, you’ll use the
return statement to return information to the caller of
the function.
34
General Form of a C program
• Preprocessor directives are
instructions to C Preprocessor
to modify The text of a C
program before compilation.
• Every variable has to be
declared first.

• Executable statements are translated into machine


language and eventually executed.
• Executable statements perform computations on the
declared variables or input/output operations.
35
Comments
• Two forms of comments:
• /* */ - anything between them with be considered a
comment, even if they span multiple lines.
• // - anything after this and before the end of the line is
considered a comment.
• Comments are used to create Program Documentation
• Information that help others read and understand the
program.
• The start of the program should consist of a comment that
includes programmer’s name, date of the current version,
and a brief description of what the program does.
36
White Spaces
• The complier ignores extra blanks between words and
symbols, but you may insert space to improve the
readability and style of a program.
• You should always leave a blank space after a comma and
before and after operators such as , −, and =.
• You should indent the lines of code in the body of a
function.
37
White Space Examples
Bad: Good:
int main(void) int main(void)
{ int foo,blah; {
scanf("%d",&foo); int foo, blah;
blah=foo+1; scanf("%d", &foo);
printf("%d", blah); blah = foo + 1;
return 0;} printf("%d", blah);
return 0;
}
38
Other Styles Concerns
• Properly comment your code
• Give variables meaningful names
• Prompt the user when you want to input data
• Display things in a way that looks good
• Insert new lines to make your information more
readable.
• Format numbers in a way that makes sense for
the application
39
Bad Programming practices
• Missing statement of purpose
• Inadequate commenting
• Variables names are not meaningful
• Use of unnamed constant.
• Indentation does not represent program structure
• Algorithm is inefficient or difficult to follow
• Program does not compile
• Program produces incorrect results.
• Insufficient testing (e.g. Test case results are different than
expected, program branch never executed, borderline case
not tested etc.)
40
Arithmetic Expressions
• To solve most programming problems, you will need to
write arithmetic expressions that manipulate type int
and double data.
• The next slide shows all arithmetic operators. Each
operator manipulates two operands, which may be
constants, variables, or other arithmetic expressions.
• Example
•5+2
• sum + (incr * 2)
• (b / c) + (a + 0.5)
41
C Operators
Arithmetic Operator Meaning Examples
+ (int, double) Addition 5 + 2 is 7
5.0 + 2.0 is 7.0
- (int, double) Subtraction 5 - 2 is 3
5.0 - 2.0 is 3.0
* (int, double) Multiplication 5 * 2 is 10
5.0 * 2.0 is 10.0
/ (int, double) Division 5 / 2 is 2
5.0 / 2.0 is 2.5
% (int) Remainder 5 % 2 is 1
42
Operators / and %
• Division: When applied to two integers, the division operator (/)
computes the integral part of the result by dividing its first operand
by its second.
• Example: 7.0 / 2.0 is 3.5 but 7 / 2 is only 3
• The reason for this is that C makes the answer be of the same
type as the operands.
• Remainder: The remainder operator (%) returns the integer
remainder of the result of dividing its first operand by its second.
• Examples: 7 % 2 = 1, 6 % 3 = 0
• The value of m % n must always be less than the divisor n.
• / & % are undefined when the divisor (second operator) is 0.
43
Data Type of an Expression
• The data type of each variable must be specified in its
declaration.
• The data type of an expression depends on the type(s) of
its operands.
• If both are of type int, then the expression is of type
int.
• If either one or both is of type double, then the
expression is of type double.
• An expression that has operands of both int and double
is a mixed-type expression.
44
Mixed-Type Assignment Statement
• The expression being evaluated and the variable to which
it is assigned have different data types.
• y = 5/2 what is the value of y if y is of type double?
• When an assignment statement is executed, the expression
is first evaluated; then the result is assigned to the variable
to the left side of assignment operator.
• Warning: assignment of a type double expression to a
type int variable causes the fractional part of the
expression to be lost.
• y = 5.0 / 2.0 when y is of type int?
45
Type Conversion Through Casts
• C allows the programmer to convert the type of an
expression.
• This is done by placing the desired type in parentheses
before the expression.
• This operation called a type cast.
• (double)5 / (double)2 is the double value 2.5,
and not 2 as seen earlier.
• (int)3.0 / (int)2.0 is the int value 1
• When casting from double to int, the decimal portion is
just truncated – not rounded.
46
Example
#include <stdio.h>
int main(void)
{
int total_score, num_students;
double average;
printf("Enter sum of students' scores> ");
scanf("%d", &total_score);
printf("Enter number of students> ");
scanf("%d", &num_students);
average = (double) total_score / (double)
num_students;
printf("Average score is %.2f\n", average);
return (0);
}
47
Expressions with Multiple Operators
• Operators can be split into two types: unary and binary.
• Unary operators take only one operand
• - (negates the value it is applied to)
• Binary operators take two operands.
• +, -, *, /
• A single expression could have multiple operators
• -5 + 4 * 3 - 2
48
Rules for Evaluating Expressions
• Parentheses rule - All expressions in parentheses must
be evaluated separately.
• Nested parenthesized expressions must be evaluated
from the inside out, with the innermost expression
evaluated first.
• Operator precedence rule – Multiple operators in the
same expression are evaluated in the following order:
• First: unary –
• Second: *, /, %
• Third: binary +,-
49
Rules for Evaluating Expressions
• Associativity rule
• Unary operators in the same subexpression and
at the same precedence level are evaluated right
to left
• Binary operators in the same subexpression and
at the same precedence level are evaluated left to
right.
Evaluation Tree for 50
area = PI * radius * radius;
51
Step-by-Step Expression Evaluation
Evaluation Tree and Evaluation for v = (p2 - p1) / (t2 - t1);52
Evaluation Tree and Evaluation for z - (a + b / 2) + w * -y 53
Formatting Numbers in Program Output (for integers) 54
• You can specify how printf will display numeric values
• Use d for integers. %#d
• % - start of placeholder
• # - field width (optional) – the number of columns to
use to display the output.
• If # is less than the integer size, it will be ignored
• If # is greater than the integer size, extra spaces will
be added on the left
Formatting Numbers in Program Output (for integers) 55
Formatting Numbers in Program Output (for double) 56

• Use %n.mf for double


• % - start of placeholder
• n - field width (optional)
• It is equal to the number of digits in the whole
number, the decimal point and fraction digits
• If n is less than what the real number needs it
will be ignored
• m – Number of decimal places (optional)
Formatting Numbers in Program Output (for double)57
58
Objectives
• Control Structures
• Conditions
• Relational Operators
• Logical Operators
• if statements
• Two-Alternatives
• One-Alternative
• Nested If Statements
59
Control Structures
• Control structures –control the flow of
execution in a program or function.
• Three basic control structures:
• Sequential Flow - this is written as a
group of statements bracketed by { and }
where one statement follows another.
C
• Selection control structure - this chooses Y N
between multiple statements to execute
based on some condition. Y
C
• Repetition – this structure executes a N
block of code multiple times.
60
Compound Statements
• A Compound statement or a Code Block is written as
a group of statements bracketed by { and } and is
used to specify sequential flow.
{
Statement_1;
Statement_2;
Statement_3;
}
• Example: the main function is surrounded by { },
and its statements are executed sequentially.
• Function body also uses compound statement.
61
Conditions
• A program chooses among alternative statements by testing the
values of variables.
• 0 means false
• Any non-zero integer means true, Usually, we'll use 1 as true.
if (a >= b)
printf ("a is larger");
else
printf ("b is larger");
• Condition - an expression that establishes a criterion for either
executing or skipping a group of statements
• a >= b is a condition that determines which printf statement
we execute.
62
Relational and Equality Operators
• Most conditions that we use to perform
comparisons will have one of these forms:
• variable relational-operator variable e.g. a < b
• variable relational-operator constant e.g. a > 3
• variable equality-operator variable e.g. a == b
• variable equality-operator constant e.g. a != 10
63
Relational and Equality Operators
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
64
Logical Operators
• logical expressions - expressions that use conditional
statements and logical operators.
• && (and)
• A && B is true if and only if both A and B are true
• || (or)
• A || B is true if either A or B are true
• ! (not)
• !(condition) is true if condition is false, and false
if condition is true
• This is called the logical complement or negation
65
Logical Operators
• Example
• (salary < 10000 || dependents > 5)
• (temperature > 90.0 && humidity > 90)
• !(temperature > 90.0)
66
Truth Table && Operator
A B A && B

False (zero) False (zero) False (zero)

False (zero) True (non-zero) False (zero)

True (non-zero) False (zero) False (zero)

True (non-zero) True (non-zero) True (1)


67
Truth Table || Operator
A B A || B
False (zero) False (zero) False (zero)
False (zero) True (non-zero) True (1)
True (non-zero) False (zero) True (1)
True (non-zero) True (non-zero) True (1)
68
Operator Table ! Operator

A !A

False (zero) True (non-zero)

True (non-zero) False (zero)


69
Remember!
• && operator yields a true result only when both its
operands are true.
• || operator yields a false result only when both its
operands are false.
70
Operator Precedence
• The order of execution. Use parenthesis to clarify
the meaning of expression.
• Relational operator has higher precedence than
logical operators.
• Ex: followings are different.
• (x < y || x < z) && (x > 0.0)
• x < y || x < z && x > 0.0
71
Operator Precedence
• function calls
• !, +, -, & (unary operations)
• *, /, %
• +, -
• <, >, <=, >=
• ==, !=
• &&
• ||
•=
72
Evaluation Tree and Step-by-Step
• Evaluation for !flag || (y + z >= x - z)
73
Writing English Conditions in C
• Make sure your C condition is logically equivalent to
the English statement.
• "x and y are greater than z"
• (x > z) && (y > z) (valid)
• x && y > z (invalid)
74
Character Comparison
• C allows character comparison using relational and
equality operators.
• During comparison Lexicographic (alphabetical)
order is followed. (See Appendix A for a complete
list of ASCII values).
• '9' >= '0' // True
• 'a' < 'e' // True
• 'a' <= ch && ch <= 'z' /* True if ch is a char type
variable that contains a lower case letter.*/
75
Logical Assignment
• You can assign an int type variable a nonzero value
for true or zero for false.
Ex: even = (n % 2 == 0)
if (even) { do something }
• Some people prefer following for better readability.
#define FALSE 0
#define TRUE !FALSE
even = (n%2 == 0)
if (even == TRUE) { do something }
76
if statement : Two alternatives
if (condition)
{compound_statement_1 } // if condition is true
else
{ compound_statement_2 } // if condition is false
Example:
if (crash_test_rating_index <= MAX_SAFE_CTRI) {
printf("Car #%d: safe\n", auto_id);
safe = safe + 1;
}
else {
printf("Car #%d: unsafe\n", auto_id);
unsafe = unsafe + 1;
}
77
if statement : Two alternatives…
• When the symbol { follows a condition or else, the C
complier either executes or skips all statements through
the matching }
• In the example of the previous slide, if you omit the
braces enclosing the compound statements, the if
statement would end after the first printf call.
• The safe = safe + 1; statement would always be executed.
• You MUST use braces if you want to execute a compound
statement in an if statement.
• To be safe, you may want to always use braces, even if
there is only a single statement.
78
No { }?
if (rest_heart_rate > 56)
printf("Keep up your exercise program!\n");
else
printf("Your heart is in excellent health!\n");

• If there is only one statement between the { }


braces, you can omit the braces.
79
One Alternative?
• You can also write the if statement with a single
alternative that executes only when the condition is
true.
if ( a <= b )
statement_1;
80
Nested if Statements
• So far, we have used if statements to code decisions with
one or two alternatives.
• A compound statement may contain more if statements.
• In this section we use nested if statements (one if
statement inside another) to code decisions with multiple
alternatives.
if (x > 0)
num_pos = num_pos + 1;
else
if (x < 0)
num_neg = num_neg + 1;
else
num_zero = num_zero + 1;
81
Multiple-Alternative Decision Form of Nested if
• Nested if statements can become quite complex. If
there are more than three alternatives and
indentation is not consistent, it may be difficult for
you to determine the logical structure of the if
statement.
• You can code the nested if as the multiple-
alternative decision described below:
82
Multiple-Alternative Decision Form of Nested if
if ( condition_1 )
statement_1
else if ( condition_2 )
statement_2
.
.
.
else if ( condition_n )
statement_n
else
statement_e
83

Repetition and Loop Statements


84
The While Statement
• Computes and displays the gross pay for seven employees.
count_emp = 0;
while (count_emp < 7) // Missing:
{ int count_emp;
printf("Hours> "); int hours;
scanf("%d",&hours);
double rate, pay;
printf("Rate> ");
scanf("%lf",&rate);
pay = hours * rate;
printf("Pay is $%6.2f\n", pay);
count_emp = count_emp + 1;
}
printf("\nAll employees processed\n");
85
While Statement
• General form:
While (loop repetition condition)
{
//Steps to perform. These should eventually
//result in condition being false
}
• Syntax of the while Statement:
• Initialization. i.e. count_emp = 0;
• Testing. i.e. count_emp < 7
• Updating i.e. count_emp = count_emp + 1;
• The above steps must be followed for every while loop.
• If any of these are skipped it may produce an infinite loop
86
While Statement
• Syntax of the while Statement:
• Initialization. i.e. count_emp = 0;
• Testing. i.e. count_emp < 7
• Updating i.e. count_emp = count_emp + 1;
• The above steps must be followed for every while
loop.
• If any of these are skipped it may produce an
infinite loop
Computing Sum
/* computes the sum: 1 + 2 + 3 + ....+ 100 */
#include <stdio.h>
int main(void) {
int sum = 0, i = 1;
while (i <= 100) {
sum = sum + i;
i = i + 1;
}
printf("Sum is %d\n", sum);
return 0;
} 87
88
Compound Assignment Operators
• Several times we have seen:
variable = variable <operator>
expression;
Example: sum = sum + i;
• where <operator> is a C operator
• This occurs so often; C gives us short cuts.
• Instead of writing x = x + 1
• we can write: x += 1.
• W can use -=, *=, /=, and %= in the same way
89
The For Statement
• C provides the for statement as another form for
implementing loops.
• As before we need to
• Initialize the loop control variable
• Test the loop repetition condition
• Update the loop control variable.
• A feature of the for statement in C is that it supplies a
designated place for each of these three components.
90
For Example
• To compute the sum of 1 to 100:
int sum = 0;
int i;
for (i = 1; i <= 100; i++)
{
sum = sum + i;
}
• Note: i++ is the same as i = i + 1
and as i += 1.
91
General Form of For statement
for (initialize; test; update)
{
//Steps to perform each iteration
}
• First, the initialization expression is executed.
• Then, the loop repetition condition is tested.
• If the condition is true, the statement enclosed in { } are
executed.
• After that, the update expression is evaluated.
• Then the loop repetition condition is retested.
• The statement is repeated as long as the condition is true.
• for loop can be used to count up or down by any interval.
92
Increment and Decrement Operators
• The counting loops that we have seen have all
included assignment expressions of the form
counter = counter + 1
or
counter++
or
counter += 1
• This will add 1 to the variable counter. If we use -
instead of +, it will subtract 1 from the variable
counter.
• Be careful about using the ++ or -- options.
93
Increment and Decrement Other Than 1
• Instead of adding just 1, we can use
sum = sum + x or sum += x
• Both of these will take the value of sum and add x
to it and then assign the new value to sum.
• We can also use temp = temp - x or temp -=
x
• Both of these will take the value of temp and
subtract x from it and then assign the new value to
temp.
94
Prefix and Postfix Increment/Decrement
• The values of the expression in which the ++ operator
is used depend on the position of the operator.
• When the ++ operator is placed immediately in front of
its operand (prefix increment, Ex: ++x), the value of the
expression is the variable's value after incrementing.
• When the ++ operator is placed immediately after the
operand (postfix increment , Ex: x++), the value of the
expression is the value of the variable before it is
incremented.
95
• If n = 4, what will be the output of the following?

printf("%3d", -- printf("%3d",
n); n--);
printf("%3d", n); printf("%3d", n);

3 3 4 3
Nested for loops 96
/* Illustrates a pair of nested counting loops */ //output:
#include <stdio.h> I
int main(void) J
{
Outer 1
int i, j;
printf(" I J\n"); Inner
for (i = 1; i < 4; ++i) { 0
printf("Outer %6d\n", i); Outer 2
for (j = 0; j < i; ++j) { Inner
printf(" Inner%9d\n", j);0
} Inner
} 1
return (0); Outer 3
}
Inner
0
Inner
97
Do While statement
• Both the for statement and the while statement
evaluate the loop condition before the first
execution of the loop body.
• In most cases, this pretest is desirable and prevents
the loop from executing when there may be no data
items to process
• There are some situations, generally involving
interactive input, when we know that a loop must
execute at least one time.
98
Do-While Example do {
#include <stdio.h>
#define KMS_PER_MILE 1.609 ---
/* converts miles to kilometers - repeateadly */
int main(void) { ---
double kms, miles;
char res; //for user response [y/n]} while
do { (Condition);
printf("Enter the distance in miles> ");
scanf("%lf", &miles);
kms = KMS_PER_MILE * miles;
printf("That equals %f kilometers. \n", kms);
printf("\nDo you wish to try again [y/n]? ");

getchar(); //skips the new line character.


scanf("%c", &res);
} while (res == 'Y' || res == 'y');
return (0);
}
99
Do-While Example
do {
printf("Enter the distance in miles> ");
scanf("%lf", &miles);
kms = KMS_PER_MILE * miles;
printf("That equals %f kilometers. \n", kms);
printf("\nDo you wish to try again [y/n]?
");
getchar(); //skips the new line character.
scanf("%c", &res);
} while (res == 'Y' || res == 'y');
100
Do-While Example
• check validity of input. n_min must be < n_max
#include <stdio.h>
int main () {
int n_min, n_max, inval;
do {
printf("Enter minimum and maximum valid values> " );
scanf("%d%d", &n_min, &n_max);
if(n_min >= n_max)
printf("Wrong input\n");
} while (n_min >= n_max);
// condition of while is true as long as the input is wrong
}
101
Functions
#include <stdio.h>
int factorial (int n) ; /* function prototype (declaration) */
int main(void)
{
int x, fact_x;
printf("Enter the value of x: ");
scanf("%d", &x);
fact_x = factorial(x);
printf("The factorial of %d = %d\n", x, fact_x);
return (0);
}
/*
* Computes n!
* Pre: n is greater than or equal to zero
*/
int factorial(int n)
{
int i, /* local variables */
product; /* accumulator for product computation */
product = 1;
/* Computes the product n x (n-1) x (n-2) x . . . x 2 x 1 */
for (i = n; i > 1; --i) {
product = product * i;
}
/* Returns function result */
return (product);
}
102
Functions
103
Functions

You might also like