SlideShare ist ein Scribd-Unternehmen logo
1 von 299
www.cyberlabzone.com
C Programming
www.cyberlabzone.com
Topics for C Language
1.Introduction to C language
2.Programming Languages
3.Data Types
4.Basic Input/Output (I/O)
5.Control Constructs
6.Array
7.Fuctions
8.Program Design Example
9.Pointers
10.Structures & Unions
11.File Operation in C
12.The C Preprocessor
13.Computational Complexity
www.cyberlabzone.com
Introduction to C languages
C is a traditional, Procedural language,i.e. one that requires the programmer to
provide step-by-step instructions for the processor (i.e., the main logic unit of a
computer).
The great success of C is due to its simplicity, efficiency,
flexibility and small memory requirements. It is also due to the portability of
programs that are written in it, i.e., the ability to be easily adapted to new
platforms (i.e., operating systems and processors).
C's great portability is in very large part a result of the fact that
compilers and libraries are available for numerous platforms. A compiler is a
specialized computer program that converts source code (i.e., the original,
human-readable form of a program typed into a computer by a programmer in a
programming language) into another language, usually machine language (also
called object code or machine code) so that it can be directly understood by
processors. A library is a collection of routines (also called subprograms,
procedures or functions) that perform operations which are commonly required
by programs.
www.cyberlabzone.com
Programming Languages
Programming Languages classified as ”Low Level/High Level”
1.Low Level
•Machine Language
(binary-based code; machine dependent)
• Assembly Language
(mnemonic form of machine language)
2.High Level
Closer to natural languages.
Generally, machine independent
Usually, several machine instructions are combined into one high-
level instruction.
Examples:
FORTRAN, COBOL,BASIC, Java, Pascal, Ada, PL/I, Lisp, C
GPSS,C++, Matlab
www.cyberlabzone.com
Processing a High-level Language
Program
Programs written in high-level languages must be converted to
machine language.
Two approaches:
(1) Compilation used with C, C++, Fortran,...
(2) Interpretation
Used with Matlab, Visual Basic,...
www.cyberlabzone.com
STEP 1) Use Dos Prompt to create a “Directory”. In this Directory
We write and save all Programme name source files with a suffix “.c”.
STEP 2)In Dos Prompt to compile the desired Programme we use “Ctrl
+F9” to get a desired result While programme is on the monitor .
STEP 3) Check the error if any caught by compiler, remove
that error and go back to step 2,repeat whole process again.
STEP 4) Run the program by using “Ctrl+F9” and for
OUTPUT we use “Alt+F5”
in the Dos prompt.
Compilation (In Window Environment)
www.cyberlabzone.com
C Program Examples
1. Requirements Specification (Problem Definition)
Write a simple C program to request the users’ SSN and print the message “Hello
(SSN)!” (where SSN is the value the user supplied) to the screen of the computer
monitor.
2. Analysis---Refine, Generalize, Decompose the problem definition
(i.e., identify sub problems, I/O, etc.)
Input = SSN
Output= A prompt for the SSN then
“Hello (SSN)!”
3. Design---Develop Algorithm
Pseudo-code Algorithm
print “Enter SSN (no dashes)”
read SSN
print “Hello (SSN) !”
4. Implementation --- Write the "Program" (Code)
www.cyberlabzone.com
C Examples
/* C Program to greet the user */
#include <stdio.h> /* makes the function printf “known” */
/* to the C compiler */
void main(void)
{
int ssn; /* variable ssn declared */
printf(”Please enter your SSN (no dashes):”);
scanf(”%d”,&ssn); /* read the SSN */
printf(”Hello %d !n”,ssn); /* print the message */
}
www.cyberlabzone.com
Main Function
#include ... /* preprocessor directive */
.
.
.
void main(void) /*function header*/
{ .
. /* function body */
.
}
In the following set of slides we will define the
component parts of the main function.
www.cyberlabzone.com
Preprocessor Directives
#include ... /* preprocessor directive */
.
.
.
void main(void)
{ .
.
.
}
Statements beginning with the symbol # are called preprocessor
directives. The #include directives allow the C program to access
libraries of functions that are not available directly in C. These
libraries are referred to as header files:
stdio.h standard input-output functions
math.h math functions
stdlib.h a “standard” library of functions
www.cyberlabzone.com
Main Function Header
#include ...
.
.
.
void main(void) /*function header*/
{ .
.
.
}
The “initial” input is any value(s) passed at initial execution, e.g.
>a.out 1.0 3.5
Typing the above at the Unix prompt attempts to pass the values 1.0
and 3.5 to main. At this point we will not do this. The header for the
programs in some C programs is of the form:
int main(void)
and there is a corresponding statement in the function body:
return (0);
main has no
“initial” input
values. (see
below)
main function
returns no value
www.cyberlabzone.com
Main Function (body)
#include ...
.
.
.
void main(void)
{ .
. /* function body */
.
}
• The body of a function is all the declarations and executable
statements between the braces (in the block). The declarations
must precede the executable statements in this block.
• When you run a program, the first statement executed is the first
(from the top of the file) executable statement in main. The
execution of statements proceeds until the terminating “}” right
brace is encountered or a return statement is executed.
a “block” in C is
defined by a set
of curly braces.
www.cyberlabzone.com
Declaration
#include <stdio.h>
void main(void)
{
int ssn; /* variable ssn declared */
printf(”Please enter your SSN (no dashes):”);
scanf(”%d”,&ssn);
printf(”Hello %d !n”,ssn);
}
One form of a declaration in C :
data-type variable_name ;
www.cyberlabzone.com
Data Types
Fixed Point(Integers) Floating Point Character
short float char
int
double
long
long double
www.cyberlabzone.com
Variable Names
Variable Names - reference to memory locations storing data values.
A variable name is one example of an identifier in C.
An identifier can use a combination of letters, numerical digits, and
the underscore ( _ ) that starts with a letter. Only the first 31
characters of an identifier are recognized by most compilers.
Identifiers cannot be the same as a reserved word or keyword, such as
void, float, or return. Examples: x sum force2
rate_Of_Change
Examples of invalid variable names (why?):
2force rate-of-change x.5 return
C case-sensitive, so that the following three names all represent
different variables (i.e., different storage locations):
time Time TIME
www.cyberlabzone.com
#include <stdio.h>
void main(void)
{
int ssn;
printf(”Please enter your SSN (no dashes):”);
scanf(”%d”,&ssn);
printf(”Hello %d !n”,ssn);
}
The printf and scanf functions appear in
‘expression’ statements.
1st executable
statement
3rd executable
statement
2nd executable
statement
Executable Statements
www.cyberlabzone.com
Executable Statements
Statements are grouped by their type:
expression statement
do-while and while statements
for statement
if and if-else statements
return statement
switch statement
assignment statement
Every executable statement in C must be followed
by a “ ; “ semicolon.
www.cyberlabzone.com
Assignment Statement
•Interpretation: compute the value on the
right-hand-side of the = and put this value in memory at
location named (or tagged) by the name variable .
• an expression can be a constant, a variable or
operators with operands.
variable = expression;
www.cyberlabzone.com
Constants
Literal Constants(examples)
Numeric: 3 6.248 -7.25 1.5e4 (=15000)
Single Character: 'A' 'a' '9' '+' ' '
Character String: “Enter a positive number: ”
Symbolic Constants(example)
#define PI 3.14159265 /* preprocessor directive */
By default, constants declared in #define are of type
double.
Standard practice is to use all upper-case letters for the
constant name, to avoid confusion with a variable name.
A “constant” means you cannot change the value, e.g.
PI = 3.0;
will generate a compiler error from gcc.
www.cyberlabzone.com
Arithmetic Operators
- for integer arithmetic, the / operator yields an integer result, and
% gives the remainder after dividing two integers. E.g.,
5 / 3 1 5 / 6 0
5 % 3 2 5 % 6 5
(Note: division by 0 creates an "overflow" run-time error.)
- use arithmetic operators, with parentheses for grouping; e.g., (a
- b) / (2 * c)
e.g, without parentheses, the example above would evaluate b/2
first, then do the multiplication, then the subtraction.
+, - , * , / , % (modulus) (no ^ operator as in Matlab)
www.cyberlabzone.com
Rules of Precedence
( ) Higher
*, /, % (left to right for tie)
+, - (left to right for tie) Lower
Examples,
: x = 3 + 2 * 3; /* x now has the value 9 */
y = 3 * 2 % 3; /* y now has the value 0 */
- Precedence Order for Arithmetic Operators:
www.cyberlabzone.com
Understanding the Assignment
statement
• Example
int time;
.
.
.
time = 0;
.
0time
1200
Main Memory
Memory map after the
assignment statement
time = 0 is executed
.
unknowntime
1200
Main Memory
Memory map before the
assignment statement
time = 0 is executed
www.cyberlabzone.com
Understanding the Assignment
statement
• Example
double force;
force = 5.0;
.
.
.
force = force * 3.0;
.
15.0force
1400
Main Memory
Memory map after the
assignment statement
force = force * 3.0;
is executed
.
5.0force
1400
Main Memory
Memory map before the
assignment statement
force = force * 3.0;
but after
force = 5.0;
is executed
www.cyberlabzone.com
Character Values
Individual characters may be assign to variables of data-type
char.
Example: Write a program to prompt the user for a Y/ N
response. Print the users response to the screen.
#include <stdio.h>
void main(void)
{
char letter;
printf(“Please enter a response (Y/N):”);
scanf(“%c”,&letter);
printf(“Your response was: %c n”,letter);
}
www.cyberlabzone.com
Expression Statements
One form of a expression statement in C :
function(argument list) ;
Scanf function
accepts input from standard input device,
usually a keyboard
scanf("format string", &var1, &var2, ...);
The number of conversion specifiers should match the
number of variables that follow the “format string”.
%i,%d - decimal integer (d=decimal)
%f - float
%lf - double(where lf="long float")
%Lf - long double
%c - character
where “format string” is the string of conversion
specifiers for the various data types in the variable list.
e.g.,
www.cyberlabzone.com
Basic Input/Output (I/O)
sends output to standard output device,
usually a video monitor
printf("format string", output-list);
where ”format string” can contain characters to be output
and the conversion specifiers indicating type and position
of the output values. For output, we specify formats
conversion specifiers) a little differently than we do for
input. For example:
%i, %d -decimal integer
%o -octal integer
%x, %X -hex integer (use X for caps A - F)
%f -float, double
%c -character
%s -character string
Printf function
www.cyberlabzone.com
Output Control: Special characters
Each is represented by an escape sequence,
which is a backslash () and an escape character.
Examples are:
" - output double quotes
b – backspace
? - output question-mark character (?)
 - output backslash character ()
n - new line
www.cyberlabzone.com
Output Control: Field Width
The number of print positions to be used in the output
of display values. For floating-point numbers, we can
also specify the number of digits to be displayed after
the decimal point.
Examples:
%3d - display an integer using 3 print positions.
%7.3f - display a floating-point number (float, or
double) using a total field width of 7 and with 3 places
after the decimal point.
www.cyberlabzone.com
Printf and scanf Examples
Example:
scanf("%i %f %lf %c", &n, &a, &x, &code);
Example:
printf("The sum of %i values is %f.n“,numValues,
sum);
printf("%sn", "Temperature Variations");
printf("The output is: n");
www.cyberlabzone.com
Comments
Comments in C are of the general form:
/* . . . */
Comments can be inserted anywhere you can put a space (blank).
Comments are ignored by the C compiler and not included in the
executable file.
The */ can be on the next line but then every character between
the /* and the */ is ignored by the C compiler.
www.cyberlabzone.com
Programming Errors
Syntax Errors
Run-time Errors
Logical Errors
The gcc compiler will catch these errors and give you
Error messages.
Example: x + 1 = x; (should be x = x+1; for a valid
assignment statement)
The gcc compiler will not catch these errors.
Example: User enters the value 0 and your code reads
this value into variable x, and then computes 1/x .
The gcc compiler will not catch these errors. Program
will run and not generate any error messages but
results outputted by the program are incorrect.
Example: User programs solution using the wrong
formula.
www.cyberlabzone.com
1. Problem Definition
Write a program that reads a number and computes the square root if
the number is non-negative.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify subproblems, I/O, etc.)
Input = real number
Output=real number
3. Develop Algorithm
(processing steps to solve problem)
C problem examples
www.cyberlabzone.com
C problem Example
Flowchart
Print “enter value”
Read value
value >= 0.0
Print sqrt(value)
TrueFalse
www.cyberlabzone.com
C program Example
/* C Program to compute the square root of a positive
number */
#include <stdio.h>
#include <math.h>
void main(void)
{
double value; /* Declare variables. */
printf(”Please enter a non-negative number :”); /* request
user input */
scanf("%lf", &value); /* read value */
/* Output the square root. */
if (value >= 0.0)
printf(”square_root(%f) = %f n", value,sqrt(value));
}
www.cyberlabzone.com
Selection Structures Decision statements
if(expression)
statement;
• if expression evaluates to true, the statement
is executed; otherwise execution passes to the
next statement in the program.
• if Selection Structure
if(value >= 0.0);
printf(”square_root(%f) = %f n", value,sqrt(value));
/* Error! Don’t put semicolon here */
/* This is an example of a logical error */
1. Problem Definition
Modify the previous program to notify the user when
the input is invalid.
www.cyberlabzone.com
C Program Examples (Modified)
Flowchart
Print “enter value”
Read value
value >= 0.0
Print sqrt(value);
TrueFalse
Print “invalid input”
www.cyberlabzone.com
C Program Examples (Modified)
/* C Program to compute the square root of a positive number */
#include <stdio.h>
#include <math.h>
void main(void)
{
double value; /* Declare variables. */
printf(”Please enter a non-negative number :”);/*request user input*/
scanf("%lf", &value); /* read value */
/* Output the square root. */
if (value >= 0.0)
printf(”square_root(%f) = %f n", value,sqrt(value));
else
printf(“invalid user input, please enter non-negative valuen”);
}
www.cyberlabzone.com
Math Library in C
- in header file math.h
Arguments (parameters) for each of the following
functions are assumed to be of type double. If not, a
type double copy is made for use in the function. To
compile a program that contains math functions you
need to use the -lm (Lm not 1m )option for gcc.
> gcc file.c -lm
See next slide
www.cyberlabzone.com
fabs (x) - |x|
sqrt (x) - square root of x
pow (x, a) - x to the power ‘a’
exp (x) - e to the power ‘x’ (e = 2.718281828 …)
log (x) - ln x = loge x
log10 (x) - log10 x
sin (x) - sine function (x in radians)
cos (x) - cosine function (x in radians)
tan (x) - tangent function (x in radians)
fmod (a, b) - remainder of a/b in floating-point
ceil (x) - smallest integer >= x
floor (x) - largest integer <= x
www.cyberlabzone.com
If- else Selection Structure
if (expression)
statement1;
else
statement2;
-if expression evaluates to true, statement1 is
executed and execution skips statement2
-If expression evaluates to false, execution skips
statement1 , statement2 is executed
Control Constructs
www.cyberlabzone.com
We can also execute multiple statements
when a given expression is true:
if (expression) {
if-statement1;
if-statement2;
if-statementn;
}
Example -
if(b < a){
temp = a;
a = b;
b = temp;
}
or
...
if (expression) {
if-statement1;
if-statement2;
if-statementn;
}
else {
else-statement1;
else-statement2;
else-statementm;
}
(what does this
code accomplish?)
...
...
If-else Selection Structure
www.cyberlabzone.com
C Problem Example
1. Problem Definition
Modify the previous program to compute the following:
You must check that the value is legal, i.e.
value >= 1.0 or value <= -1.0
0.1
2
value
www.cyberlabzone.com
C Problem Example
Flowchart
Print “enter
value”
Read
value
value >= 1.0 or value <= -
1.0
Print sqrt(value*value -
1.0);
TrueFalse
Print “invalid
input”
www.cyberlabzone.com
/* C Program to compute the square root of */
/* value*value -1.0 */
#include <stdio.h>
#include <math.h>
void main(void)
{
double value; /* Declare variables. */
/* request user input*/
printf(”Please enter value >= 1.0 or <= -1.0 :”);
scanf("%lf", &value); /* read value */
/* Output the square root. */
if ((value >= 1.0) || (value <= -1.0))
printf(”square_root(%f) = %f n", value,sqrt(value*value - 1.0));
else {
printf(“invalid user inputn”);
printf(“input should be a value >= 1.0 or <= -1.0 n”);
}
}
C Problem Example (Modified)
www.cyberlabzone.com
Logical Expression (Relational Operator)
In logical expressions (which evaluate to true or
false), we can use the following Relational
operators:
Relational
Operator
Type of Test
== equal to (don’t use =)
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
www.cyberlabzone.com
Logical Expression (Relational Operations)
Logical(Boolean)
Operators
&& and (true if both true)
|| or (true if at least one is true)
! not (a unary operator)
Operation
In logical expressions (which evaluate to true or
false), we can use the following Logical operators:
www.cyberlabzone.com
Logical Expressions
int ans, x = 3, y = 4;
ans = (x < 5)||(y >= 5); /* ans now has the value 1 */
ans = (x < 5)&&(y >= 5); /* ans now has the value 0 */
In C the value for False is represented by the value zero
and True is represented by any nonzero value. The value
False can be any zero value such as the number 0 or 0.0
or null character ‘ 0 ’ or the NULL pointer.
Example 2:
int x = 0; /* x declared as an integer variable */
/* and initialized to the value 0 */
if (x = 0) /* note the error, == should be used */
printf(“ x is zeron”); /*message not printed, why?*/
Example 1:
Caution: Avoid testing floating-
point numbers for equality! Why?
www.cyberlabzone.com
Nested if- else Selection Structure
1. Problem Definition
Write a program that returns a letter grade based on a quiz score. The input
will be the integer score from a 10 point quiz. The letter grades are assigned
by:
9 - 10 “A”
7 - 8 “B”
5 - 6 “C”
3 - 4 “D”
< 3 “F”
2. Refine, Generalize, Decompose the problem definition
(i.e., identify subproblems, I/O, etc.)
Input = integer score
Output=character “grade”
3. Develop Algorithm
(processing steps to solve problem)
www.cyberlabzone.com
C Problem Example
Flowchart
Print “enter score”
Read score
score == 10 || score == 9
Print “A”
TrueFalse
(continued on next slide)
(skip else part of statement)
www.cyberlabzone.com
C Problem Example
False
score == 8 || score == 7
Print “B”;
True
(skip else part of statement)
(continued on next slide)
False
www.cyberlabzone.com
C Problem Example
False
score == 6 || score == 5
Print “C”;
True
(skip else part of statement)
(continued on next slide)
False
www.cyberlabzone.com
C Problem Example
False
score == 4 || score == 3
Print “D”
True
False
Print “F”
www.cyberlabzone.com
C Problem Example
/* C Program to compute the letter grade for a quiz.
*/
#include <stdio.h>
void main(void)
{
int score; /* Declare variables. */
printf(”Please enter a score :”); /* request user input
*/
scanf("%i", &score); /* read value */
/* Output the grade */
/* continued on the next slide */
www.cyberlabzone.com
C Problem Example
if ((score == 10) || (score == 9))
printf(“An”);
else
if ((score == 8) || (score == 7))
printf(“Bn”);
else
if ((score == 6) || (score == 5))
printf(“Cn”);
else
if ((score == 4) || (score == 3))
printf(“Dn”);
else
printf(“Fn”);
} /* end of program */
Unless { } are used the else matches the first if in the code above.
www.cyberlabzone.com
Switch Selection structure
1. Problem Definition
Redo the previous problem by using a switch statement rather
than the nested if-else statement.
Pseudo-code Algorithm
print “enter score”
read score
switch score
score = 9,10 print “A”
score = 7,8 print “B”
score = 5,6 print “C”
score = 3,4 print “D”
otherwise print “F”
www.cyberlabzone.com
C Program Example
/* C Program to compute the letter grade for a quiz. */
#include <stdio.h>
void main(void)
{
int score; /* Declare variables. */
/* request user input */
printf(”Please enter a score :”);
scanf("%i", &score); /* read value */
/* Output the grade */
/* continued on the next slide */
www.cyberlabzone.com
C Program Example
switch (score) {
case 10:
case 9: printf(“An”);
break;
case 8:
case 7: printf(“Bn”);
break;
case 6:
case 5: printf(“Cn”);
break;
case 4:
case 3: printf(“Dn”);
break;
default: printf(“Fn”);
} /* end of switch */
} /* end of program */
www.cyberlabzone.com
Switch Selection Structure
The switch structure can be used when we have
multiple alternatives based on a value of type int or
type char (but not floating point). This structure has
the general form:
switch (controlling expression) {
case label1:
statements1;
case label2:
statements2;
default:
default statements;
}
(controlling expr.
must evaluate to an
integer or a
character value;
each case should
end with a break
stmt.)
...
www.cyberlabzone.com
1. Problem Definition
Use a while statement to read a list of integers from a file and
compute the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = integers from file “input.dat”
Output=real number representing the arithmetic average =(sum of
values)/(count of number of values)
3. Develop Algorithm
(processing steps to solve problem)
C problem Example
www.cyberlabzone.com
Flowchart
while EOF != scanf value
total = total + value;
count = count + 1;
TrueFalse
total = 0;
count = 0;
printf total/(double) count
(double) is a cast
see slide #14
C problem Example
www.cyberlabzone.com
/* C Program to compute the average of a list of numbers. */
#include <stdio.h>
void main(void)
{
int value,total = 0,count = 0; /*Why are total and count set to
zero?*/
while (EOF != scanf("%i", &value)) { /* read value */
total = total + value;
count = count + 1;
} /* end of while loop */
/* Output the average. */
printf(”Average of the %i numbers = %f
n“,count,total/(float)count);
}
C problem Example
www.cyberlabzone.com
1. Use xemacs to enter the above code in a file problem1.c ,
and make sure to save the file.
2. Use xemacs to create an input file input.dat and enter in integers
into this file. Save and exit this file.
3. Compile the problem1.c code by typing
gcc problem1.c
C problem Example-Execution
www.cyberlabzone.com
4. Run the program using Unix redirection <
a.out < input.dat
5. What happens if you type
a.out < input.dat > output.dat
Note: if you do this a second time it will fail because
Unix will not let you over-write an existing file.
6. To append the results to the existing file output.dat
a.out < input.dat >> output.dat
C problem Example-I/O Redirection
www.cyberlabzone.com
A second form of a declaration in C :
data-type variable_name = initializer;
/*Why are total and count initialized to zero?*/
Answer: Un-initialized variables have unknown (garbage) values.
int value,total = 0,count = 0;
Assignment statement
www.cyberlabzone.com
while(expression)
statement;
• if expression evaluates to true, the statement
is executed and then execution loops up and
re-evaluates expression; otherwise execution
passes to the next statement in the program.
• while statement format
while(value >= 0.0);
/* Error! Don’t put semicolon here */
/* This is an example of a logical error*/
while (EOF != scanf("%i", &value)) { /* read value */
total = total + value;
count = count +1;
} /* end of while loop */
While-loop Statement
www.cyberlabzone.com
We can also execute multiple statements
when a given expression is true:
while (expression) {
while-statement1;
while-statement2;
while-statementn;
}
• if expression evaluates to true, all the
statements are executed and then execution
loops up and re-evaluates expression;
otherwise execution passes to the next
statement in the program.
While-General Format
www.cyberlabzone.com
{
statement1;
statement2;
.
.
.
statementn;
}
A sequence of statements surrounded by a pair
of curly braces is called a block or
compound statement
1) From outside, the compound statement looks
like a single statement. A compound statement
can go where any single C statement can go.
(e.g. a branch of if-else, body of a for loop, ...)
What is a Compound statement?
www.cyberlabzone.com
What is all this fuss about blocks?
A block is any compound statement that may include variable
declaration(s).
1.As a compound statement, from outside, the
block looks like a single C statement. A
block can go where any single C statement
can go.
2.The importance of a block is that, the curly
braces of the block delimit the Scope (i.e.
the region of validity) of the variables
declared in the block.
3. The concept of Scoping lies at the heart of
Structured Programming, as will be
discussed in a future lecture on Modularity.
www.cyberlabzone.com
The program makes use of the fact that the scanf function returns
and integer value representing the number of successful
conversions. For example in the code fragment:
Example:
int number,value1,value2,value3;
number = scanf(“%d%d%d”,&value1,&value2,&value3);
the variable number could take the value 0,1,2 or 3.
EOF is a built-in constant in C(usually assigned -1).
If you are checking for End-of-File then use this constant.
EOF != scanf("%i", &value)
Scanf-Revisited
www.cyberlabzone.com
To fix the above use the cast operator
where data_type is a valid C data type.
float result;
int total = 10 , count = 4 ;
result = total / (float) count; /* result now has the value 2.5 */
Example,
float result;
int total = 10 , count = 4 ;
result = total / count; /* result has the value 2.0 */
( data_type )
printf(”Average of the %i numbers = %fn“,count, total/(float)count );
Arithmetic Conversions-Cast
www.cyberlabzone.com
data_type1 x;
data_type2 result;
result = x;
If x and result have different data types then an automatic
conversion takes place. Data could be lost.
Example,
float x = 3.1416;
int result;
result = x; /* result now has the value 3 */
1) Conversion of assigned values
Arithmetic Conversions
www.cyberlabzone.com
+, - , * , /x op y ; where op is
If x and y have different (mixed) data types then C automatically
converts data from the lower rank to the higher rank and then
performs the computation.
Note: % (modulus) is only defined on integers.
The ranking is given by the following table.
long double Higher
double
float
long integer
integer
short integer Lower
2) Conversion of values with mixed data types
in an expression using arithmetic operators
Arithmetic Conversions
www.cyberlabzone.com
Example,
float result , x = 3.1416;
int y = 3;
result = x + y; /* result now has the value 6.1416 */
Example,
int x = 2.5;
float result, y;
y = x;
result = 1 / y; /* result now has the value .5 */
Arithmetic Conversions
www.cyberlabzone.com
1. Problem Definition
Write a program that reads a file of characters one
character at a time and writes out each non-blank character to
another file.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = characters in a file “input2.dat” Assume this file
is non-empty.
Output=Non-blank characters from input2.dat are
output to the file output2.dat
3. Develop Algorithm
(processing steps to solve problem)
C Problem Example
www.cyberlabzone.com
Flowchart
while EOF != scanf c
TrueFalse
scanf c
if c != ‘ ‘ /* a blank */
printf c
C Problem Example
www.cyberlabzone.com
/* C Program to remove the blanks from a text file. */
#include <stdio.h>
void main(void){
char c;
scanf("%c",&c);
do {
if (c != ' ')
printf("%c",c);
} while(EOF != scanf("%c",&c));
}
C Problem Example
www.cyberlabzone.com
1. Use xemacs to enter the above code in a file problem2.c ,
and make sure to save the file.
2. Use xemacs to create an input file input2.dat and enter in any
number of lines of text including blanks. Save and exit this file.
3. Compile the problem2.c code by typing
gcc problem2.c
4. Run the program using Unix redirection < and >
a.out < input2.dat > output2.dat
5. View the contents of output2.dat
more output2.dat
C Problem Example-Execution
www.cyberlabzone.com
do
statement;
while(expression);
• The statement is executed first. Then if expression
evaluates to true, execution loops up and the statement is
executed again; otherwise execution passes to the next
statement in the program. The general form of the do-while
statement is:
• do/while statement format
do {
while-statement1;
while-statement2;
while-statementn;
} while (expression);
C Problem Example
www.cyberlabzone.com
1. Problem Definition
Use a for statement to read a list of integers from a file and
compute the average. The first number in the list gives the count
of the numbers to be read. This first value is not used in the
computation of the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = integers from file “input3.dat”
Output=real number representing the arithmetic average (sum of
values)/(count of number of values)
3. Develop Algorithm
Use a counter controlled loop.
(processing steps to solve problem)
C Problem Example
www.cyberlabzone.com
Flowchart
for i = 1 ; i <= count; i=i+1
scanf value
total = total + value;
TrueFalse
total = 0;
scanf count
printf total/(double) count
C Problem Example
www.cyberlabzone.com
/* C Program to compute the average of a list of numbers. */
#include <stdio.h>
void main(void)
{
int value,total = 0,count;
int i; /* loop counter */
scanf(“%i”,&count);
for(i=1;i<=count;i=i+1) {
scanf(“%i”,&value); /* read value */
total = total + value;
} /* end of for loop */
/* Output the average. */
printf(”Average of the %i numbers = %f n“,count,total/(float)count);
}
C Problem Example
www.cyberlabzone.com
1. Use xemacs to enter the above code in a file problem3.c ,
and make sure to save the file.
2. Use xemacs to create an input file input3.dat and enter in integers
into this file .The first integer is the count of integers to be
averaged. Save and exit this file.
3. Compile the problem1.c code by typing
gcc problem3.c
4. Run the program using Unix redirection <
a.out < input3.dat
C Problem Example-Execution
www.cyberlabzone.com
for(init. expressions ; expression ; update stmnts. )
statement1;
C allows more than one initialization expression or update statement but
these statements or expressions must be separated by a comma not a
semicolon. Also, if there is more than one init. expression or update
statement then the order of execution is from left to right.
The initialization expressions are executed once (and only once) .
If expression evaluates to true, statement1 is executed and execution loops
up and evaluates all the update stmnts. and then expression is
re-evaluated; otherwise execution passes to the next statement in the
program.
The following order of must be observed …
init. expressions; expression ; update stmnts
for-loop Statement
www.cyberlabzone.com
for(init. expressions ; expression ; update stmnts. ){
statement1;
statement2;
.
.
.
statementn;
}
The initialization expressions are executed once (and only once) ,
next:
if expression evaluates to true, the statements
statement1,... ,statementn are executed and execution
loops up and evaluates all the update stmnts. and then
expression is re-evaluated;
otherwise execution passes to the next statement in the program.
for-General Format
www.cyberlabzone.com
Write a code fragment to add the integers from 1 to 100.
int i,total;
total = 0;
for(i=1;i<=100;i=i+1)
total = total + i;
The above code could be re-written as:
int i,total;
for(i=1, total = 0; i<=100; total=total+i, i=i+1);
but not as:
int i,total;
for(i=1, total = 0; i<=100; i=i+1, total=total+i);
Why not? The order of the statements is critical!
for-Examples
www.cyberlabzone.com
1. Problem Definition
Use a for statement to read a list of integers from a file and
compute the average. Read the integers until the sentinel value of
-999 occurs. Do not use the sentinel value in the computation of
the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = integers from file “input4.dat”
Output=real number representing the arithmetic average (sum of
values)/(count of number of values)
3. Develop Algorithm
(processing steps to solve problem)
C Problem Example-Revisited
www.cyberlabzone.com
Flowchart
for i = 1 ; ; i=i+1
scanf value
if value == -999
break;
total = total+value;
TrueFalse
total = 0;
printf total/(float) (i-1)
C Problem Example-Revisited
www.cyberlabzone.com
/* C Program to compute the average of a list of numbers. */
#include <stdio.h>
void main(void)
{
int value,total = 0,count;
int i; /* loop counter */
for(i=1; ;i=i+1) {
scanf(“%i”,&value); /* read value */
if (value == -999) /* -999 is the sentinel value */
break;
total = total + value;
} /* end of for loop */
/* Output the average. */
count = i-1;
printf(”Average of the %i numbers = %f n“,count,total/(float)count);
}
C Problem Example-Revisited
www.cyberlabzone.com
Omitting the logical expression in a for statement means
that the for statement executes as an infinite loop.
for(i=1; ;i=i+1) {
As with the switch statement the break statement causes
the termination of the loop but not the program.
Break Statement
www.cyberlabzone.com
A one dimensional array is a list of data values, with
all values having the same data type(the base type),
such as:
• integer
• float
• double
• char
Technically, an array is a uniform data structure.
Individual array elements are referenced using
the array name and a subscript that identifies the
element position in the array.
What is an Array?
Array
www.cyberlabzone.com
For a one dimensional array, we specify the array name, its
base data type, and the number of storage locations
required using declarations such as
int a[25];
float x[100], y[100];
which specifies 25 integer locations for a and 100 floating-
point locations for arrays x and y.
Storage for array elements are in contiguous locations in
memory, referenced by subscript(or index) values starting at 0.
Thus for array a above, the storage is
. . .
a[0] a[1] a[24]
RAM
Declaring an Array
www.cyberlabzone.com
We can initialize array elements in declaration
statements; e.g.,
int counts[5] = {1, 2, 3, 4, 5};
int evens[] = {2, 4, 6, 8};
The array size could also be specified using a symbolic
constant:
#define ARRAY_SIZE 25
int a[ARRAY_SIZE];
.
.
.
/* evens has 4 elements */
We cannot specify more initial values than there are array
elements, but we can specify fewer initial values, and the
remaining elements will be initialized to 0. e.g.,
int b[10] = {2};
double x[250] = {0};
Declaring and initializing an Array
www.cyberlabzone.com
Note: when referencing a particular element of an array use
square brackets, not parenthesis or curly braces.
Given that the array x is declared as:
int x[250];
To initialize a large array to a nonzero value - say 10, we
can use a loop. e.g.,
for (k = 0; k <= 249; k = k+1)
x[k] = 10;
k is a subscript
Arrays-Subscripting
www.cyberlabzone.com
A subscript value for an array element can be specified as any
integer expression.
For example, given the following declarations:
double y[4] = {-1.0, 12.0, 3.5, 3.2e-2};
int c = 2;
the following statement would assign the value of 5.5 to y[1]
y[2 * c - 3] = 5.5;
Arrays-Subscripting
www.cyberlabzone.com
Given an integer value n, we can use the
following code to compute and store the first n
Fibonacci numbers in an array:
1. Problem Definition
Write a program “fib” that prompts the user for an integer n. The
program prints the first n Fibonacci numbers.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = n - the count of Fibonacci Numbers to be printed
Output= Fib Numbers printed to screen.
3. Develop Algorithm
Use the formula: fib0= 1, fib1 =1 and for k > 1
fibk = fibk-1 + fibk-2
Example-Fibonacci Numbers
www.cyberlabzone.com
#include <stdio.h>
/* C program to print the first n Fibonacci Numbers. */
void main(void){
int k,n;
int fib[100] = {1,1}; /* note: n must be <= 100 , why ? */
printf(“How many Fibonacci number do you want listed?”);
scanf(“%i”,&n);
for (k = 2; k < n; k++) /* the ++ is the increment operator */
fib[k] = fib[k-1] + fib[k-2];
/* print the results, four per line */
for (k = 0; k < n;++k){
if (k % 4 == 0)
printf(“n”);
printf("%8i", fib[k]); /* that’s 8 ints */
} /* end of for loop */
printf(“n”);
} /* end of main */
(For large values of parameter n, we would need more space for each
print column. Also, even with data type long , the calculated values may
become too large for the allocated storage space.)
www.cyberlabzone.com
:
.
Since incrementing and decrementing (negative increments)
are common programming operations, the C language
provides shortcut Increment / Decrement operators.
++k Increment k by 1 and use incremented value
in expression containing ++k.
k++ Use the current value of k then increment by 1.
--k Decrement k by 1 and use decremented value
in expression containing --k.
k-- Use current value of k then decrement by 1.
++k;
Increment and Decrement Operators
www.cyberlabzone.com
++k; /*C statement k = k + 1; */
int x,z;
int y = 1;
int a = 2;
x = y + a++;
/* now x = 3 , y = 1 , a = 3 */
z = x + --a;
/* now a = 2, z = 5, x = 3, y = 1 */
z = --x * ++y;
/* now x = 2, y = 2, z = 4, a = 2 */
x = a++ / --y;
/* now y = 1, x = 2, a = 3, z = 4 */
Note: The increment/decrement operators can be
applied only to single variables. They cannot be
applied to expressions.
Increment and Decrement Operators-Examples
www.cyberlabzone.com
Given an integer value n, we can use the following code to
compute and store the first n Fibonacci numbers in an array:
1. Problem Definition
Write a program that inputs a list of numbers into an array. The
program then calculates the average value, and then prints a list
of differences. The differences are computed by taking the original
values in the list minus the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = list of reals in a file “input.dat” . We will use Unix
redirection to read values from this file.
Output= The average and the list of differences.
Example-Average and difference List
www.cyberlabzone.com
int counter,k;
double datVal[500]; /* 500 element max */
double datAve;
double sum = 0.0;
/* read the file and compute the average */
counter = 0;
while (EOF != scanf("%lf", &datVal[counter])){
sum += datVal[counter]; /* += is an assignment operator */
counter++;
}
/* compute and print the average */
datAve = sum /counter;
printf(“The average is:%lf n", datAve);
/* compute and print the diff list */
for(k=0;k<counter;++k)
printf(“%lfn", datVal[k]-datAve);
Example-Average and difference List
www.cyberlabzone.com
- a shortcut method for writing assignment statements of the
form
var1 = var1 op expression;
Using an "assignment operator", we can rewrite the above as
var1 op= expression;
where op can be any one of the arithmetic
binary operators:
+ - * / %
sum += datVal[counter];
Assignment-operators
www.cyberlabzone.com
sum += datVal[counter]; or
sum = sum + datVal[counter];
k += 5; or k = k +5;
n -= 4; or n = n -4;
a *= 2.0; or a = a*2.0;
x /= b; or x = x/b;
remainder %= 6; or
remainder = remainder % 6;
newValue += (a-b)/(2*c); or
newValue = newValue + (a-b)/(2*c);
Assignment-operators-Examples
www.cyberlabzone.com
Unlike many other languages, there is no data type for
character strings in C. But we can reference a string as
a one dimensional array of characters. That is, each
element of the array is a single character.
Character Arrays
www.cyberlabzone.com
char aString[5] = "Zip!";
char atomic[ ] = "hydrogen";
char aString[] = {'Z', 'i', 'p', '!',
'0'};
Declaring a string array with character constants
Declaring character arrays with a string constant
IMPORTANT!!!
In C, you must always terminate a character array with the
NULL character, ‘0’ . Therefore, the array size of your
character array should be one plus the maximum length of
the string you want to store. Example: In the declaration
char atomic[ ] = "hydrogen";
“atomic” is an array of nine elements, the last being ‘0’
Declaring a Character Array
www.cyberlabzone.com
char atomic[ ] = "hydrogen";
You may declare and initialize a character arrays
with a string constant as in,
but you cannot assign an array in the same
manner, e.g.
atomic = "hydrogen"; not legal in C!
One of the mysteries of C!
Declaring a Character Array
www.cyberlabzone.com
Use the %s conversion specifier to read in a string of
characters. Any blanks will be skipped.
There should not be any blank character input such as in the
string “Hello World”, since a blank signals an end of input for
the string.
Again, don’t forget to declare the array size as one more than
the length of the longest string that you want to read in
order to accommodate the NULL character.
char strArray [10];
printf("Input a string with at most nine characters ”);
printf("with no blanks in the string: n");
scanf("%s", strArray);
/* Notice: No & is used for an array argument! */
printf(“n%s", strArray);
Input and output of Strings
www.cyberlabzone.com
You can use the %c conversion specifier to output
the string character by character.
k = 0;
while (strArray[k] != NULL)
printf("%c", strArray[k++]);
NULL is a built-in constant (‘0’). You must have
#include <stdio.h> in your file to be able to use NULL.
Outputing a String
www.cyberlabzone.com
• strlen(str) - string length, not counting NULL char.
• strcpy(str1, str2) - copy string2 to string1.
• strcmp(str1, str2) - returns a negative , zero or positive int
depending on whether str1 is lexicographically
less than, equal or greater than str2 respectively.
• strncmp(str1,str2,n) - like strcmp but just the first n characters
of str1 are compared to str2.
#include <string.h>
Arguments str1 and str2 in the following functions can be
character array names, string pointers(discussed in a future
lecture), or string constants.
See Chapter 13.3 for examples. There are many other string
functions (see Appendix G p. 1036 for a complete list).
String.h Library Functions
www.cyberlabzone.com
1. Problem Definition
Write a C program that converts a Morse code string into alphabet.
(Morse code is a sequence of dots and dashes). If the input is not a
valid string (see table on next slide) then a message is output to the
user. You will do a variation of this program in a future lab
assignment.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = a single string of characters.
Output= A single letter A-Z.
Example-Morse Code
www.cyberlabzone.com
A .- , N -.
B -... O ---
C -.-. P .--.
D -.. Q --.-
E . R .-.
F ..-. S ...
G --. T -
H .... U ..-
I .. V ...-
J .--- W .--
K -.- X -..-
L .-.. Y -.--
M -- Z --..
www.cyberlabzone.com
#include <stdio.h>
#include <string.h>
typedef char string[5];
void main(void){
string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.",
"--.", "....", "..", ".---", "-.-", ".-..",
"--", "-.", "---", ".--.", "--.-", ".-.", "...",
"-", "..-", "...-", ".--", "-..-", "-.--", "--.. " };
www.cyberlabzone.com
char alphabet[26] = {'A','B','C','D','E','F','G','H','I','J','K',
'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
char input[5];
int i;
int flag = 0; /* flag = 0 means match not found ,
flag = 1 means match found */
printf("Please enter a Morse code string:");
scanf("%s",input); /* no & for array */
www.cyberlabzone.com
/* loop through the Morse array to find a match */
for(i=0;i<26;++i)
if (strcmp(input,morse[i]) == 0)
{
printf("%cn",alphabet[i]);
flag = 1;
break; /*terminate for loop */
}
if (flag == 0)
printf("Input not a valid Morse character.n");
} /* end of main */
www.cyberlabzone.com
The typedef mechanism in C enables a programmer to create
a “custom” data-type.
Examples of the use of typedef are
typedef int blah; /* don’t do this !!!!! */
typedef char string[5];
In the first example we give another name or alias to the
data-type int .
In the second example we create a new data-type named
string.
typedef
www.cyberlabzone.com
To declare a variable of data-type blah ,
blah x;
this declaration is equivalent to
int x;
To declare a variable of data-type string ,
string var =“init”; /* declare and initialize */
scanf(“%s”,var); /* we can read in a string of chars */
var = “next”; But we can’t do this!!!
The declaration
string morse[26];
declares morse as an array of 26 elements. Each element
has data-type string.
typedef
www.cyberlabzone.com
The declaration and initialization:
string morse[26] =
{".-", "-...", "-.-.", "-..", ".", "..-.",
"--.", "....", "..", ".---", "-.-", ".-..",
"--", "-.", "---", ".--.", "--.-", ".-.", "...",
"-", "..-", "...-", ".--", "-..-", "-.--", "--.. " };
declares morse as an array of 26 elements with
morse[0] = “.-”
morse[1] = “-...” and so on...
typedef
www.cyberlabzone.com
- Two dimensional arrays are declared
similarly to one dimensional arrays:
char t[20][10]; (and referred to as a
matrix, or as a "table")
The first subscript gives the row number, and
the second subscript specifies column number.
Two-Dimensional Arrays
www.cyberlabzone.com
We can also initialize a two-dimensional array
in a declaration statement; E.g.,
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
which specifies the elements in each row of the
array (the interior braces around each row of
values could be omitted). The matrix for this
example is







654
321
m
Declaration and Initialization
www.cyberlabzone.com
Specification of the number of rows could be
omitted. But other subscript specifications can
not be omitted. So, we could also write the
initialization as
int m[ ][3] = {{1, 2, 3}, {4, 5, 6}};
Declaration and Initialization
www.cyberlabzone.com
int a[2][3]= {1,2,3,4,5,6};
specifies 6 integer locations.
Storage for array elements are in contiguous locations in
memory in row major order (unlike column major order in
Fortran), referenced by subscripts(or index) values starting at
0 for both rows and columns.
a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2]
RAM
1 2 3 4 5 6
Memory Storage for a Two dimensional Array
www.cyberlabzone.com
1. Problem Definition
Assume we have a file “in.dat” (located in the pwd) consisting of 10 rows of
10 integers per row (100 integers total). Write a C program which reads
from the file and stores the numbers in a two dimensional array named
‘mat’, computes the largest of all of these numbers and prints the largest
value to the screen.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = from file “in.dat”
Output= Largest of the 100 integers printed to screen.
3. Develop Algorithm
Use Unix redirection to read file “in.dat”.
Use nested for loop to go through two dimensional array to
find the largest value.
Example-Maximum Value
www.cyberlabzone.com
#include <stdio.h>
void main(void){
int row, col, maximum;
/* Declare a 2-D array called ‘mat’ which can hold a 10-by-10 */
/* matrix of integers */
int mat[10][10];
/* Write code here to read from the file ‘in.dat’ */
for(row=0;row<10;++row)
for(col=0;col<10;++col)
scanf(“%d”,&mat[row][col]);
/* Write code to find the largest value in the array ‘mat’ */
maximum = mat[0][0]; /* why ??? */
for(row=0;row<10;++row) /* How does this work??? */
for(col=0;col<10;++col)
if (mat[row][col] > maximum)
maximum = mat[row][col];
/* Print the largest value to the screen */
printf(“ max value in the array = %dn”,maximum);
}
www.cyberlabzone.com
Another example of the use of typedef is:
typedef double matrix[size][size];
In this example we create a new data-type named matrix.
We can declare a variable of data-type matrix by
matrix a;
this declaration is equivalent to
double a[size][size];
Typedef Revisited
www.cyberlabzone.com
Standard (ANSI) C allows up to 12 dimension.
But more computation is required by the system
to locate elements in multi-subscripted arrays.
Therefore, in problems involving intensive
numerical calculations, we should use arrays
with fewer dimension.
We can also use 3, 4, … dimensional arrays,
e.g.,
threeDArray [i][j][k];
Higher Dimensional Arrays
www.cyberlabzone.com
In slides 2-15 and 11-15 we discussed a method for creating
programs. In step three “Develop the Algorithm”, the nature of the
programming problem may suggest that we use top down
programming (as opposed to bottom-up programming , ...)
An analogy for top-down design is the following: Suppose a
general contractor was hired to construct a commercial building. The
contractor would need to know where to build and what are the blue-
prints. Then the contractor would hire various sub-contractors to dig
foundation, install electric, plumbing, frame, roof. That is, the large
job would be broken into smaller jobs, however these jobs must be
performed in some sequence and not at random.
Function-”Top Down Design”
www.cyberlabzone.com
In top-down design for programming, we specify the first function to
be invoked (the top function or “general contractor”). In C the top
function is called “main”.
The programmer then refines “main” into its component functions
(sub-contractors), which may in turn be refined into further functions,
and so on.
Function-”Top Down Design”
www.cyberlabzone.com
1. Problem Definition
Write a program that inputs a list of numbers into an array. The
program then calculates the average value, and then prints a list
of differences. The differences are computed by taking the original
values in the list minus the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = list of reals in a file “input.dat” . We will use Unix
redirection to read values from this file.
Output= The average and the list of differences.
Example-Average and difference List
www.cyberlabzone.com
#include <stdio.h>
int read(double datVal[]); /* prototype for read function */
double ave(int counter,double datVal[]);
/* prototype for ave function */
void diff(double datAve, int counter, double datVal[]);
/* prototype for diff function */
void main(void){
int counter,k;
double datVal[500]; /* 500 element max */
double datAve;
counter = read(datVal); /* read file into datVal */
datAve = ave(counter,datVal); /* compute & print average */
printf(“The average is:%f n", datAve);
diff(datAve,counter,datVal); /* compute diff list */
for(k=0;k<counter;++k) /* print the diff list */
printf(“%lfn", datVal[k]);
} /* end of main */
www.cyberlabzone.com
/* read function */
int read(double array[]) {
int count = 0;
while (EOF != scanf("%lf", &array[count])){
++count;
}
return count;
} /* end of read function */
/* ave function */
double ave(int count,double array[]){
int i;
double sum = 0.0;
for (i=0;i<count;++i)
sum += array[i];
return sum/count;
} /* end of ave function */
/* diff function */
void diff(double average, int count, double array[]){
int i;
for (i = 0;i<count;++i)
array[i] -= average;
} /* end of diff */
www.cyberlabzone.com
1. Use xemacs to enter the above code in a file problem1.c ,
and make sure to save the file.
2. Use xemacs to create an input file input.dat and enter in integers
into this file. Save and exit this file.
3. Compile the problem1.c code by typing
gcc problem1.c
4. Run the program using Unix redirection <
a.out < input.dat
C Problem Example-Execution
www.cyberlabzone.com
Example:
If the file input.dat has the values:
1.0 2.0 3.0 4.0 5.0
Then the program would execute as follows:
dclsn70> a.out < input.dat
The average is:3.000000
-2.000000
-1.000000
0.000000
1.000000
2.000000
dclsn70>
C Problem Example-Execution
www.cyberlabzone.com
#include <stdio.h> /* include statements */
int read(double datVal[]); /* prototype for read function */
void main(void) /* definiton of the main function */
{
/* C code here */
} /* end of main */
int read(double array[]) /* function definition */
{
/* more C code here */
} /* end of read */
One method to code the function “read”in C :
Functions-Prototypes
Functions
www.cyberlabzone.com
In the latest versions of standard C ("ANSI C"),
the function prototype is used to define the data
type to be returned by the function, the number
and data type of function parameters, and the
order of the function parameters. This info is
used by the C compiler to validate calls to the
function.
A general principle in C is that you must declare
or define the variable or function before you use
them.
Functions-Prototypes
www.cyberlabzone.com
The actual variable or array name is not needed in the
function prototype.
Examples:
Instead of the following prototypes
int read(double datVal[]);
double ave(int counter,double datVal[]);
void diff(double datAve, int counter, double datVal[]);
we could have used
int read(double []);
double ave(int ,double []);
void diff(double , int , double []);
Functions-Prototypes
www.cyberlabzone.com
#include <stdio.h> /* include statements */
/* Since the definition of read occurs before it is */
/* used (called) by main, we don’t need a prototype.*/
int read(double array[]) /* function definition */
{
/* C code for read here */
} /* end of read */
void main(void) /* definiton of the main function */
{
/* C code for main function here */
} /* end of main */
Another method to code the function “read ” in C
without using a prototype :
Functions-Prototypes
www.cyberlabzone.com
• The function definition in C is of the form:
return-type function-name(parameter-list)
{
/* function code */
return (value); /* parenthesis optional */
}
• The “value” can be a single variable, constant, or any C expression.
• The data type of “value” should be of type “return-type”, if not
then a conversion of the “value” to the “return-type” is specified
by the C compiler.
• If the “return-type is void then the programmer can omit the return
statement or code: return ; /* return nothing */
Function- definition
www.cyberlabzone.com
/* function called */
int x = 1;
float y = 2.0;
float value;
double z = 5.0;
value = sum(x,y,z+4.0);
/* more code here */
/* sum adds an integer a float and a double and returns */
/* a double */
double sum(int a, float b, double c)
{
double result;
result = a + b + c;
return result;
}
Data-types agree!
Since value has type
float and sum returns
a double, a conversion
takes place.
Function Type Checking
www.cyberlabzone.com
• A function that does not return a value is declared to
be of type void. e.g.,
void printFunction (int, int);
• If a function takes no parameters, we specify the
parameter list as void. e.g.,
void printPageHeading (void);
It is also possible to specify an "empty" parameter list:
void myFunction ( );
- argument checking is "turned off", so that anything
can be passed to myFunction. Best to avoid this in C.
Function Type Checking
www.cyberlabzone.com
• By default , if you omit the data type of the return
value, C assumes that the function returns an int value
(not void). Therefore the following function header:
main(void)
int main(void)
is equivalent to:
Function Type Checking
www.cyberlabzone.com
• A function may be called from any function (including itself) in C.
• A call is of the form:
function-name(argument-list)
• To “call” or invoke a function, you must pass the same
number of arguments for which the function has been defined.
The order of the arguments is important!!!
• If the data types in the argument list do not match the data
types in the parameter list, a conversion(or coercion) takes
place.
Function Call
www.cyberlabzone.com
.
.
.
int x = 1;
double y = 2.0;
float result;
/* function called */
result = F1(x,x+1,sin(y)); /* argument list */
.
.
.
} /* end main */
/* data types match */
float F1(int var1, int var2, double var3){ /*parameter list
*/
/* function code */
return (value);}
Example-Function Type Checking
www.cyberlabzone.com
• Arrays are passed as call-by-reference.
counter = read(datVal);
.
.
.
int read(double array[]) {
int count = 0;
while (EOF != scanf("%lf",
&array[count])){
++count;
}
return count;
} 2.0
1.0
1200
Main Memory after call
unknowndatVal[0]
datVal[1]
datVal[2]
1200
Main Memory before call
datVal[0]
datVal[1]
datVal[2]
.
.
.
.
.
.
.
.
.
.
.
.
The parameter “array” can be
considered as a pseudonym or
alias for “datVal”. There is only
one array in memory.
Passing arguments in a function Call
www.cyberlabzone.com
For two dimensional arrays, we could omit
specification of the number of rows in
function prototype and header. But we must
include size declaration for the number of
columns.
(see example on next slide)
Two-Dimensional Arrays Function Parameters
www.cyberlabzone.com
#define ROWS 10
#define COLS 5
void doSumpin(int [][COLS]);
int main (void)
{
int a[ROWS][COLS] = {{0}};
doSumpin (a);
}
void doSumpin(int b[][COLS]){ /* array passed by reference */
...
}
/* function prototype */
/* function call */
Examples of passing 2-D arrays
www.cyberlabzone.com
We can replace any 2-D array with an equivalent 1-D
array. For instance the following 2-D array
int A[2][3]= {1,2,3,4,5,6};
A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2]
RAM
1 2 3 4 5 6
can be replaced with the equivalent 1-D array,
int a[6]= {1,2,3,4,5,6};
however a[0][0] , a[0][1] , … is not defined.
Alternative to 2-D arrays
www.cyberlabzone.com
In order to reference A[0][0] , A[0][1] , … with a[ ]
we use the following formula,
int a[]= {1,2,3,4,5,6};
A[row][col] = a[row*3 + col]
A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2]
RAM
1 2 3 4 5 6
a[0] a[1] a[2] a[3] a[4] a[5]
Alternative to 2-D arrays
www.cyberlabzone.com
1. Problem Definition
Write a function that performs matrix – vector multiplication.
Assume that the matrix is passed as a
1-D array using the formula on the previous slide.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = A matrix and vector of reals .
Output= The vector that results from the matrix - vector
multiplication.
Alternative to 2-D arrays
www.cyberlabzone.com
/* The function mvmult works with any size matrix a. */
/* This function assumes that the number of Cols of a is */
/* equal to the number of Rows of invec */
/* a is 1-D version of matrix A[Rows][Cols] */
void mvmult(double a[], int Rows, int Cols, double invec[],
double outvec[]){
int row, col;
/* A[row][col] = a[row*cols + col] */
for(row=0;row<Rows;++row){
outvec[row] = 0.0;
for(col=0;col<Cols;++col)
outvec[row] += a[row*Cols +col] * invec[col];
}
} /* end of mvmult */
www.cyberlabzone.com
1. Use xemacs to enter the above code in a file mvmult.c ,
and make sure to save the file.
2. Use xemacs to create a file test.c and write the main function that
calls the mvmult function. Don’t forget the prototype!
3. Compile the code in the two files mvmult.c and test.c by typing,
gcc test.c mvmult.c -o mult
4. Run the program
mult
C Problem Example-Execution
www.cyberlabzone.com
#include <stdio.h>
#define ROWS 2
#define COLS 3
mvmult(double [], int , int double [] , double []); /* prototype */
void main(void){
double a[ROWS*COLS] = {1,2,3,4,5,6};
double invec[COLS] = {1,1,1};
double outvec[ROWS];
int row,col;
mvmult(a,ROWS,COLS,invec,outvec); /* call mvmult */
for(row=0;row<ROWS;++row) /* print the values of a */
for(col=0;col<COLS;++col)
printf("a[%i][%i] = %lfn",row,col,a[row*COLS+col]);
for(row=0;row<COLS;++row) /* print invec */
printf("invec[%i] = %lfn",row,invec[row]);
for(row=0;row<ROWS;++row) /* print outvec */
printf("outvec[%i] = %lfn",row,outvec[row]);
}
www.cyberlabzone.com
eesn23> mult
a[0][0] = 1.000000
a[0][1] = 2.000000
a[0][2] = 3.000000
a[1][0] = 4.000000
a[1][1] = 5.000000
a[1][2] = 6.000000
invec[0] = 1.000000
invec[1] = 1.000000
invec[2] = 1.000000
outvec[0] = 6.000000
outvec[1] = 15.000000
eesn23>
C Problem Example-Execution
www.cyberlabzone.com
• Non-arrays are passed as call-by-value.
datAve = ave(counter,datVal);
.
.
.
double ave(int count,double
array[]){
int i;
double sum = 0.0;
for (i=0;i<count;++i)
sum += array[i];
return sum/count;
}
1196
Main Memory while executing ave
5
counter
1196
Main Memory before call
counter
.
.
.
The value of the parameter “counter” is copied into the
memory location for the variable “count”. Therefore any
change to “count” would have no affect on “counter”.
1192count 5
55
Passing arguments in a function Call
www.cyberlabzone.com
1. Problem Definition
Write a function “sinc” that computes the value of
sin(x)/x . If x is zero return 1.0.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = One real number of type double.
Output= sin(x)/x as a double if x is not zero else 1.0.
3. Develop Algorithm
Use an if statement to check for a non-zero value.
But since the user could input 1.0e-600 , this may cause an
overflow when the value 1/x is computed so we will actually not
check for equality with zero but will check if the input value is
close to zero.
Example-Call-by-value
www.cyberlabzone.com
#include <stdio.h>
#include <math.h>
double sinc (double); /* function prototype */
void main(void){
double x, y;
printf("Enter a number: ");
scanf("%lf", &x);
y = sinc(x); /* function call */
printf(“n sinc(%f) = %f n”, x, y);
}
double sinc (double x){ /* function header */
if (fabs(x) < 1.0e-15)
return 1.0;
else
return sin(x) / x; } /* notice that sinc calls sin */
Example: function sinc(x)=sin(x)/x
www.cyberlabzone.com
Using Xemacs, user-defined functions can be typed into the same
file as “main”.
Functions may be typed into a separate file. For example, suppose
“main” is in the file test.c and the user defined function “sinc” is
entered into the file func.c then to compile both “main” and “sinc”
you would type (at the Unix prompt)
gcc test.c func.c -lm Note the use of the “-lm” option
The -lm option is needed only if you use a math library function in
“main” or “sinc”.
Don’t forget that if you put the function “sinc” into a separate file,
then you must still put the prototype for “sinc” in the same file as
main. The prototype for “sinc” must precede the function main.
Example: Location of user-defined functions
www.cyberlabzone.com
We present some methods to debug C programs.
We can categorize errors as
A) compile errors
B) run-time errors
C) Logical errors
Logical errors are the most difficult since they may involve using
the incorrect formula. This has nothing to do with C so we will not
discuss these types of errors any further.
Debugging
www.cyberlabzone.com
We present some methods to debug C programs.
A) compile errors
If your program doesn’t compile.
1) Check the line number that gcc returns for the error.
Note: a warning message is not an error. If you only have
warning messages gcc will go ahead and compile your code.
2) Sometimes the line number of the error is not where the
actual error occurred. An error on one line can produce
errors messages for subsequent lines. Therefore it is best in
general to fix the errors occurring on the earliest line numbers
first. Also, if you can’t find an error on the line specified by
gcc then look at the preceding lines.
Compiler Errors
www.cyberlabzone.com
A) compile errors(continued)
3) If you can’t find the error specified by gcc then try removing
some code by using the #ifdef feature of C. This is a
preprocessor command that will optionally compile (or not
compile) a group of statements. Or gcc allows you to use the
characters // at the beginning of a line to comment out that line
of code.
Compiler Errors
www.cyberlabzone.com
Example: On slide 25 add a semicolon to the which contains the
code:
if (fabs(x) < 1.0e-15);
When you compile you get an error message.
The error message states the problem is before line 15 but the
actual problem occurred on line 13.
dclsn70> gcc test.c -lm
test.c: In function `main':
test.c:4: warning: return type of `main' is not `int'
test.c: In function `sinc':
test.c:15: parse error before `else'
dclsn70>
Compiler Errors
www.cyberlabzone.com
Example: Use #ifdef to have the compiler skip
compiling line(s) of code.
From the previous problem add the #ifdef as follows:
double sinc (double x){ /* function header */
if (fabs(x) < 1.0e-15);
#ifdef foo
return 1.0;
#endif
else
return sin(x) / x; } /* notice that sinc calls sin */
Compiler Errors
www.cyberlabzone.com
From the above we can see that the code now compiles without
errors.
The reason for this is that the if-else statement is now a valid
statement. If the condition is true do nothing else return sin(x)/x .
Even if you don’t see the extra semicolon, at this point you know
that your if-else statement was the source of your previous compile
error.
dclsn70> gcc test.c -lm
test.c: In function `main':
test.c:4: warning: return type of `main' is not `int'
dclsn70>
Compiler Errors
www.cyberlabzone.com
B) run-time errors
If your program compiles without errors but you get incorrect
values or a message like “Segmentation fault”.
1) Use the statement:
fprintf(stderr, “format string”,variable-list);
Run-time Errors
www.cyberlabzone.com
On slide 25 remove the “&” symbol to obtain the following line:
scanf("%lf", x);
When you compile and run a.out you get the run-time error
“Segmentation Fault”,
dclsn70> gcc test.c -lm
test.c: In function `main':
test.c:4: warning: return type of `main' is not `int'
dclsn70> a.out
Enter a number: 3.14159
Segmentation fault
dclsn70>
Run-time Errors
www.cyberlabzone.com
Example: Use the fprintf statement to debug your code.
void main(void){
double x, y;
printf("Enter a number: ");
fprintf(stderr,“Before scanfn”);
scanf("%lf", &x);
fprintf(stderr,”After scanf x = %lfn”,x);
y = sinc(x); /* function call */
fprintf(stderr,“After sincn”);
printf(“n sinc(%f) = %f n”, x, y);
}
Run-time Errors
www.cyberlabzone.com
dclsn70> gcc test.c -lm
test.c: In function `main':
test.c:4: warning: return type of `main' is not `int'
dclsn70> a.out
Before scanf
Enter a number: 3.14159
Segmentation fault
dclsn70>
Since only “Before scanf” prints to the screen (specified by stderr).
This indicates that the problem occurs in the scanf statement.
Run-time Errors
www.cyberlabzone.com
1. Problem Definition
Write a function “swap” that has two integer input arguments.
This function should swap the values of the variables.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = two integers
Output= no value is returned to the calling function, but the values
of the called variables should be swapped.
3. Develop Algorithm
temp = a;
a = b;
b = temp;
Example-call-by-value
www.cyberlabzone.com
/* C Function to swap values. */
#include <stdio.h>
void swap(int, int); /* prototype for swap */
void main(void){ /* function header */
int x = 1;
int y = 2;
swap(x,y);
printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */
}
void swap(int a , int b){
int temp = a;
a = b;
b = temp;
return;
}
Example-bad Swap!!!
www.cyberlabzone.com
x
1000
Main Memory before call
1
The swap function will successfully swap the values of the variables a and
b.
But, since non-arrays are passed by value the swap of the values for a and
b will not have any affect on the variables x and y.
It is important to note that even if we had used the variable names x and y
rather than a and b the swap function would still not work. See the next
slide...
y 2
Main Memory while executing swap,
but before the return statement
x
1000
1
y 2
a 2
b 1
3000
Why swap doesn’t work.
www.cyberlabzone.com
/* Modified function to swap values. */
#include <stdio.h>
void swap(int, int);
void main(void){
int x = 1;
int y = 2;
swap(x,y);
printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */
}
void swap(int x , int y){ /* we now use x and y */
int temp = x;
x = y;
y = temp;
return;
}
Example-bad Swap!!!
www.cyberlabzone.com
x
1000
Main Memory before call
1
The C compiler will keep track of the variables x and y declared in main and
the variables x and y declared in swap. The x in main is a different variable
than the x in swap. Similarly for the y variable.
The reason that the x variable in main is different than the x variable in
swap is that two declarations of x occur in different blocks. That is the
scope of the x in main is different than the scope of x in swap.
One solution to the problem is to use pointer variables. We will discuss
pointer variables in a future lecture.
y 2
Main Memory while executing swap,
but before the return statement
x
1000
1
y 2
x 2
y 1
3000
Why the modified swap doesn’t work.
www.cyberlabzone.com
An identifier is a name that is composed of a sequence of letters,
digits, and the ‘_’ underscore character.
Variable names are identifiers and so are function names and
symbolic constant names.
The scope of an identifier is the portion of the program in which
the identifier is visible or accessible.
Both variables and functions have two attributes: type and
storage class. The scope of a variable or function is related to its
storage class.
Scope of Identifiers
www.cyberlabzone.com
•Local Variables - are declared within a block and cannot be referenced
by outside the block; i.e., each function is assigned its own "local"
storage areas.
•Global Variables - declared outside any block and are known to all
blocks in the same file . By default, global variables are "static”
storage class.
In the examples on the following slides, drawing a picture of memory is
helpful in understanding how scoping works.
Scope of Variable Names
www.cyberlabzone.com
int globalVar = 1; /* global variable */
int myFunction(int); /* function prototypes */
void main(void){ /* local variable: result, in main */
int result;
result = myFunction(globalVar); /* call myFunction */
printf(“%d”,result); /* prints “2” */
printf(“%d”,globalVar); /* prints “2” */
printf(“%d”,x); /* compile error! x not known in main */
}
int myFunction(int x){ /* Local variable x */
++x;
printf(“%d”,x); /* prints value “2” */
printf(“%d”,globalVar); /*prints value“1” */
++globalVar;
return x;
}
Example1:Scope of Variables
Program Design Example
www.cyberlabzone.com
globalVar
1000
Main Memory before call to Myfunction
1
result
???
Main Memory while executing MyFunction, but before ++globalVar;
1000
1
x 2
3000
???
globalVar
result
Example1:Scope of Variables
www.cyberlabzone.com
globalVar
1000
Main Memory after call to Myfunction
2
result
2
Main Memory while executing MyFunction, but before return(x);
1000
2
???
x 2
3000
globalVar
result
Example1:Scope of Variables
www.cyberlabzone.com
int globalVar = 1; /* global variable */
int myFunction(int); /* function prototypes */
void main(void){ /* local variable: result, in main */
int result;
result = myFunction(globalVar); /* call myFunction */
printf(“%d”,result); /* prints “2” */
}
int myFunction(int x){/* Local variables: x, globalVar */
int globalVar; /* new “local” variable */
printf(“%dn”,globalVar);/* prints ??? */
return x + 1;
}
Example2:Scope of Variables
www.cyberlabzone.com
int myFunction(int); /* function prototypes */
void main(void){ /* local variables: x,result in main */
int result, x = 2;
result = myFunction(x); /* call myFunction */
printf(“%d”,result); /* prints “3” */
printf(“%d”,x); /* prints “2” WHY??? */
}
int myFunction(int x){/* Local variable: x */
x = x + 1;
printf(“%dn”,x);/* prints “3” */
return x;
}
Example3:Scope of Variables
www.cyberlabzone.com
/* C Function to swap values.This doesn’t work!!!! */
#include <stdio.h>
int x; /* x is a global variable */
int y; /* y is a global variable */
void swap(int, int); /* prototype for swap */
void main(void){
x = 1; /* note that x and y are not declared here!!! */
y = 2;
swap(x,y);
printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */
}
void swap(int x , int y){
int temp = x;
x = y;
y = temp;
return;
}
Example4:Scope of Variables
www.cyberlabzone.com
A function can be called by any other function, provided that
either the function definition or its prototype is in the same
file as the calling function and precedes the function call.
If no prototype is specified for a function, its header serves as
the function prototype.
Note: Functions cannot be defined within each other
Scope of Function Names
www.cyberlabzone.com
- Determines the storage duration and scope of identifiers,
and also linkage between files.
auto - creates storage for variables when the block that
declares them is entered, and deletes the storage when the
block is exited. Local variables have "auto" storage by
default.
e.g.,typing auto float a, b, c; is equivalent to typing float a, b, c;
Storage Classes-auto
www.cyberlabzone.com
static - creates and initializes storage for variables when the program
begins execution. Storage continues to exist until execution terminates. If
an initial value is not explicitly stated, a static variable is initialized to 0. We
can retain values of local variables by declaring them to be static.
In the following example, the static variable sum is initialized to 1.
static int sum = 1;
The initialization takes place only once. If the above declaration appears in
a user defined function , the first time the function is called, the variable
sum is initialized to 1. The next time the function (containing the above
declaration) is executed sum is not reset to 1.
Storage Classes-static
www.cyberlabzone.com
extern - used to reference identifiers in another file. Function names
are extern by default.
e.g., extern int foreignVar;
Storage Classes-extern
www.cyberlabzone.com
1. Problem Definition
Write a function “sum”that keeps a running total of the sum of
every value passed to “sum”. To test this function, modify the
previous program of slide 15 -3 that compute the average of
values in a file.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = integers from file “input.dat”
Output=real number representing the arithmetic average (sum of
values)/(count of number of values)
3. Develop Algorithm
(processing steps to solve problem)
Example-static variable
www.cyberlabzone.com
Flowchart for main
while EOF != scanf value
total = sum(value);
++count;
TrueFalse
count = 0;
printf total/(double) count
Example-static variable
www.cyberlabzone.com
/* C Program to compute the average of a list of numbers. */
#include <stdio.h>
int sum(int); /* function protoype */
void main(void)
{
int value,total,count = 0;
while (EOF != scanf("%i", &value)) { /* read value */
total = sum(value);
++count;
} /* end of while loop */
printf(”Average of the %i numbers = %f n“,count,total/(double)count);
}
int sum(int val){ /* function header */
static int total_val = 0; /* static variable, */
total_val += val;
return total_val;
}
Example-static variable
www.cyberlabzone.com
Pointer variables are variables that store memory addresses.
Pointers variables are useful in passing storage addresses in
function calls (call-by-reference) and for applications involving
dynamic data structures (e.g., linked lists)
Example: int *intPtr;
float *floatPtr;
declares intPtr to be a pointer variable to an object of type
integer. and floatPtr to be a pointer variable to an object of
type float.
Pointers
www.cyberlabzone.com
We can write the pointer variable declaration
as int* intPtr;
or as int * intPtr;
Note that when we declare more than two pointer
variables in one line each pointer name requires an
asterisk:
int *ptr1, *ptr2;
otherwise we are just declaring a regular variable ,
not a pointer variable.
Pointer Declaration-syntax
www.cyberlabzone.com
There are two C operators that are necessary when using
pointer variables.
& - the address operator returns the address of a variable
x
1000
3
ptrX 1000
ptrX holds the address of x.
We say ptrX “points” to x.
We will apply the & operator only to variables, e.g. &77 or &(x+1)
are not valid.
The declaration of ptrX initializes the variable ptrX = &x;
Example:
int x = 3;
int * ptrX = &x;
1004
& Operator
www.cyberlabzone.com
Example:
int x;
int * pt;
pt = &x; /* another way to assign an address to a pointer variable */
Suppose the address of the variable x is 9640
Then, the effect of pt = &x; will be:
x pt
Address
9640 9640
& Operator
www.cyberlabzone.com
int x;
int * pt;
pt = &x;
To assign the value “3” to the variable x in C:
x = 3;
We can use the “ * ” operator to indirectly reference x.
We can assign “3” to x by:
*pt = 3;
Here we use the fact that “pt” points to integer values.
x pt
Address
9640 96403
* - means "a pointer to" and is called an indirection operator or
dereferencing operator, since a pointer "indirectly" references a
value in a storage location. Example:
*Operator
www.cyberlabzone.com
double *ptr;
ptr = NULL;
Assigning a NULL value (zero) to a pointer
A null pointer points to nothing. We often depict it as
ptr
/*called a null pointer*/
Null Pointer
www.cyberlabzone.com
1. Problem Definition
Write a function “swap” that has two input integer arguments.
This function should swap the values of the variables.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = two integers
Output= no value is returned to the calling function, but the values
of the called variables should be swapped.
3. Develop Algorithm
Pass the addresses of the variables and not their values. In the
swap function the parameters that hold the addresses are
pointers. Use the indirection operator to swap the values.
Example-call-by-Reference
www.cyberlabzone.com
/* C Function to swap values. */
#include <stdio.h>
void swap(int * , int *);
void main(void){ /* function header */
int x = 1;
int y = 2;
swap(&x,&y); /* pass the addresses of x and y */
printf(“x = %d , y = %d n”,x,y); /* prints x = 2 , y = 1 */
}
void swap(int *ptrX , int *ptrY){ /* pointer variables */
int temp = *ptrX;
*ptrX = *ptrY ;
*ptrY = temp;
return;
}
Example-good Swap
www.cyberlabzone.com
x
1000
Main Memory before call to swap
1
y
2
Main Memory while executing swap, after temp = *ptrX;
but before *ptrX = *ptrY ;
10001
ptrX 1000 3000
2
x
y 1004
1004
3008
30041004ptrY
temp 1
Example-good Swap
www.cyberlabzone.com
x
y
Main Memory while executing swap, after *ptrX = *ptrY ;
but before *ptrY = temp;
10002
ptrX 1000 3000
2 1004
3008
30041004ptrY
temp 1
Example-good Swap
www.cyberlabzone.com
x
y
Main Memory while executing swap, after *ptrY = temp;
but before return;
10002
ptrX 1000 3000
1 1004
3008
30041004ptrY
temp 1
Example-good Swap
www.cyberlabzone.com
The array name in C is assigned the address of the
first element of the array.
The following code will assign the address of
xArray[0] to xArrayPtr :
float xArray[50];
float * xArrayPtr;
xArrayPtr = xArray;
The assignment statement above is equivalent to:
xArrayPtr = &xArray[0];
Array Names are Constant Pointers
www.cyberlabzone.com
A string literal (e.g. “A – your course graden”) is actually
represented in C by a pointer to an address in memory that holds the
first byte of the array of characters.
Therefore the following declaration of the pointer variable “string” is
valid:
char * string = “A – your course graden”;
and to print the value of “string” , use the “%s” conversion specifier,
printf(“%s”,string);
Although a pointer can be used as an array name, we cannot modify
the values of “string” by using the square brackets of array notation.
string[0] = ‘B’; /* error !!! */
The error is due to the fact that the literal “A – your course graden”
is stored in a location in memory that cannot be accessed by
pointers.
String Literal is pointer to an array
www.cyberlabzone.com
One use of char * pointers is ragged arrays.
In slide 15-24 we used the following code fragment in the “Morse
Code” example to declare and initialize the array “morse” as :
typedef char string[5];
string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..","--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--.." };
An alternative would be the use of a ragged “morse” array declared
as:
typedef char * string;
string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..","--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--.." };
String Literal is Pointer to an Array
www.cyberlabzone.com
The later declaration of the array “morse” is called ragged since
each element of the array , morse[0], morse[1], … takes up
exactly the number of bytes necessary in memory to hold the
initialized strings whereas in the previous declaration of “morse”
each element of the array takes exactly five character values in
memory no matter what length of the initializing string.
As discussed on slide 15, we cannot change the values of the
ragged “morse” array. But in the “Morse Code” problem we know
that the morse strings should never be changed.
Ragged Arrays
www.cyberlabzone.com
To sort means to put in place or rank according to kind, class or nature.
For example, consider a herd of cows. We can sort the cows by weight,
age, amount of milk produced, etc. . The sort can be in ascending or
descending order.
Note that we could not include a lizard in among the sort if we were
sorting with respect to amount of milk produced. That is, the items we
want to sort must have the same nature.
In C we will use arrays to do our sorting. Since the data-type(kind, class
or nature) for each element of the array must be the same we are able to
compare any two elements in the array (no lizards in the array of milk
producing cows).
Why sort?
Sorting
www.cyberlabzone.com
One method of sorting is called “selection sort”.
The algorithm: find the smallest element in the list and swap the first item in
the list with the smallest value.
For example, suppose you are given the values(below):
5 3 7 2 4 ( 2 is the smallest value )
step 1
2 3 7 5 4 ( swap 2 with 5, now 3 is the smallest element)
step 2
2 3 7 5 4 ( 3 is in place don’t swap, now 4 is the smallest element)
step 3
2 3 4 5 7 ( swap 4 with 7, now 5 is the smallest element)
step 4
2 3 4 5 7 ( 5 is in place don’t swap, 7 is in place )
www.cyberlabzone.com
Another method of sorting is called “insertion sort”.
You use insertion sort when you sort a hand of cards.
For example, suppose you are given the five cards (below):
5 3 7 2 4 (cards in Right hand)
empty (cards in Left hand)
step 1
3 7 2 4 (Right hand)
5 (Left hand)
step 2
7 2 4 ( R )
3 5 ( L )
step 3
2 4 ( R )
3 5 7 ( L )
step 4
4 ( R) )
2 3 5 7 ( L )
step 5
empty ( R )
2 3 4 5 7 ( L ) ( the cards are now sorted )
www.cyberlabzone.com
1. Problem Definition
Write a program that sorts the values in an array in ascending
order. Use the built-in function ‘qsort’ to do the work of sorting.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = Array of integers.
Output= Sorted array of integers (ascending order) is printed.
Qsort-Sorting an array
www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
int compare(int *ptr1, int *ptr2) {
if ( *ptr1 > *ptr2)
return 1;
else if ( *ptr1 < *ptr2)
return -1;
else
return 0;
}
void main(void) {
int numbers[100];
int k,i=0;
printf(“Enter an array of no more than 100 integers.n”);
while (EOF != scanf(“%d”,&numbers[i]))
++i;
qsort(numbers, i, sizeof(numbers[0]), compare);
for (k=0; k<i; k++)
printf("%d ", numbers[k]);
printf(“n”);
}
www.cyberlabzone.com
Execution:
dclsn67>./a.out
Enter an array of no more than 100 integers.
3 4 2 1 5 (hit Enter and then Control-d to signal EOF)
1 2 3 4 5 (this is the output the program produces)
dclsn67>
Qsort-Sorting an array
www.cyberlabzone.com
arrayname - is the name of an existing array. This array
can have any data-type. It can even be an array of
pointers. We will refer to the array’s type as datatype .
elts is the number of elements of array.
qsort(arrayname,elts,size_of_elts,compare_function)
The qsort function is a built-in C function that sorts values
in an array. The algorithm behind qsort is called “Quick
Sort” . In CS101 we are interested only in how to call this
function.
The general format of the qsort function is:
Sorting Example-qsort
www.cyberlabzone.com
size_of_elts is the size in bytes of each element in the
array. Use the built-in operator sizeof that returns an
integer value representing the number of bytes a variable
or data-type takes up in RAM.
Example:
sizeof(integer) returns the value 4 on the Lab machines.
sizeof(numbers[0]) returns the number of bytes the variable
numbers[0] takes up in RAM, which is 4 since numbers is
an integer array.
compare_function is the name of the user defined function
that actually does the comparison.
qsort(arrayname,elts,size_of_elts,compare_function)
Sorting Example-qsort
www.cyberlabzone.com
The general format of the header for the user defined compare
function is:
int compare_function( datatype * ptr1,datatype * ptr2)
qsort will call the compare_function and pass two pointers ptr1
and ptr2 . Both ptr1 and ptr2 “point” to values in the array
arrayname (see previous slide).
The user must code the function compare_function so that it
returns an integer value back to qsort (the function that called
compare_function) . qsort will use this integer to determine
whether or not to swap the values in the array.
To sort in ascending order the return value is:
0 if the elements *ptr1 and *ptr2 of the array are equal
positive if *ptr1 > *ptr2 (i.e. swap the array values)
negative if *ptr1 < *ptr2 (i.e. don’t swap the array values)
Sorting Example- compare_function
www.cyberlabzone.com
Writing the code for compare_function depends on the data-type
datatype and whether the data is sorted in ascending order,
descending order, ... or by some other rule.
Therefore it’s not possible to write one version of
compare_function that does all.
Sorting Example- compare_function
www.cyberlabzone.com
The datatype in the sorting example is int . Therefore the
header for the compare_function has the form:
int compare( int * ptr1,int * ptr2)
where ptr1 and ptr2 are pointers to values in the array
numbers . As an example of how qsort works with compare see
the pictures of memory in the following slides.
Sorting Example
www.cyberlabzone.com
ptr1 ptr2 numbers[0] numbers[1] numbers[4]
3 4
Address 2000 2004 …
20042000 2 1 5
. . .
Suppose qsort called the compare function and *ptr1 is “3” and
*ptr2 is “4”. The picture above shows this situation. In this
example, we want to tell qsort to sort 3 before 4(don’t swap the
values). To do this, we use *ptr1 and *ptr2 . Since *ptr1 < *ptr2
( 3 < 4) we return a -1 value to qsort. That’s why we have the
code(slide 20):
else if ( *ptr1 < *ptr2)
{
return -1;
Sorting Example
www.cyberlabzone.com
ptr1 ptr2 numbers[1] numbers[2] numbers[4]
3 4
Address 2000 2004 2008…
20082004 2 1 5
. . .
Now suppose qsort called the compare function and *ptr1 is “4” and
*ptr2 is “2”. The picture above shows this situation. In this
example, we want to tell qsort to sort 2 before 4( swap the values).
To do this, we use *ptr1 and *ptr2 . Since *ptr1 > *ptr2 ( 4 > 2)
we return +1 value to qsort. That’s why we have the code(slide
20):
if ( *ptr1 > *ptr2)
{
return 1;
}
Sorting Example
www.cyberlabzone.com
The previous code works correctly but will generate a warning
message. We can avoid the error messages if we obey the
rules that qsort expects the compare_function to observe.
The code on the next slide will sort the numbers as before but
gcc will not display any warning messages.
In the compare function (on the next slide), note the use of the
void pointer data-type and the use of the cast operators on the
pointer variables.
const int x = 1;
x = 2; /* illegal */
Compiler Warning Messages
www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
int compare(const void *ptr1, const void *ptr2) {
if ( *(int *)ptr1 > *(int *)ptr2)
return 1;
else if ( *(int *)ptr1 < *(int *)ptr2)
return -1;
else
return 0;
}
void main(void) {
int numbers[100];
int k,i=0;
printf(“Enter an array of no more than 100 integers.n”);
while (EOF != scanf(“%d”,&numbers[i]))
++i;
qsort(numbers, i, sizeof(numbers[0]), compare);
for (k=0; k<i; k++)
printf("%d ", numbers[k]);
printf(“n”);
}
www.cyberlabzone.com
#include <stdio.h>
void main(void){
int z = 3;
float w = 4.0;
void * ptr;
ptr = &z;
/* add one to z */
*(int *)ptr = *(int *)ptr + 1; /* cast ptr */
ptr = &w;
/* add 1.0 to w */
*(float *)ptr = *(float *)ptr + 1.0; /* cast ptr */
printf("z = %i n",z); /* prints 4 */
printf("w = %f n",w); /* prints 5.000 */
}
www.cyberlabzone.com
1. Problem Definition
Write a program that creates a new data type named “vector”. A “vector”
represents a 2 dimensional vector v =<x,y> in the plane. The values of v are of
type double. Along with this new data-type, create functions add, sub, and dot
which will add , subtract and take the vector dot product of two vectors.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
We first define a new data type “vector”. Then in main we will declare v1,v2,v3 of
data type “vector”. We will assign values to these vectors and then perform
addition, subtraction and the dot product.
Input = None
Output= The values of v1,v2 will be printed along with the results from add, sub
and dot.
Example-Defining a 2D “vector data type”
www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
typedef struct { /* user defined data-type called vector */
double x; /* this is a definition*/
/* no variables are declared */
double y; /* location is outside any block */
} vector;
vector add(vector vec1, vector vec2) ; /* prototype */
vector sub(vector vec1, vector vec2) ; /* prototype */
double dot(vector vec1, vector vec2) ; /* prototype */
/* see explanation of the above in subsequent slides */
void main(void){
vector v1,v2,v3 ={1.0,2.0}; /* three variables of type vector*/
/* v3 initialized to {1.0,2.0} */
v1.x = 2.5; /* use the . to access individual fields */
v1.y = -1.5;
v2 = v3; /* can assign all the values with one statement */
/* continued on next slide */
www.cyberlabzone.com
printf(“v1 = [%f,%f]n”,v1.x,v1.y);
printf(“v2 = [%f,%f]n”,v2.x,v2.y);
v3 = add(v1,v2);
printf(“add(v1,v2) = [%f,%f]n”,v3.x,v3.y);
v3 = sub(v1,v2);
printf(“sub(v1,v2) = [%f,%f]n”,v3.x,v3.y);
printf(“dot(v1,v2) = %fn”,dot(v1,v2));
} /* end of main */
vector add(vector vec1, vector vec2){
vector v4 = {vec1.x + vec2.x, vec1.y + vec2.y};
return v4;
} /* end of add */
vector sub(vector vec1, vector vec2){
vector v4 = {vec1.x - vec2.x, vec1.y - vec2.y};
return v4;
} /* end of sub */
double dot(vector vec1, vector vec2){
return (vec1.x * vec2.x) + (vec1.y * vec2.y);
} /* end of dot */
www.cyberlabzone.com
> a.out
v1 = [2.500000,-1.500000]
v2 = [1.000000,2.000000]
add(v1,v2) = [3.500000,0.500000]
sub(v1,v2) = [1.500000,-3.500000]
dot(v1,v2) = -0.500000
Example-Execution
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course
Complete C programming Language Course

Weitere ähnliche Inhalte

Was ist angesagt?

Conditional statement c++
Conditional statement c++Conditional statement c++
Conditional statement c++amber chaudary
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming languageMd.Al-imran Roton
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C ProgrammingKamal Acharya
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++Vishesh Jha
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member FunctionsMOHIT AGARWAL
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While LoopAbhishek Choksi
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
Programming in ansi C by Balaguruswami
Programming in ansi C by BalaguruswamiProgramming in ansi C by Balaguruswami
Programming in ansi C by BalaguruswamiPriya Chauhan
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Sanjit Shaw
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++Neeru Mittal
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01Wingston
 

Was ist angesagt? (20)

Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
JAVA PROGRAMMING
JAVA PROGRAMMING JAVA PROGRAMMING
JAVA PROGRAMMING
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
 
Conditional statement c++
Conditional statement c++Conditional statement c++
Conditional statement c++
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C Programming
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
C introduction by thooyavan
C introduction by  thooyavanC introduction by  thooyavan
C introduction by thooyavan
 
Lecture 21 - Preprocessor and Header File
Lecture 21 - Preprocessor and Header FileLecture 21 - Preprocessor and Header File
Lecture 21 - Preprocessor and Header File
 
Programming in ansi C by Balaguruswami
Programming in ansi C by BalaguruswamiProgramming in ansi C by Balaguruswami
Programming in ansi C by Balaguruswami
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 

Andere mochten auch

Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programmingavikdhupar
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02Wingston
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGAbhishek Dwivedi
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)Dushmanta Nath
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C LanguageShaina Arora
 
Basic C concepts.
Basic C concepts.Basic C concepts.
Basic C concepts.Farooq Mian
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programmingprogramming9
 
SULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notesSULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notesSULTHAN BASHA
 
c++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data typesc++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data typesAAKASH KUMAR
 
C Language Program
C Language ProgramC Language Program
C Language ProgramWarawut
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programmingChitrank Dixit
 
C Programming basics
C Programming basicsC Programming basics
C Programming basicsJitin Pillai
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming LanguageMahantesh Devoor
 
8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solving8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solvingKhan Yousafzai
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)sachindane
 

Andere mochten auch (20)

Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
 
C ppt
C pptC ppt
C ppt
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
 
Basic C concepts.
Basic C concepts.Basic C concepts.
Basic C concepts.
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
 
CHAPTER 3
CHAPTER 3CHAPTER 3
CHAPTER 3
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
 
SULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notesSULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notes
 
c++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data typesc++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data types
 
C Language Program
C Language ProgramC Language Program
C Language Program
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programming
 
C Programming basics
C Programming basicsC Programming basics
C Programming basics
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming Language
 
8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solving8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solving
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
C++ Language
C++ LanguageC++ Language
C++ Language
 

Ähnlich wie Complete C programming Language Course

1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docxtarifarmarie
 
C prog ppt
C prog pptC prog ppt
C prog pptxinoe
 
Programming Fundamentals lecture 5
Programming Fundamentals lecture 5Programming Fundamentals lecture 5
Programming Fundamentals lecture 5REHAN IJAZ
 
Introduction of c language
Introduction of c languageIntroduction of c language
Introduction of c languagefarishah
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxrajkumar490591
 
C Introduction and bascis of high level programming
C Introduction and bascis of high level programmingC Introduction and bascis of high level programming
C Introduction and bascis of high level programmingvipulkondekar
 
Introduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itIntroduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itPushkarNiroula1
 
C introduction
C introductionC introduction
C introductionKamran
 
Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)Rohit Singh
 
(Lect. 2 & 3) Introduction to C.ppt
(Lect. 2 & 3) Introduction to C.ppt(Lect. 2 & 3) Introduction to C.ppt
(Lect. 2 & 3) Introduction to C.pptatulchaudhary821
 

Ähnlich wie Complete C programming Language Course (20)

C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx
 
C prog ppt
C prog pptC prog ppt
C prog ppt
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
C language tutorial
C language tutorialC language tutorial
C language tutorial
 
C programming day#1
C programming day#1C programming day#1
C programming day#1
 
Programming Fundamentals lecture 5
Programming Fundamentals lecture 5Programming Fundamentals lecture 5
Programming Fundamentals lecture 5
 
Introduction of c language
Introduction of c languageIntroduction of c language
Introduction of c language
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
 
C Introduction and bascis of high level programming
C Introduction and bascis of high level programmingC Introduction and bascis of high level programming
C Introduction and bascis of high level programming
 
Introduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to itIntroduction to cpp language and all the required information relating to it
Introduction to cpp language and all the required information relating to it
 
C++ How to program
C++ How to programC++ How to program
C++ How to program
 
C introduction
C introductionC introduction
C introduction
 
The smartpath information systems c pro
The smartpath information systems c proThe smartpath information systems c pro
The smartpath information systems c pro
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
 
C introduction
C introductionC introduction
C introduction
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
 
Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)Learn c language Important topics ( Easy & Logical, & smart way of learning)
Learn c language Important topics ( Easy & Logical, & smart way of learning)
 
(Lect. 2 & 3) Introduction to C.ppt
(Lect. 2 & 3) Introduction to C.ppt(Lect. 2 & 3) Introduction to C.ppt
(Lect. 2 & 3) Introduction to C.ppt
 

Mehr von Vivek chan

Deceptive Marketing.pdf
Deceptive Marketing.pdfDeceptive Marketing.pdf
Deceptive Marketing.pdfVivek chan
 
brain controled wheel chair.pdf
brain controled wheel chair.pdfbrain controled wheel chair.pdf
brain controled wheel chair.pdfVivek chan
 
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)Vivek chan
 
Manav dharma shashtra tatha shashan paddati munshiram jigyasu
Manav dharma shashtra tatha shashan paddati   munshiram jigyasuManav dharma shashtra tatha shashan paddati   munshiram jigyasu
Manav dharma shashtra tatha shashan paddati munshiram jigyasuVivek chan
 
Self driving and connected cars fooling sensors and tracking drivers
Self driving and connected cars fooling sensors and tracking driversSelf driving and connected cars fooling sensors and tracking drivers
Self driving and connected cars fooling sensors and tracking driversVivek chan
 
EEG Acquisition Device to Control Wheelchair Using Thoughts
EEG Acquisition Device to Control Wheelchair Using ThoughtsEEG Acquisition Device to Control Wheelchair Using Thoughts
EEG Acquisition Device to Control Wheelchair Using ThoughtsVivek chan
 
Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant Vivek chan
 
Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant Vivek chan
 
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)Vivek chan
 
Net framework session01
Net framework session01Net framework session01
Net framework session01Vivek chan
 
Net framework session03
Net framework session03Net framework session03
Net framework session03Vivek chan
 
Net framework session02
Net framework session02Net framework session02
Net framework session02Vivek chan
 
04 intel v_tune_session_05
04 intel v_tune_session_0504 intel v_tune_session_05
04 intel v_tune_session_05Vivek chan
 
03 intel v_tune_session_04
03 intel v_tune_session_0403 intel v_tune_session_04
03 intel v_tune_session_04Vivek chan
 
02 intel v_tune_session_02
02 intel v_tune_session_0202 intel v_tune_session_02
02 intel v_tune_session_02Vivek chan
 
01 intel v_tune_session_01
01 intel v_tune_session_0101 intel v_tune_session_01
01 intel v_tune_session_01Vivek chan
 
09 intel v_tune_session_13
09 intel v_tune_session_1309 intel v_tune_session_13
09 intel v_tune_session_13Vivek chan
 
07 intel v_tune_session_10
07 intel v_tune_session_1007 intel v_tune_session_10
07 intel v_tune_session_10Vivek chan
 
02 asp.net session02
02 asp.net session0202 asp.net session02
02 asp.net session02Vivek chan
 
01 asp.net session01
01 asp.net session0101 asp.net session01
01 asp.net session01Vivek chan
 

Mehr von Vivek chan (20)

Deceptive Marketing.pdf
Deceptive Marketing.pdfDeceptive Marketing.pdf
Deceptive Marketing.pdf
 
brain controled wheel chair.pdf
brain controled wheel chair.pdfbrain controled wheel chair.pdf
brain controled wheel chair.pdf
 
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)
 
Manav dharma shashtra tatha shashan paddati munshiram jigyasu
Manav dharma shashtra tatha shashan paddati   munshiram jigyasuManav dharma shashtra tatha shashan paddati   munshiram jigyasu
Manav dharma shashtra tatha shashan paddati munshiram jigyasu
 
Self driving and connected cars fooling sensors and tracking drivers
Self driving and connected cars fooling sensors and tracking driversSelf driving and connected cars fooling sensors and tracking drivers
Self driving and connected cars fooling sensors and tracking drivers
 
EEG Acquisition Device to Control Wheelchair Using Thoughts
EEG Acquisition Device to Control Wheelchair Using ThoughtsEEG Acquisition Device to Control Wheelchair Using Thoughts
EEG Acquisition Device to Control Wheelchair Using Thoughts
 
Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant
 
Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant Vivek Chan | Technology Consultant
Vivek Chan | Technology Consultant
 
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)
 
Net framework session01
Net framework session01Net framework session01
Net framework session01
 
Net framework session03
Net framework session03Net framework session03
Net framework session03
 
Net framework session02
Net framework session02Net framework session02
Net framework session02
 
04 intel v_tune_session_05
04 intel v_tune_session_0504 intel v_tune_session_05
04 intel v_tune_session_05
 
03 intel v_tune_session_04
03 intel v_tune_session_0403 intel v_tune_session_04
03 intel v_tune_session_04
 
02 intel v_tune_session_02
02 intel v_tune_session_0202 intel v_tune_session_02
02 intel v_tune_session_02
 
01 intel v_tune_session_01
01 intel v_tune_session_0101 intel v_tune_session_01
01 intel v_tune_session_01
 
09 intel v_tune_session_13
09 intel v_tune_session_1309 intel v_tune_session_13
09 intel v_tune_session_13
 
07 intel v_tune_session_10
07 intel v_tune_session_1007 intel v_tune_session_10
07 intel v_tune_session_10
 
02 asp.net session02
02 asp.net session0202 asp.net session02
02 asp.net session02
 
01 asp.net session01
01 asp.net session0101 asp.net session01
01 asp.net session01
 

Kürzlich hochgeladen

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 

Kürzlich hochgeladen (20)

Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 

Complete C programming Language Course

  • 2. www.cyberlabzone.com Topics for C Language 1.Introduction to C language 2.Programming Languages 3.Data Types 4.Basic Input/Output (I/O) 5.Control Constructs 6.Array 7.Fuctions 8.Program Design Example 9.Pointers 10.Structures & Unions 11.File Operation in C 12.The C Preprocessor 13.Computational Complexity
  • 3. www.cyberlabzone.com Introduction to C languages C is a traditional, Procedural language,i.e. one that requires the programmer to provide step-by-step instructions for the processor (i.e., the main logic unit of a computer). The great success of C is due to its simplicity, efficiency, flexibility and small memory requirements. It is also due to the portability of programs that are written in it, i.e., the ability to be easily adapted to new platforms (i.e., operating systems and processors). C's great portability is in very large part a result of the fact that compilers and libraries are available for numerous platforms. A compiler is a specialized computer program that converts source code (i.e., the original, human-readable form of a program typed into a computer by a programmer in a programming language) into another language, usually machine language (also called object code or machine code) so that it can be directly understood by processors. A library is a collection of routines (also called subprograms, procedures or functions) that perform operations which are commonly required by programs.
  • 4. www.cyberlabzone.com Programming Languages Programming Languages classified as ”Low Level/High Level” 1.Low Level •Machine Language (binary-based code; machine dependent) • Assembly Language (mnemonic form of machine language) 2.High Level Closer to natural languages. Generally, machine independent Usually, several machine instructions are combined into one high- level instruction. Examples: FORTRAN, COBOL,BASIC, Java, Pascal, Ada, PL/I, Lisp, C GPSS,C++, Matlab
  • 5. www.cyberlabzone.com Processing a High-level Language Program Programs written in high-level languages must be converted to machine language. Two approaches: (1) Compilation used with C, C++, Fortran,... (2) Interpretation Used with Matlab, Visual Basic,...
  • 6. www.cyberlabzone.com STEP 1) Use Dos Prompt to create a “Directory”. In this Directory We write and save all Programme name source files with a suffix “.c”. STEP 2)In Dos Prompt to compile the desired Programme we use “Ctrl +F9” to get a desired result While programme is on the monitor . STEP 3) Check the error if any caught by compiler, remove that error and go back to step 2,repeat whole process again. STEP 4) Run the program by using “Ctrl+F9” and for OUTPUT we use “Alt+F5” in the Dos prompt. Compilation (In Window Environment)
  • 7. www.cyberlabzone.com C Program Examples 1. Requirements Specification (Problem Definition) Write a simple C program to request the users’ SSN and print the message “Hello (SSN)!” (where SSN is the value the user supplied) to the screen of the computer monitor. 2. Analysis---Refine, Generalize, Decompose the problem definition (i.e., identify sub problems, I/O, etc.) Input = SSN Output= A prompt for the SSN then “Hello (SSN)!” 3. Design---Develop Algorithm Pseudo-code Algorithm print “Enter SSN (no dashes)” read SSN print “Hello (SSN) !” 4. Implementation --- Write the "Program" (Code)
  • 8. www.cyberlabzone.com C Examples /* C Program to greet the user */ #include <stdio.h> /* makes the function printf “known” */ /* to the C compiler */ void main(void) { int ssn; /* variable ssn declared */ printf(”Please enter your SSN (no dashes):”); scanf(”%d”,&ssn); /* read the SSN */ printf(”Hello %d !n”,ssn); /* print the message */ }
  • 9. www.cyberlabzone.com Main Function #include ... /* preprocessor directive */ . . . void main(void) /*function header*/ { . . /* function body */ . } In the following set of slides we will define the component parts of the main function.
  • 10. www.cyberlabzone.com Preprocessor Directives #include ... /* preprocessor directive */ . . . void main(void) { . . . } Statements beginning with the symbol # are called preprocessor directives. The #include directives allow the C program to access libraries of functions that are not available directly in C. These libraries are referred to as header files: stdio.h standard input-output functions math.h math functions stdlib.h a “standard” library of functions
  • 11. www.cyberlabzone.com Main Function Header #include ... . . . void main(void) /*function header*/ { . . . } The “initial” input is any value(s) passed at initial execution, e.g. >a.out 1.0 3.5 Typing the above at the Unix prompt attempts to pass the values 1.0 and 3.5 to main. At this point we will not do this. The header for the programs in some C programs is of the form: int main(void) and there is a corresponding statement in the function body: return (0); main has no “initial” input values. (see below) main function returns no value
  • 12. www.cyberlabzone.com Main Function (body) #include ... . . . void main(void) { . . /* function body */ . } • The body of a function is all the declarations and executable statements between the braces (in the block). The declarations must precede the executable statements in this block. • When you run a program, the first statement executed is the first (from the top of the file) executable statement in main. The execution of statements proceeds until the terminating “}” right brace is encountered or a return statement is executed. a “block” in C is defined by a set of curly braces.
  • 13. www.cyberlabzone.com Declaration #include <stdio.h> void main(void) { int ssn; /* variable ssn declared */ printf(”Please enter your SSN (no dashes):”); scanf(”%d”,&ssn); printf(”Hello %d !n”,ssn); } One form of a declaration in C : data-type variable_name ;
  • 14. www.cyberlabzone.com Data Types Fixed Point(Integers) Floating Point Character short float char int double long long double
  • 15. www.cyberlabzone.com Variable Names Variable Names - reference to memory locations storing data values. A variable name is one example of an identifier in C. An identifier can use a combination of letters, numerical digits, and the underscore ( _ ) that starts with a letter. Only the first 31 characters of an identifier are recognized by most compilers. Identifiers cannot be the same as a reserved word or keyword, such as void, float, or return. Examples: x sum force2 rate_Of_Change Examples of invalid variable names (why?): 2force rate-of-change x.5 return C case-sensitive, so that the following three names all represent different variables (i.e., different storage locations): time Time TIME
  • 16. www.cyberlabzone.com #include <stdio.h> void main(void) { int ssn; printf(”Please enter your SSN (no dashes):”); scanf(”%d”,&ssn); printf(”Hello %d !n”,ssn); } The printf and scanf functions appear in ‘expression’ statements. 1st executable statement 3rd executable statement 2nd executable statement Executable Statements
  • 17. www.cyberlabzone.com Executable Statements Statements are grouped by their type: expression statement do-while and while statements for statement if and if-else statements return statement switch statement assignment statement Every executable statement in C must be followed by a “ ; “ semicolon.
  • 18. www.cyberlabzone.com Assignment Statement •Interpretation: compute the value on the right-hand-side of the = and put this value in memory at location named (or tagged) by the name variable . • an expression can be a constant, a variable or operators with operands. variable = expression;
  • 19. www.cyberlabzone.com Constants Literal Constants(examples) Numeric: 3 6.248 -7.25 1.5e4 (=15000) Single Character: 'A' 'a' '9' '+' ' ' Character String: “Enter a positive number: ” Symbolic Constants(example) #define PI 3.14159265 /* preprocessor directive */ By default, constants declared in #define are of type double. Standard practice is to use all upper-case letters for the constant name, to avoid confusion with a variable name. A “constant” means you cannot change the value, e.g. PI = 3.0; will generate a compiler error from gcc.
  • 20. www.cyberlabzone.com Arithmetic Operators - for integer arithmetic, the / operator yields an integer result, and % gives the remainder after dividing two integers. E.g., 5 / 3 1 5 / 6 0 5 % 3 2 5 % 6 5 (Note: division by 0 creates an "overflow" run-time error.) - use arithmetic operators, with parentheses for grouping; e.g., (a - b) / (2 * c) e.g, without parentheses, the example above would evaluate b/2 first, then do the multiplication, then the subtraction. +, - , * , / , % (modulus) (no ^ operator as in Matlab)
  • 21. www.cyberlabzone.com Rules of Precedence ( ) Higher *, /, % (left to right for tie) +, - (left to right for tie) Lower Examples, : x = 3 + 2 * 3; /* x now has the value 9 */ y = 3 * 2 % 3; /* y now has the value 0 */ - Precedence Order for Arithmetic Operators:
  • 22. www.cyberlabzone.com Understanding the Assignment statement • Example int time; . . . time = 0; . 0time 1200 Main Memory Memory map after the assignment statement time = 0 is executed . unknowntime 1200 Main Memory Memory map before the assignment statement time = 0 is executed
  • 23. www.cyberlabzone.com Understanding the Assignment statement • Example double force; force = 5.0; . . . force = force * 3.0; . 15.0force 1400 Main Memory Memory map after the assignment statement force = force * 3.0; is executed . 5.0force 1400 Main Memory Memory map before the assignment statement force = force * 3.0; but after force = 5.0; is executed
  • 24. www.cyberlabzone.com Character Values Individual characters may be assign to variables of data-type char. Example: Write a program to prompt the user for a Y/ N response. Print the users response to the screen. #include <stdio.h> void main(void) { char letter; printf(“Please enter a response (Y/N):”); scanf(“%c”,&letter); printf(“Your response was: %c n”,letter); }
  • 25. www.cyberlabzone.com Expression Statements One form of a expression statement in C : function(argument list) ; Scanf function accepts input from standard input device, usually a keyboard scanf("format string", &var1, &var2, ...); The number of conversion specifiers should match the number of variables that follow the “format string”. %i,%d - decimal integer (d=decimal) %f - float %lf - double(where lf="long float") %Lf - long double %c - character where “format string” is the string of conversion specifiers for the various data types in the variable list. e.g.,
  • 26. www.cyberlabzone.com Basic Input/Output (I/O) sends output to standard output device, usually a video monitor printf("format string", output-list); where ”format string” can contain characters to be output and the conversion specifiers indicating type and position of the output values. For output, we specify formats conversion specifiers) a little differently than we do for input. For example: %i, %d -decimal integer %o -octal integer %x, %X -hex integer (use X for caps A - F) %f -float, double %c -character %s -character string Printf function
  • 27. www.cyberlabzone.com Output Control: Special characters Each is represented by an escape sequence, which is a backslash () and an escape character. Examples are: " - output double quotes b – backspace ? - output question-mark character (?) - output backslash character () n - new line
  • 28. www.cyberlabzone.com Output Control: Field Width The number of print positions to be used in the output of display values. For floating-point numbers, we can also specify the number of digits to be displayed after the decimal point. Examples: %3d - display an integer using 3 print positions. %7.3f - display a floating-point number (float, or double) using a total field width of 7 and with 3 places after the decimal point.
  • 29. www.cyberlabzone.com Printf and scanf Examples Example: scanf("%i %f %lf %c", &n, &a, &x, &code); Example: printf("The sum of %i values is %f.n“,numValues, sum); printf("%sn", "Temperature Variations"); printf("The output is: n");
  • 30. www.cyberlabzone.com Comments Comments in C are of the general form: /* . . . */ Comments can be inserted anywhere you can put a space (blank). Comments are ignored by the C compiler and not included in the executable file. The */ can be on the next line but then every character between the /* and the */ is ignored by the C compiler.
  • 31. www.cyberlabzone.com Programming Errors Syntax Errors Run-time Errors Logical Errors The gcc compiler will catch these errors and give you Error messages. Example: x + 1 = x; (should be x = x+1; for a valid assignment statement) The gcc compiler will not catch these errors. Example: User enters the value 0 and your code reads this value into variable x, and then computes 1/x . The gcc compiler will not catch these errors. Program will run and not generate any error messages but results outputted by the program are incorrect. Example: User programs solution using the wrong formula.
  • 32. www.cyberlabzone.com 1. Problem Definition Write a program that reads a number and computes the square root if the number is non-negative. 2. Refine, Generalize, Decompose the problem definition (i.e., identify subproblems, I/O, etc.) Input = real number Output=real number 3. Develop Algorithm (processing steps to solve problem) C problem examples
  • 33. www.cyberlabzone.com C problem Example Flowchart Print “enter value” Read value value >= 0.0 Print sqrt(value) TrueFalse
  • 34. www.cyberlabzone.com C program Example /* C Program to compute the square root of a positive number */ #include <stdio.h> #include <math.h> void main(void) { double value; /* Declare variables. */ printf(”Please enter a non-negative number :”); /* request user input */ scanf("%lf", &value); /* read value */ /* Output the square root. */ if (value >= 0.0) printf(”square_root(%f) = %f n", value,sqrt(value)); }
  • 35. www.cyberlabzone.com Selection Structures Decision statements if(expression) statement; • if expression evaluates to true, the statement is executed; otherwise execution passes to the next statement in the program. • if Selection Structure if(value >= 0.0); printf(”square_root(%f) = %f n", value,sqrt(value)); /* Error! Don’t put semicolon here */ /* This is an example of a logical error */ 1. Problem Definition Modify the previous program to notify the user when the input is invalid.
  • 36. www.cyberlabzone.com C Program Examples (Modified) Flowchart Print “enter value” Read value value >= 0.0 Print sqrt(value); TrueFalse Print “invalid input”
  • 37. www.cyberlabzone.com C Program Examples (Modified) /* C Program to compute the square root of a positive number */ #include <stdio.h> #include <math.h> void main(void) { double value; /* Declare variables. */ printf(”Please enter a non-negative number :”);/*request user input*/ scanf("%lf", &value); /* read value */ /* Output the square root. */ if (value >= 0.0) printf(”square_root(%f) = %f n", value,sqrt(value)); else printf(“invalid user input, please enter non-negative valuen”); }
  • 38. www.cyberlabzone.com Math Library in C - in header file math.h Arguments (parameters) for each of the following functions are assumed to be of type double. If not, a type double copy is made for use in the function. To compile a program that contains math functions you need to use the -lm (Lm not 1m )option for gcc. > gcc file.c -lm See next slide
  • 39. www.cyberlabzone.com fabs (x) - |x| sqrt (x) - square root of x pow (x, a) - x to the power ‘a’ exp (x) - e to the power ‘x’ (e = 2.718281828 …) log (x) - ln x = loge x log10 (x) - log10 x sin (x) - sine function (x in radians) cos (x) - cosine function (x in radians) tan (x) - tangent function (x in radians) fmod (a, b) - remainder of a/b in floating-point ceil (x) - smallest integer >= x floor (x) - largest integer <= x
  • 40. www.cyberlabzone.com If- else Selection Structure if (expression) statement1; else statement2; -if expression evaluates to true, statement1 is executed and execution skips statement2 -If expression evaluates to false, execution skips statement1 , statement2 is executed Control Constructs
  • 41. www.cyberlabzone.com We can also execute multiple statements when a given expression is true: if (expression) { if-statement1; if-statement2; if-statementn; } Example - if(b < a){ temp = a; a = b; b = temp; } or ... if (expression) { if-statement1; if-statement2; if-statementn; } else { else-statement1; else-statement2; else-statementm; } (what does this code accomplish?) ... ... If-else Selection Structure
  • 42. www.cyberlabzone.com C Problem Example 1. Problem Definition Modify the previous program to compute the following: You must check that the value is legal, i.e. value >= 1.0 or value <= -1.0 0.1 2 value
  • 43. www.cyberlabzone.com C Problem Example Flowchart Print “enter value” Read value value >= 1.0 or value <= - 1.0 Print sqrt(value*value - 1.0); TrueFalse Print “invalid input”
  • 44. www.cyberlabzone.com /* C Program to compute the square root of */ /* value*value -1.0 */ #include <stdio.h> #include <math.h> void main(void) { double value; /* Declare variables. */ /* request user input*/ printf(”Please enter value >= 1.0 or <= -1.0 :”); scanf("%lf", &value); /* read value */ /* Output the square root. */ if ((value >= 1.0) || (value <= -1.0)) printf(”square_root(%f) = %f n", value,sqrt(value*value - 1.0)); else { printf(“invalid user inputn”); printf(“input should be a value >= 1.0 or <= -1.0 n”); } } C Problem Example (Modified)
  • 45. www.cyberlabzone.com Logical Expression (Relational Operator) In logical expressions (which evaluate to true or false), we can use the following Relational operators: Relational Operator Type of Test == equal to (don’t use =) != not equal to > greater than >= greater than or equal to < less than <= less than or equal to
  • 46. www.cyberlabzone.com Logical Expression (Relational Operations) Logical(Boolean) Operators && and (true if both true) || or (true if at least one is true) ! not (a unary operator) Operation In logical expressions (which evaluate to true or false), we can use the following Logical operators:
  • 47. www.cyberlabzone.com Logical Expressions int ans, x = 3, y = 4; ans = (x < 5)||(y >= 5); /* ans now has the value 1 */ ans = (x < 5)&&(y >= 5); /* ans now has the value 0 */ In C the value for False is represented by the value zero and True is represented by any nonzero value. The value False can be any zero value such as the number 0 or 0.0 or null character ‘ 0 ’ or the NULL pointer. Example 2: int x = 0; /* x declared as an integer variable */ /* and initialized to the value 0 */ if (x = 0) /* note the error, == should be used */ printf(“ x is zeron”); /*message not printed, why?*/ Example 1: Caution: Avoid testing floating- point numbers for equality! Why?
  • 48. www.cyberlabzone.com Nested if- else Selection Structure 1. Problem Definition Write a program that returns a letter grade based on a quiz score. The input will be the integer score from a 10 point quiz. The letter grades are assigned by: 9 - 10 “A” 7 - 8 “B” 5 - 6 “C” 3 - 4 “D” < 3 “F” 2. Refine, Generalize, Decompose the problem definition (i.e., identify subproblems, I/O, etc.) Input = integer score Output=character “grade” 3. Develop Algorithm (processing steps to solve problem)
  • 49. www.cyberlabzone.com C Problem Example Flowchart Print “enter score” Read score score == 10 || score == 9 Print “A” TrueFalse (continued on next slide) (skip else part of statement)
  • 50. www.cyberlabzone.com C Problem Example False score == 8 || score == 7 Print “B”; True (skip else part of statement) (continued on next slide) False
  • 51. www.cyberlabzone.com C Problem Example False score == 6 || score == 5 Print “C”; True (skip else part of statement) (continued on next slide) False
  • 52. www.cyberlabzone.com C Problem Example False score == 4 || score == 3 Print “D” True False Print “F”
  • 53. www.cyberlabzone.com C Problem Example /* C Program to compute the letter grade for a quiz. */ #include <stdio.h> void main(void) { int score; /* Declare variables. */ printf(”Please enter a score :”); /* request user input */ scanf("%i", &score); /* read value */ /* Output the grade */ /* continued on the next slide */
  • 54. www.cyberlabzone.com C Problem Example if ((score == 10) || (score == 9)) printf(“An”); else if ((score == 8) || (score == 7)) printf(“Bn”); else if ((score == 6) || (score == 5)) printf(“Cn”); else if ((score == 4) || (score == 3)) printf(“Dn”); else printf(“Fn”); } /* end of program */ Unless { } are used the else matches the first if in the code above.
  • 55. www.cyberlabzone.com Switch Selection structure 1. Problem Definition Redo the previous problem by using a switch statement rather than the nested if-else statement. Pseudo-code Algorithm print “enter score” read score switch score score = 9,10 print “A” score = 7,8 print “B” score = 5,6 print “C” score = 3,4 print “D” otherwise print “F”
  • 56. www.cyberlabzone.com C Program Example /* C Program to compute the letter grade for a quiz. */ #include <stdio.h> void main(void) { int score; /* Declare variables. */ /* request user input */ printf(”Please enter a score :”); scanf("%i", &score); /* read value */ /* Output the grade */ /* continued on the next slide */
  • 57. www.cyberlabzone.com C Program Example switch (score) { case 10: case 9: printf(“An”); break; case 8: case 7: printf(“Bn”); break; case 6: case 5: printf(“Cn”); break; case 4: case 3: printf(“Dn”); break; default: printf(“Fn”); } /* end of switch */ } /* end of program */
  • 58. www.cyberlabzone.com Switch Selection Structure The switch structure can be used when we have multiple alternatives based on a value of type int or type char (but not floating point). This structure has the general form: switch (controlling expression) { case label1: statements1; case label2: statements2; default: default statements; } (controlling expr. must evaluate to an integer or a character value; each case should end with a break stmt.) ...
  • 59. www.cyberlabzone.com 1. Problem Definition Use a while statement to read a list of integers from a file and compute the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = integers from file “input.dat” Output=real number representing the arithmetic average =(sum of values)/(count of number of values) 3. Develop Algorithm (processing steps to solve problem) C problem Example
  • 60. www.cyberlabzone.com Flowchart while EOF != scanf value total = total + value; count = count + 1; TrueFalse total = 0; count = 0; printf total/(double) count (double) is a cast see slide #14 C problem Example
  • 61. www.cyberlabzone.com /* C Program to compute the average of a list of numbers. */ #include <stdio.h> void main(void) { int value,total = 0,count = 0; /*Why are total and count set to zero?*/ while (EOF != scanf("%i", &value)) { /* read value */ total = total + value; count = count + 1; } /* end of while loop */ /* Output the average. */ printf(”Average of the %i numbers = %f n“,count,total/(float)count); } C problem Example
  • 62. www.cyberlabzone.com 1. Use xemacs to enter the above code in a file problem1.c , and make sure to save the file. 2. Use xemacs to create an input file input.dat and enter in integers into this file. Save and exit this file. 3. Compile the problem1.c code by typing gcc problem1.c C problem Example-Execution
  • 63. www.cyberlabzone.com 4. Run the program using Unix redirection < a.out < input.dat 5. What happens if you type a.out < input.dat > output.dat Note: if you do this a second time it will fail because Unix will not let you over-write an existing file. 6. To append the results to the existing file output.dat a.out < input.dat >> output.dat C problem Example-I/O Redirection
  • 64. www.cyberlabzone.com A second form of a declaration in C : data-type variable_name = initializer; /*Why are total and count initialized to zero?*/ Answer: Un-initialized variables have unknown (garbage) values. int value,total = 0,count = 0; Assignment statement
  • 65. www.cyberlabzone.com while(expression) statement; • if expression evaluates to true, the statement is executed and then execution loops up and re-evaluates expression; otherwise execution passes to the next statement in the program. • while statement format while(value >= 0.0); /* Error! Don’t put semicolon here */ /* This is an example of a logical error*/ while (EOF != scanf("%i", &value)) { /* read value */ total = total + value; count = count +1; } /* end of while loop */ While-loop Statement
  • 66. www.cyberlabzone.com We can also execute multiple statements when a given expression is true: while (expression) { while-statement1; while-statement2; while-statementn; } • if expression evaluates to true, all the statements are executed and then execution loops up and re-evaluates expression; otherwise execution passes to the next statement in the program. While-General Format
  • 67. www.cyberlabzone.com { statement1; statement2; . . . statementn; } A sequence of statements surrounded by a pair of curly braces is called a block or compound statement 1) From outside, the compound statement looks like a single statement. A compound statement can go where any single C statement can go. (e.g. a branch of if-else, body of a for loop, ...) What is a Compound statement?
  • 68. www.cyberlabzone.com What is all this fuss about blocks? A block is any compound statement that may include variable declaration(s). 1.As a compound statement, from outside, the block looks like a single C statement. A block can go where any single C statement can go. 2.The importance of a block is that, the curly braces of the block delimit the Scope (i.e. the region of validity) of the variables declared in the block. 3. The concept of Scoping lies at the heart of Structured Programming, as will be discussed in a future lecture on Modularity.
  • 69. www.cyberlabzone.com The program makes use of the fact that the scanf function returns and integer value representing the number of successful conversions. For example in the code fragment: Example: int number,value1,value2,value3; number = scanf(“%d%d%d”,&value1,&value2,&value3); the variable number could take the value 0,1,2 or 3. EOF is a built-in constant in C(usually assigned -1). If you are checking for End-of-File then use this constant. EOF != scanf("%i", &value) Scanf-Revisited
  • 70. www.cyberlabzone.com To fix the above use the cast operator where data_type is a valid C data type. float result; int total = 10 , count = 4 ; result = total / (float) count; /* result now has the value 2.5 */ Example, float result; int total = 10 , count = 4 ; result = total / count; /* result has the value 2.0 */ ( data_type ) printf(”Average of the %i numbers = %fn“,count, total/(float)count ); Arithmetic Conversions-Cast
  • 71. www.cyberlabzone.com data_type1 x; data_type2 result; result = x; If x and result have different data types then an automatic conversion takes place. Data could be lost. Example, float x = 3.1416; int result; result = x; /* result now has the value 3 */ 1) Conversion of assigned values Arithmetic Conversions
  • 72. www.cyberlabzone.com +, - , * , /x op y ; where op is If x and y have different (mixed) data types then C automatically converts data from the lower rank to the higher rank and then performs the computation. Note: % (modulus) is only defined on integers. The ranking is given by the following table. long double Higher double float long integer integer short integer Lower 2) Conversion of values with mixed data types in an expression using arithmetic operators Arithmetic Conversions
  • 73. www.cyberlabzone.com Example, float result , x = 3.1416; int y = 3; result = x + y; /* result now has the value 6.1416 */ Example, int x = 2.5; float result, y; y = x; result = 1 / y; /* result now has the value .5 */ Arithmetic Conversions
  • 74. www.cyberlabzone.com 1. Problem Definition Write a program that reads a file of characters one character at a time and writes out each non-blank character to another file. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = characters in a file “input2.dat” Assume this file is non-empty. Output=Non-blank characters from input2.dat are output to the file output2.dat 3. Develop Algorithm (processing steps to solve problem) C Problem Example
  • 75. www.cyberlabzone.com Flowchart while EOF != scanf c TrueFalse scanf c if c != ‘ ‘ /* a blank */ printf c C Problem Example
  • 76. www.cyberlabzone.com /* C Program to remove the blanks from a text file. */ #include <stdio.h> void main(void){ char c; scanf("%c",&c); do { if (c != ' ') printf("%c",c); } while(EOF != scanf("%c",&c)); } C Problem Example
  • 77. www.cyberlabzone.com 1. Use xemacs to enter the above code in a file problem2.c , and make sure to save the file. 2. Use xemacs to create an input file input2.dat and enter in any number of lines of text including blanks. Save and exit this file. 3. Compile the problem2.c code by typing gcc problem2.c 4. Run the program using Unix redirection < and > a.out < input2.dat > output2.dat 5. View the contents of output2.dat more output2.dat C Problem Example-Execution
  • 78. www.cyberlabzone.com do statement; while(expression); • The statement is executed first. Then if expression evaluates to true, execution loops up and the statement is executed again; otherwise execution passes to the next statement in the program. The general form of the do-while statement is: • do/while statement format do { while-statement1; while-statement2; while-statementn; } while (expression); C Problem Example
  • 79. www.cyberlabzone.com 1. Problem Definition Use a for statement to read a list of integers from a file and compute the average. The first number in the list gives the count of the numbers to be read. This first value is not used in the computation of the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = integers from file “input3.dat” Output=real number representing the arithmetic average (sum of values)/(count of number of values) 3. Develop Algorithm Use a counter controlled loop. (processing steps to solve problem) C Problem Example
  • 80. www.cyberlabzone.com Flowchart for i = 1 ; i <= count; i=i+1 scanf value total = total + value; TrueFalse total = 0; scanf count printf total/(double) count C Problem Example
  • 81. www.cyberlabzone.com /* C Program to compute the average of a list of numbers. */ #include <stdio.h> void main(void) { int value,total = 0,count; int i; /* loop counter */ scanf(“%i”,&count); for(i=1;i<=count;i=i+1) { scanf(“%i”,&value); /* read value */ total = total + value; } /* end of for loop */ /* Output the average. */ printf(”Average of the %i numbers = %f n“,count,total/(float)count); } C Problem Example
  • 82. www.cyberlabzone.com 1. Use xemacs to enter the above code in a file problem3.c , and make sure to save the file. 2. Use xemacs to create an input file input3.dat and enter in integers into this file .The first integer is the count of integers to be averaged. Save and exit this file. 3. Compile the problem1.c code by typing gcc problem3.c 4. Run the program using Unix redirection < a.out < input3.dat C Problem Example-Execution
  • 83. www.cyberlabzone.com for(init. expressions ; expression ; update stmnts. ) statement1; C allows more than one initialization expression or update statement but these statements or expressions must be separated by a comma not a semicolon. Also, if there is more than one init. expression or update statement then the order of execution is from left to right. The initialization expressions are executed once (and only once) . If expression evaluates to true, statement1 is executed and execution loops up and evaluates all the update stmnts. and then expression is re-evaluated; otherwise execution passes to the next statement in the program. The following order of must be observed … init. expressions; expression ; update stmnts for-loop Statement
  • 84. www.cyberlabzone.com for(init. expressions ; expression ; update stmnts. ){ statement1; statement2; . . . statementn; } The initialization expressions are executed once (and only once) , next: if expression evaluates to true, the statements statement1,... ,statementn are executed and execution loops up and evaluates all the update stmnts. and then expression is re-evaluated; otherwise execution passes to the next statement in the program. for-General Format
  • 85. www.cyberlabzone.com Write a code fragment to add the integers from 1 to 100. int i,total; total = 0; for(i=1;i<=100;i=i+1) total = total + i; The above code could be re-written as: int i,total; for(i=1, total = 0; i<=100; total=total+i, i=i+1); but not as: int i,total; for(i=1, total = 0; i<=100; i=i+1, total=total+i); Why not? The order of the statements is critical! for-Examples
  • 86. www.cyberlabzone.com 1. Problem Definition Use a for statement to read a list of integers from a file and compute the average. Read the integers until the sentinel value of -999 occurs. Do not use the sentinel value in the computation of the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = integers from file “input4.dat” Output=real number representing the arithmetic average (sum of values)/(count of number of values) 3. Develop Algorithm (processing steps to solve problem) C Problem Example-Revisited
  • 87. www.cyberlabzone.com Flowchart for i = 1 ; ; i=i+1 scanf value if value == -999 break; total = total+value; TrueFalse total = 0; printf total/(float) (i-1) C Problem Example-Revisited
  • 88. www.cyberlabzone.com /* C Program to compute the average of a list of numbers. */ #include <stdio.h> void main(void) { int value,total = 0,count; int i; /* loop counter */ for(i=1; ;i=i+1) { scanf(“%i”,&value); /* read value */ if (value == -999) /* -999 is the sentinel value */ break; total = total + value; } /* end of for loop */ /* Output the average. */ count = i-1; printf(”Average of the %i numbers = %f n“,count,total/(float)count); } C Problem Example-Revisited
  • 89. www.cyberlabzone.com Omitting the logical expression in a for statement means that the for statement executes as an infinite loop. for(i=1; ;i=i+1) { As with the switch statement the break statement causes the termination of the loop but not the program. Break Statement
  • 90. www.cyberlabzone.com A one dimensional array is a list of data values, with all values having the same data type(the base type), such as: • integer • float • double • char Technically, an array is a uniform data structure. Individual array elements are referenced using the array name and a subscript that identifies the element position in the array. What is an Array? Array
  • 91. www.cyberlabzone.com For a one dimensional array, we specify the array name, its base data type, and the number of storage locations required using declarations such as int a[25]; float x[100], y[100]; which specifies 25 integer locations for a and 100 floating- point locations for arrays x and y. Storage for array elements are in contiguous locations in memory, referenced by subscript(or index) values starting at 0. Thus for array a above, the storage is . . . a[0] a[1] a[24] RAM Declaring an Array
  • 92. www.cyberlabzone.com We can initialize array elements in declaration statements; e.g., int counts[5] = {1, 2, 3, 4, 5}; int evens[] = {2, 4, 6, 8}; The array size could also be specified using a symbolic constant: #define ARRAY_SIZE 25 int a[ARRAY_SIZE]; . . . /* evens has 4 elements */ We cannot specify more initial values than there are array elements, but we can specify fewer initial values, and the remaining elements will be initialized to 0. e.g., int b[10] = {2}; double x[250] = {0}; Declaring and initializing an Array
  • 93. www.cyberlabzone.com Note: when referencing a particular element of an array use square brackets, not parenthesis or curly braces. Given that the array x is declared as: int x[250]; To initialize a large array to a nonzero value - say 10, we can use a loop. e.g., for (k = 0; k <= 249; k = k+1) x[k] = 10; k is a subscript Arrays-Subscripting
  • 94. www.cyberlabzone.com A subscript value for an array element can be specified as any integer expression. For example, given the following declarations: double y[4] = {-1.0, 12.0, 3.5, 3.2e-2}; int c = 2; the following statement would assign the value of 5.5 to y[1] y[2 * c - 3] = 5.5; Arrays-Subscripting
  • 95. www.cyberlabzone.com Given an integer value n, we can use the following code to compute and store the first n Fibonacci numbers in an array: 1. Problem Definition Write a program “fib” that prompts the user for an integer n. The program prints the first n Fibonacci numbers. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = n - the count of Fibonacci Numbers to be printed Output= Fib Numbers printed to screen. 3. Develop Algorithm Use the formula: fib0= 1, fib1 =1 and for k > 1 fibk = fibk-1 + fibk-2 Example-Fibonacci Numbers
  • 96. www.cyberlabzone.com #include <stdio.h> /* C program to print the first n Fibonacci Numbers. */ void main(void){ int k,n; int fib[100] = {1,1}; /* note: n must be <= 100 , why ? */ printf(“How many Fibonacci number do you want listed?”); scanf(“%i”,&n); for (k = 2; k < n; k++) /* the ++ is the increment operator */ fib[k] = fib[k-1] + fib[k-2]; /* print the results, four per line */ for (k = 0; k < n;++k){ if (k % 4 == 0) printf(“n”); printf("%8i", fib[k]); /* that’s 8 ints */ } /* end of for loop */ printf(“n”); } /* end of main */ (For large values of parameter n, we would need more space for each print column. Also, even with data type long , the calculated values may become too large for the allocated storage space.)
  • 97. www.cyberlabzone.com : . Since incrementing and decrementing (negative increments) are common programming operations, the C language provides shortcut Increment / Decrement operators. ++k Increment k by 1 and use incremented value in expression containing ++k. k++ Use the current value of k then increment by 1. --k Decrement k by 1 and use decremented value in expression containing --k. k-- Use current value of k then decrement by 1. ++k; Increment and Decrement Operators
  • 98. www.cyberlabzone.com ++k; /*C statement k = k + 1; */ int x,z; int y = 1; int a = 2; x = y + a++; /* now x = 3 , y = 1 , a = 3 */ z = x + --a; /* now a = 2, z = 5, x = 3, y = 1 */ z = --x * ++y; /* now x = 2, y = 2, z = 4, a = 2 */ x = a++ / --y; /* now y = 1, x = 2, a = 3, z = 4 */ Note: The increment/decrement operators can be applied only to single variables. They cannot be applied to expressions. Increment and Decrement Operators-Examples
  • 99. www.cyberlabzone.com Given an integer value n, we can use the following code to compute and store the first n Fibonacci numbers in an array: 1. Problem Definition Write a program that inputs a list of numbers into an array. The program then calculates the average value, and then prints a list of differences. The differences are computed by taking the original values in the list minus the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = list of reals in a file “input.dat” . We will use Unix redirection to read values from this file. Output= The average and the list of differences. Example-Average and difference List
  • 100. www.cyberlabzone.com int counter,k; double datVal[500]; /* 500 element max */ double datAve; double sum = 0.0; /* read the file and compute the average */ counter = 0; while (EOF != scanf("%lf", &datVal[counter])){ sum += datVal[counter]; /* += is an assignment operator */ counter++; } /* compute and print the average */ datAve = sum /counter; printf(“The average is:%lf n", datAve); /* compute and print the diff list */ for(k=0;k<counter;++k) printf(“%lfn", datVal[k]-datAve); Example-Average and difference List
  • 101. www.cyberlabzone.com - a shortcut method for writing assignment statements of the form var1 = var1 op expression; Using an "assignment operator", we can rewrite the above as var1 op= expression; where op can be any one of the arithmetic binary operators: + - * / % sum += datVal[counter]; Assignment-operators
  • 102. www.cyberlabzone.com sum += datVal[counter]; or sum = sum + datVal[counter]; k += 5; or k = k +5; n -= 4; or n = n -4; a *= 2.0; or a = a*2.0; x /= b; or x = x/b; remainder %= 6; or remainder = remainder % 6; newValue += (a-b)/(2*c); or newValue = newValue + (a-b)/(2*c); Assignment-operators-Examples
  • 103. www.cyberlabzone.com Unlike many other languages, there is no data type for character strings in C. But we can reference a string as a one dimensional array of characters. That is, each element of the array is a single character. Character Arrays
  • 104. www.cyberlabzone.com char aString[5] = "Zip!"; char atomic[ ] = "hydrogen"; char aString[] = {'Z', 'i', 'p', '!', '0'}; Declaring a string array with character constants Declaring character arrays with a string constant IMPORTANT!!! In C, you must always terminate a character array with the NULL character, ‘0’ . Therefore, the array size of your character array should be one plus the maximum length of the string you want to store. Example: In the declaration char atomic[ ] = "hydrogen"; “atomic” is an array of nine elements, the last being ‘0’ Declaring a Character Array
  • 105. www.cyberlabzone.com char atomic[ ] = "hydrogen"; You may declare and initialize a character arrays with a string constant as in, but you cannot assign an array in the same manner, e.g. atomic = "hydrogen"; not legal in C! One of the mysteries of C! Declaring a Character Array
  • 106. www.cyberlabzone.com Use the %s conversion specifier to read in a string of characters. Any blanks will be skipped. There should not be any blank character input such as in the string “Hello World”, since a blank signals an end of input for the string. Again, don’t forget to declare the array size as one more than the length of the longest string that you want to read in order to accommodate the NULL character. char strArray [10]; printf("Input a string with at most nine characters ”); printf("with no blanks in the string: n"); scanf("%s", strArray); /* Notice: No & is used for an array argument! */ printf(“n%s", strArray); Input and output of Strings
  • 107. www.cyberlabzone.com You can use the %c conversion specifier to output the string character by character. k = 0; while (strArray[k] != NULL) printf("%c", strArray[k++]); NULL is a built-in constant (‘0’). You must have #include <stdio.h> in your file to be able to use NULL. Outputing a String
  • 108. www.cyberlabzone.com • strlen(str) - string length, not counting NULL char. • strcpy(str1, str2) - copy string2 to string1. • strcmp(str1, str2) - returns a negative , zero or positive int depending on whether str1 is lexicographically less than, equal or greater than str2 respectively. • strncmp(str1,str2,n) - like strcmp but just the first n characters of str1 are compared to str2. #include <string.h> Arguments str1 and str2 in the following functions can be character array names, string pointers(discussed in a future lecture), or string constants. See Chapter 13.3 for examples. There are many other string functions (see Appendix G p. 1036 for a complete list). String.h Library Functions
  • 109. www.cyberlabzone.com 1. Problem Definition Write a C program that converts a Morse code string into alphabet. (Morse code is a sequence of dots and dashes). If the input is not a valid string (see table on next slide) then a message is output to the user. You will do a variation of this program in a future lab assignment. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = a single string of characters. Output= A single letter A-Z. Example-Morse Code
  • 110. www.cyberlabzone.com A .- , N -. B -... O --- C -.-. P .--. D -.. Q --.- E . R .-. F ..-. S ... G --. T - H .... U ..- I .. V ...- J .--- W .-- K -.- X -..- L .-.. Y -.-- M -- Z --..
  • 111. www.cyberlabzone.com #include <stdio.h> #include <string.h> typedef char string[5]; void main(void){ string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.. " };
  • 112. www.cyberlabzone.com char alphabet[26] = {'A','B','C','D','E','F','G','H','I','J','K', 'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; char input[5]; int i; int flag = 0; /* flag = 0 means match not found , flag = 1 means match found */ printf("Please enter a Morse code string:"); scanf("%s",input); /* no & for array */
  • 113. www.cyberlabzone.com /* loop through the Morse array to find a match */ for(i=0;i<26;++i) if (strcmp(input,morse[i]) == 0) { printf("%cn",alphabet[i]); flag = 1; break; /*terminate for loop */ } if (flag == 0) printf("Input not a valid Morse character.n"); } /* end of main */
  • 114. www.cyberlabzone.com The typedef mechanism in C enables a programmer to create a “custom” data-type. Examples of the use of typedef are typedef int blah; /* don’t do this !!!!! */ typedef char string[5]; In the first example we give another name or alias to the data-type int . In the second example we create a new data-type named string. typedef
  • 115. www.cyberlabzone.com To declare a variable of data-type blah , blah x; this declaration is equivalent to int x; To declare a variable of data-type string , string var =“init”; /* declare and initialize */ scanf(“%s”,var); /* we can read in a string of chars */ var = “next”; But we can’t do this!!! The declaration string morse[26]; declares morse as an array of 26 elements. Each element has data-type string. typedef
  • 116. www.cyberlabzone.com The declaration and initialization: string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.. " }; declares morse as an array of 26 elements with morse[0] = “.-” morse[1] = “-...” and so on... typedef
  • 117. www.cyberlabzone.com - Two dimensional arrays are declared similarly to one dimensional arrays: char t[20][10]; (and referred to as a matrix, or as a "table") The first subscript gives the row number, and the second subscript specifies column number. Two-Dimensional Arrays
  • 118. www.cyberlabzone.com We can also initialize a two-dimensional array in a declaration statement; E.g., int m[2][3] = {{1, 2, 3}, {4, 5, 6}}; which specifies the elements in each row of the array (the interior braces around each row of values could be omitted). The matrix for this example is        654 321 m Declaration and Initialization
  • 119. www.cyberlabzone.com Specification of the number of rows could be omitted. But other subscript specifications can not be omitted. So, we could also write the initialization as int m[ ][3] = {{1, 2, 3}, {4, 5, 6}}; Declaration and Initialization
  • 120. www.cyberlabzone.com int a[2][3]= {1,2,3,4,5,6}; specifies 6 integer locations. Storage for array elements are in contiguous locations in memory in row major order (unlike column major order in Fortran), referenced by subscripts(or index) values starting at 0 for both rows and columns. a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] RAM 1 2 3 4 5 6 Memory Storage for a Two dimensional Array
  • 121. www.cyberlabzone.com 1. Problem Definition Assume we have a file “in.dat” (located in the pwd) consisting of 10 rows of 10 integers per row (100 integers total). Write a C program which reads from the file and stores the numbers in a two dimensional array named ‘mat’, computes the largest of all of these numbers and prints the largest value to the screen. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = from file “in.dat” Output= Largest of the 100 integers printed to screen. 3. Develop Algorithm Use Unix redirection to read file “in.dat”. Use nested for loop to go through two dimensional array to find the largest value. Example-Maximum Value
  • 122. www.cyberlabzone.com #include <stdio.h> void main(void){ int row, col, maximum; /* Declare a 2-D array called ‘mat’ which can hold a 10-by-10 */ /* matrix of integers */ int mat[10][10]; /* Write code here to read from the file ‘in.dat’ */ for(row=0;row<10;++row) for(col=0;col<10;++col) scanf(“%d”,&mat[row][col]); /* Write code to find the largest value in the array ‘mat’ */ maximum = mat[0][0]; /* why ??? */ for(row=0;row<10;++row) /* How does this work??? */ for(col=0;col<10;++col) if (mat[row][col] > maximum) maximum = mat[row][col]; /* Print the largest value to the screen */ printf(“ max value in the array = %dn”,maximum); }
  • 123. www.cyberlabzone.com Another example of the use of typedef is: typedef double matrix[size][size]; In this example we create a new data-type named matrix. We can declare a variable of data-type matrix by matrix a; this declaration is equivalent to double a[size][size]; Typedef Revisited
  • 124. www.cyberlabzone.com Standard (ANSI) C allows up to 12 dimension. But more computation is required by the system to locate elements in multi-subscripted arrays. Therefore, in problems involving intensive numerical calculations, we should use arrays with fewer dimension. We can also use 3, 4, … dimensional arrays, e.g., threeDArray [i][j][k]; Higher Dimensional Arrays
  • 125. www.cyberlabzone.com In slides 2-15 and 11-15 we discussed a method for creating programs. In step three “Develop the Algorithm”, the nature of the programming problem may suggest that we use top down programming (as opposed to bottom-up programming , ...) An analogy for top-down design is the following: Suppose a general contractor was hired to construct a commercial building. The contractor would need to know where to build and what are the blue- prints. Then the contractor would hire various sub-contractors to dig foundation, install electric, plumbing, frame, roof. That is, the large job would be broken into smaller jobs, however these jobs must be performed in some sequence and not at random. Function-”Top Down Design”
  • 126. www.cyberlabzone.com In top-down design for programming, we specify the first function to be invoked (the top function or “general contractor”). In C the top function is called “main”. The programmer then refines “main” into its component functions (sub-contractors), which may in turn be refined into further functions, and so on. Function-”Top Down Design”
  • 127. www.cyberlabzone.com 1. Problem Definition Write a program that inputs a list of numbers into an array. The program then calculates the average value, and then prints a list of differences. The differences are computed by taking the original values in the list minus the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = list of reals in a file “input.dat” . We will use Unix redirection to read values from this file. Output= The average and the list of differences. Example-Average and difference List
  • 128. www.cyberlabzone.com #include <stdio.h> int read(double datVal[]); /* prototype for read function */ double ave(int counter,double datVal[]); /* prototype for ave function */ void diff(double datAve, int counter, double datVal[]); /* prototype for diff function */ void main(void){ int counter,k; double datVal[500]; /* 500 element max */ double datAve; counter = read(datVal); /* read file into datVal */ datAve = ave(counter,datVal); /* compute & print average */ printf(“The average is:%f n", datAve); diff(datAve,counter,datVal); /* compute diff list */ for(k=0;k<counter;++k) /* print the diff list */ printf(“%lfn", datVal[k]); } /* end of main */
  • 129. www.cyberlabzone.com /* read function */ int read(double array[]) { int count = 0; while (EOF != scanf("%lf", &array[count])){ ++count; } return count; } /* end of read function */ /* ave function */ double ave(int count,double array[]){ int i; double sum = 0.0; for (i=0;i<count;++i) sum += array[i]; return sum/count; } /* end of ave function */ /* diff function */ void diff(double average, int count, double array[]){ int i; for (i = 0;i<count;++i) array[i] -= average; } /* end of diff */
  • 130. www.cyberlabzone.com 1. Use xemacs to enter the above code in a file problem1.c , and make sure to save the file. 2. Use xemacs to create an input file input.dat and enter in integers into this file. Save and exit this file. 3. Compile the problem1.c code by typing gcc problem1.c 4. Run the program using Unix redirection < a.out < input.dat C Problem Example-Execution
  • 131. www.cyberlabzone.com Example: If the file input.dat has the values: 1.0 2.0 3.0 4.0 5.0 Then the program would execute as follows: dclsn70> a.out < input.dat The average is:3.000000 -2.000000 -1.000000 0.000000 1.000000 2.000000 dclsn70> C Problem Example-Execution
  • 132. www.cyberlabzone.com #include <stdio.h> /* include statements */ int read(double datVal[]); /* prototype for read function */ void main(void) /* definiton of the main function */ { /* C code here */ } /* end of main */ int read(double array[]) /* function definition */ { /* more C code here */ } /* end of read */ One method to code the function “read”in C : Functions-Prototypes Functions
  • 133. www.cyberlabzone.com In the latest versions of standard C ("ANSI C"), the function prototype is used to define the data type to be returned by the function, the number and data type of function parameters, and the order of the function parameters. This info is used by the C compiler to validate calls to the function. A general principle in C is that you must declare or define the variable or function before you use them. Functions-Prototypes
  • 134. www.cyberlabzone.com The actual variable or array name is not needed in the function prototype. Examples: Instead of the following prototypes int read(double datVal[]); double ave(int counter,double datVal[]); void diff(double datAve, int counter, double datVal[]); we could have used int read(double []); double ave(int ,double []); void diff(double , int , double []); Functions-Prototypes
  • 135. www.cyberlabzone.com #include <stdio.h> /* include statements */ /* Since the definition of read occurs before it is */ /* used (called) by main, we don’t need a prototype.*/ int read(double array[]) /* function definition */ { /* C code for read here */ } /* end of read */ void main(void) /* definiton of the main function */ { /* C code for main function here */ } /* end of main */ Another method to code the function “read ” in C without using a prototype : Functions-Prototypes
  • 136. www.cyberlabzone.com • The function definition in C is of the form: return-type function-name(parameter-list) { /* function code */ return (value); /* parenthesis optional */ } • The “value” can be a single variable, constant, or any C expression. • The data type of “value” should be of type “return-type”, if not then a conversion of the “value” to the “return-type” is specified by the C compiler. • If the “return-type is void then the programmer can omit the return statement or code: return ; /* return nothing */ Function- definition
  • 137. www.cyberlabzone.com /* function called */ int x = 1; float y = 2.0; float value; double z = 5.0; value = sum(x,y,z+4.0); /* more code here */ /* sum adds an integer a float and a double and returns */ /* a double */ double sum(int a, float b, double c) { double result; result = a + b + c; return result; } Data-types agree! Since value has type float and sum returns a double, a conversion takes place. Function Type Checking
  • 138. www.cyberlabzone.com • A function that does not return a value is declared to be of type void. e.g., void printFunction (int, int); • If a function takes no parameters, we specify the parameter list as void. e.g., void printPageHeading (void); It is also possible to specify an "empty" parameter list: void myFunction ( ); - argument checking is "turned off", so that anything can be passed to myFunction. Best to avoid this in C. Function Type Checking
  • 139. www.cyberlabzone.com • By default , if you omit the data type of the return value, C assumes that the function returns an int value (not void). Therefore the following function header: main(void) int main(void) is equivalent to: Function Type Checking
  • 140. www.cyberlabzone.com • A function may be called from any function (including itself) in C. • A call is of the form: function-name(argument-list) • To “call” or invoke a function, you must pass the same number of arguments for which the function has been defined. The order of the arguments is important!!! • If the data types in the argument list do not match the data types in the parameter list, a conversion(or coercion) takes place. Function Call
  • 141. www.cyberlabzone.com . . . int x = 1; double y = 2.0; float result; /* function called */ result = F1(x,x+1,sin(y)); /* argument list */ . . . } /* end main */ /* data types match */ float F1(int var1, int var2, double var3){ /*parameter list */ /* function code */ return (value);} Example-Function Type Checking
  • 142. www.cyberlabzone.com • Arrays are passed as call-by-reference. counter = read(datVal); . . . int read(double array[]) { int count = 0; while (EOF != scanf("%lf", &array[count])){ ++count; } return count; } 2.0 1.0 1200 Main Memory after call unknowndatVal[0] datVal[1] datVal[2] 1200 Main Memory before call datVal[0] datVal[1] datVal[2] . . . . . . . . . . . . The parameter “array” can be considered as a pseudonym or alias for “datVal”. There is only one array in memory. Passing arguments in a function Call
  • 143. www.cyberlabzone.com For two dimensional arrays, we could omit specification of the number of rows in function prototype and header. But we must include size declaration for the number of columns. (see example on next slide) Two-Dimensional Arrays Function Parameters
  • 144. www.cyberlabzone.com #define ROWS 10 #define COLS 5 void doSumpin(int [][COLS]); int main (void) { int a[ROWS][COLS] = {{0}}; doSumpin (a); } void doSumpin(int b[][COLS]){ /* array passed by reference */ ... } /* function prototype */ /* function call */ Examples of passing 2-D arrays
  • 145. www.cyberlabzone.com We can replace any 2-D array with an equivalent 1-D array. For instance the following 2-D array int A[2][3]= {1,2,3,4,5,6}; A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2] RAM 1 2 3 4 5 6 can be replaced with the equivalent 1-D array, int a[6]= {1,2,3,4,5,6}; however a[0][0] , a[0][1] , … is not defined. Alternative to 2-D arrays
  • 146. www.cyberlabzone.com In order to reference A[0][0] , A[0][1] , … with a[ ] we use the following formula, int a[]= {1,2,3,4,5,6}; A[row][col] = a[row*3 + col] A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2] RAM 1 2 3 4 5 6 a[0] a[1] a[2] a[3] a[4] a[5] Alternative to 2-D arrays
  • 147. www.cyberlabzone.com 1. Problem Definition Write a function that performs matrix – vector multiplication. Assume that the matrix is passed as a 1-D array using the formula on the previous slide. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = A matrix and vector of reals . Output= The vector that results from the matrix - vector multiplication. Alternative to 2-D arrays
  • 148. www.cyberlabzone.com /* The function mvmult works with any size matrix a. */ /* This function assumes that the number of Cols of a is */ /* equal to the number of Rows of invec */ /* a is 1-D version of matrix A[Rows][Cols] */ void mvmult(double a[], int Rows, int Cols, double invec[], double outvec[]){ int row, col; /* A[row][col] = a[row*cols + col] */ for(row=0;row<Rows;++row){ outvec[row] = 0.0; for(col=0;col<Cols;++col) outvec[row] += a[row*Cols +col] * invec[col]; } } /* end of mvmult */
  • 149. www.cyberlabzone.com 1. Use xemacs to enter the above code in a file mvmult.c , and make sure to save the file. 2. Use xemacs to create a file test.c and write the main function that calls the mvmult function. Don’t forget the prototype! 3. Compile the code in the two files mvmult.c and test.c by typing, gcc test.c mvmult.c -o mult 4. Run the program mult C Problem Example-Execution
  • 150. www.cyberlabzone.com #include <stdio.h> #define ROWS 2 #define COLS 3 mvmult(double [], int , int double [] , double []); /* prototype */ void main(void){ double a[ROWS*COLS] = {1,2,3,4,5,6}; double invec[COLS] = {1,1,1}; double outvec[ROWS]; int row,col; mvmult(a,ROWS,COLS,invec,outvec); /* call mvmult */ for(row=0;row<ROWS;++row) /* print the values of a */ for(col=0;col<COLS;++col) printf("a[%i][%i] = %lfn",row,col,a[row*COLS+col]); for(row=0;row<COLS;++row) /* print invec */ printf("invec[%i] = %lfn",row,invec[row]); for(row=0;row<ROWS;++row) /* print outvec */ printf("outvec[%i] = %lfn",row,outvec[row]); }
  • 151. www.cyberlabzone.com eesn23> mult a[0][0] = 1.000000 a[0][1] = 2.000000 a[0][2] = 3.000000 a[1][0] = 4.000000 a[1][1] = 5.000000 a[1][2] = 6.000000 invec[0] = 1.000000 invec[1] = 1.000000 invec[2] = 1.000000 outvec[0] = 6.000000 outvec[1] = 15.000000 eesn23> C Problem Example-Execution
  • 152. www.cyberlabzone.com • Non-arrays are passed as call-by-value. datAve = ave(counter,datVal); . . . double ave(int count,double array[]){ int i; double sum = 0.0; for (i=0;i<count;++i) sum += array[i]; return sum/count; } 1196 Main Memory while executing ave 5 counter 1196 Main Memory before call counter . . . The value of the parameter “counter” is copied into the memory location for the variable “count”. Therefore any change to “count” would have no affect on “counter”. 1192count 5 55 Passing arguments in a function Call
  • 153. www.cyberlabzone.com 1. Problem Definition Write a function “sinc” that computes the value of sin(x)/x . If x is zero return 1.0. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = One real number of type double. Output= sin(x)/x as a double if x is not zero else 1.0. 3. Develop Algorithm Use an if statement to check for a non-zero value. But since the user could input 1.0e-600 , this may cause an overflow when the value 1/x is computed so we will actually not check for equality with zero but will check if the input value is close to zero. Example-Call-by-value
  • 154. www.cyberlabzone.com #include <stdio.h> #include <math.h> double sinc (double); /* function prototype */ void main(void){ double x, y; printf("Enter a number: "); scanf("%lf", &x); y = sinc(x); /* function call */ printf(“n sinc(%f) = %f n”, x, y); } double sinc (double x){ /* function header */ if (fabs(x) < 1.0e-15) return 1.0; else return sin(x) / x; } /* notice that sinc calls sin */ Example: function sinc(x)=sin(x)/x
  • 155. www.cyberlabzone.com Using Xemacs, user-defined functions can be typed into the same file as “main”. Functions may be typed into a separate file. For example, suppose “main” is in the file test.c and the user defined function “sinc” is entered into the file func.c then to compile both “main” and “sinc” you would type (at the Unix prompt) gcc test.c func.c -lm Note the use of the “-lm” option The -lm option is needed only if you use a math library function in “main” or “sinc”. Don’t forget that if you put the function “sinc” into a separate file, then you must still put the prototype for “sinc” in the same file as main. The prototype for “sinc” must precede the function main. Example: Location of user-defined functions
  • 156. www.cyberlabzone.com We present some methods to debug C programs. We can categorize errors as A) compile errors B) run-time errors C) Logical errors Logical errors are the most difficult since they may involve using the incorrect formula. This has nothing to do with C so we will not discuss these types of errors any further. Debugging
  • 157. www.cyberlabzone.com We present some methods to debug C programs. A) compile errors If your program doesn’t compile. 1) Check the line number that gcc returns for the error. Note: a warning message is not an error. If you only have warning messages gcc will go ahead and compile your code. 2) Sometimes the line number of the error is not where the actual error occurred. An error on one line can produce errors messages for subsequent lines. Therefore it is best in general to fix the errors occurring on the earliest line numbers first. Also, if you can’t find an error on the line specified by gcc then look at the preceding lines. Compiler Errors
  • 158. www.cyberlabzone.com A) compile errors(continued) 3) If you can’t find the error specified by gcc then try removing some code by using the #ifdef feature of C. This is a preprocessor command that will optionally compile (or not compile) a group of statements. Or gcc allows you to use the characters // at the beginning of a line to comment out that line of code. Compiler Errors
  • 159. www.cyberlabzone.com Example: On slide 25 add a semicolon to the which contains the code: if (fabs(x) < 1.0e-15); When you compile you get an error message. The error message states the problem is before line 15 but the actual problem occurred on line 13. dclsn70> gcc test.c -lm test.c: In function `main': test.c:4: warning: return type of `main' is not `int' test.c: In function `sinc': test.c:15: parse error before `else' dclsn70> Compiler Errors
  • 160. www.cyberlabzone.com Example: Use #ifdef to have the compiler skip compiling line(s) of code. From the previous problem add the #ifdef as follows: double sinc (double x){ /* function header */ if (fabs(x) < 1.0e-15); #ifdef foo return 1.0; #endif else return sin(x) / x; } /* notice that sinc calls sin */ Compiler Errors
  • 161. www.cyberlabzone.com From the above we can see that the code now compiles without errors. The reason for this is that the if-else statement is now a valid statement. If the condition is true do nothing else return sin(x)/x . Even if you don’t see the extra semicolon, at this point you know that your if-else statement was the source of your previous compile error. dclsn70> gcc test.c -lm test.c: In function `main': test.c:4: warning: return type of `main' is not `int' dclsn70> Compiler Errors
  • 162. www.cyberlabzone.com B) run-time errors If your program compiles without errors but you get incorrect values or a message like “Segmentation fault”. 1) Use the statement: fprintf(stderr, “format string”,variable-list); Run-time Errors
  • 163. www.cyberlabzone.com On slide 25 remove the “&” symbol to obtain the following line: scanf("%lf", x); When you compile and run a.out you get the run-time error “Segmentation Fault”, dclsn70> gcc test.c -lm test.c: In function `main': test.c:4: warning: return type of `main' is not `int' dclsn70> a.out Enter a number: 3.14159 Segmentation fault dclsn70> Run-time Errors
  • 164. www.cyberlabzone.com Example: Use the fprintf statement to debug your code. void main(void){ double x, y; printf("Enter a number: "); fprintf(stderr,“Before scanfn”); scanf("%lf", &x); fprintf(stderr,”After scanf x = %lfn”,x); y = sinc(x); /* function call */ fprintf(stderr,“After sincn”); printf(“n sinc(%f) = %f n”, x, y); } Run-time Errors
  • 165. www.cyberlabzone.com dclsn70> gcc test.c -lm test.c: In function `main': test.c:4: warning: return type of `main' is not `int' dclsn70> a.out Before scanf Enter a number: 3.14159 Segmentation fault dclsn70> Since only “Before scanf” prints to the screen (specified by stderr). This indicates that the problem occurs in the scanf statement. Run-time Errors
  • 166. www.cyberlabzone.com 1. Problem Definition Write a function “swap” that has two integer input arguments. This function should swap the values of the variables. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = two integers Output= no value is returned to the calling function, but the values of the called variables should be swapped. 3. Develop Algorithm temp = a; a = b; b = temp; Example-call-by-value
  • 167. www.cyberlabzone.com /* C Function to swap values. */ #include <stdio.h> void swap(int, int); /* prototype for swap */ void main(void){ /* function header */ int x = 1; int y = 2; swap(x,y); printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */ } void swap(int a , int b){ int temp = a; a = b; b = temp; return; } Example-bad Swap!!!
  • 168. www.cyberlabzone.com x 1000 Main Memory before call 1 The swap function will successfully swap the values of the variables a and b. But, since non-arrays are passed by value the swap of the values for a and b will not have any affect on the variables x and y. It is important to note that even if we had used the variable names x and y rather than a and b the swap function would still not work. See the next slide... y 2 Main Memory while executing swap, but before the return statement x 1000 1 y 2 a 2 b 1 3000 Why swap doesn’t work.
  • 169. www.cyberlabzone.com /* Modified function to swap values. */ #include <stdio.h> void swap(int, int); void main(void){ int x = 1; int y = 2; swap(x,y); printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */ } void swap(int x , int y){ /* we now use x and y */ int temp = x; x = y; y = temp; return; } Example-bad Swap!!!
  • 170. www.cyberlabzone.com x 1000 Main Memory before call 1 The C compiler will keep track of the variables x and y declared in main and the variables x and y declared in swap. The x in main is a different variable than the x in swap. Similarly for the y variable. The reason that the x variable in main is different than the x variable in swap is that two declarations of x occur in different blocks. That is the scope of the x in main is different than the scope of x in swap. One solution to the problem is to use pointer variables. We will discuss pointer variables in a future lecture. y 2 Main Memory while executing swap, but before the return statement x 1000 1 y 2 x 2 y 1 3000 Why the modified swap doesn’t work.
  • 171. www.cyberlabzone.com An identifier is a name that is composed of a sequence of letters, digits, and the ‘_’ underscore character. Variable names are identifiers and so are function names and symbolic constant names. The scope of an identifier is the portion of the program in which the identifier is visible or accessible. Both variables and functions have two attributes: type and storage class. The scope of a variable or function is related to its storage class. Scope of Identifiers
  • 172. www.cyberlabzone.com •Local Variables - are declared within a block and cannot be referenced by outside the block; i.e., each function is assigned its own "local" storage areas. •Global Variables - declared outside any block and are known to all blocks in the same file . By default, global variables are "static” storage class. In the examples on the following slides, drawing a picture of memory is helpful in understanding how scoping works. Scope of Variable Names
  • 173. www.cyberlabzone.com int globalVar = 1; /* global variable */ int myFunction(int); /* function prototypes */ void main(void){ /* local variable: result, in main */ int result; result = myFunction(globalVar); /* call myFunction */ printf(“%d”,result); /* prints “2” */ printf(“%d”,globalVar); /* prints “2” */ printf(“%d”,x); /* compile error! x not known in main */ } int myFunction(int x){ /* Local variable x */ ++x; printf(“%d”,x); /* prints value “2” */ printf(“%d”,globalVar); /*prints value“1” */ ++globalVar; return x; } Example1:Scope of Variables Program Design Example
  • 174. www.cyberlabzone.com globalVar 1000 Main Memory before call to Myfunction 1 result ??? Main Memory while executing MyFunction, but before ++globalVar; 1000 1 x 2 3000 ??? globalVar result Example1:Scope of Variables
  • 175. www.cyberlabzone.com globalVar 1000 Main Memory after call to Myfunction 2 result 2 Main Memory while executing MyFunction, but before return(x); 1000 2 ??? x 2 3000 globalVar result Example1:Scope of Variables
  • 176. www.cyberlabzone.com int globalVar = 1; /* global variable */ int myFunction(int); /* function prototypes */ void main(void){ /* local variable: result, in main */ int result; result = myFunction(globalVar); /* call myFunction */ printf(“%d”,result); /* prints “2” */ } int myFunction(int x){/* Local variables: x, globalVar */ int globalVar; /* new “local” variable */ printf(“%dn”,globalVar);/* prints ??? */ return x + 1; } Example2:Scope of Variables
  • 177. www.cyberlabzone.com int myFunction(int); /* function prototypes */ void main(void){ /* local variables: x,result in main */ int result, x = 2; result = myFunction(x); /* call myFunction */ printf(“%d”,result); /* prints “3” */ printf(“%d”,x); /* prints “2” WHY??? */ } int myFunction(int x){/* Local variable: x */ x = x + 1; printf(“%dn”,x);/* prints “3” */ return x; } Example3:Scope of Variables
  • 178. www.cyberlabzone.com /* C Function to swap values.This doesn’t work!!!! */ #include <stdio.h> int x; /* x is a global variable */ int y; /* y is a global variable */ void swap(int, int); /* prototype for swap */ void main(void){ x = 1; /* note that x and y are not declared here!!! */ y = 2; swap(x,y); printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */ } void swap(int x , int y){ int temp = x; x = y; y = temp; return; } Example4:Scope of Variables
  • 179. www.cyberlabzone.com A function can be called by any other function, provided that either the function definition or its prototype is in the same file as the calling function and precedes the function call. If no prototype is specified for a function, its header serves as the function prototype. Note: Functions cannot be defined within each other Scope of Function Names
  • 180. www.cyberlabzone.com - Determines the storage duration and scope of identifiers, and also linkage between files. auto - creates storage for variables when the block that declares them is entered, and deletes the storage when the block is exited. Local variables have "auto" storage by default. e.g.,typing auto float a, b, c; is equivalent to typing float a, b, c; Storage Classes-auto
  • 181. www.cyberlabzone.com static - creates and initializes storage for variables when the program begins execution. Storage continues to exist until execution terminates. If an initial value is not explicitly stated, a static variable is initialized to 0. We can retain values of local variables by declaring them to be static. In the following example, the static variable sum is initialized to 1. static int sum = 1; The initialization takes place only once. If the above declaration appears in a user defined function , the first time the function is called, the variable sum is initialized to 1. The next time the function (containing the above declaration) is executed sum is not reset to 1. Storage Classes-static
  • 182. www.cyberlabzone.com extern - used to reference identifiers in another file. Function names are extern by default. e.g., extern int foreignVar; Storage Classes-extern
  • 183. www.cyberlabzone.com 1. Problem Definition Write a function “sum”that keeps a running total of the sum of every value passed to “sum”. To test this function, modify the previous program of slide 15 -3 that compute the average of values in a file. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = integers from file “input.dat” Output=real number representing the arithmetic average (sum of values)/(count of number of values) 3. Develop Algorithm (processing steps to solve problem) Example-static variable
  • 184. www.cyberlabzone.com Flowchart for main while EOF != scanf value total = sum(value); ++count; TrueFalse count = 0; printf total/(double) count Example-static variable
  • 185. www.cyberlabzone.com /* C Program to compute the average of a list of numbers. */ #include <stdio.h> int sum(int); /* function protoype */ void main(void) { int value,total,count = 0; while (EOF != scanf("%i", &value)) { /* read value */ total = sum(value); ++count; } /* end of while loop */ printf(”Average of the %i numbers = %f n“,count,total/(double)count); } int sum(int val){ /* function header */ static int total_val = 0; /* static variable, */ total_val += val; return total_val; } Example-static variable
  • 186. www.cyberlabzone.com Pointer variables are variables that store memory addresses. Pointers variables are useful in passing storage addresses in function calls (call-by-reference) and for applications involving dynamic data structures (e.g., linked lists) Example: int *intPtr; float *floatPtr; declares intPtr to be a pointer variable to an object of type integer. and floatPtr to be a pointer variable to an object of type float. Pointers
  • 187. www.cyberlabzone.com We can write the pointer variable declaration as int* intPtr; or as int * intPtr; Note that when we declare more than two pointer variables in one line each pointer name requires an asterisk: int *ptr1, *ptr2; otherwise we are just declaring a regular variable , not a pointer variable. Pointer Declaration-syntax
  • 188. www.cyberlabzone.com There are two C operators that are necessary when using pointer variables. & - the address operator returns the address of a variable x 1000 3 ptrX 1000 ptrX holds the address of x. We say ptrX “points” to x. We will apply the & operator only to variables, e.g. &77 or &(x+1) are not valid. The declaration of ptrX initializes the variable ptrX = &x; Example: int x = 3; int * ptrX = &x; 1004 & Operator
  • 189. www.cyberlabzone.com Example: int x; int * pt; pt = &x; /* another way to assign an address to a pointer variable */ Suppose the address of the variable x is 9640 Then, the effect of pt = &x; will be: x pt Address 9640 9640 & Operator
  • 190. www.cyberlabzone.com int x; int * pt; pt = &x; To assign the value “3” to the variable x in C: x = 3; We can use the “ * ” operator to indirectly reference x. We can assign “3” to x by: *pt = 3; Here we use the fact that “pt” points to integer values. x pt Address 9640 96403 * - means "a pointer to" and is called an indirection operator or dereferencing operator, since a pointer "indirectly" references a value in a storage location. Example: *Operator
  • 191. www.cyberlabzone.com double *ptr; ptr = NULL; Assigning a NULL value (zero) to a pointer A null pointer points to nothing. We often depict it as ptr /*called a null pointer*/ Null Pointer
  • 192. www.cyberlabzone.com 1. Problem Definition Write a function “swap” that has two input integer arguments. This function should swap the values of the variables. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = two integers Output= no value is returned to the calling function, but the values of the called variables should be swapped. 3. Develop Algorithm Pass the addresses of the variables and not their values. In the swap function the parameters that hold the addresses are pointers. Use the indirection operator to swap the values. Example-call-by-Reference
  • 193. www.cyberlabzone.com /* C Function to swap values. */ #include <stdio.h> void swap(int * , int *); void main(void){ /* function header */ int x = 1; int y = 2; swap(&x,&y); /* pass the addresses of x and y */ printf(“x = %d , y = %d n”,x,y); /* prints x = 2 , y = 1 */ } void swap(int *ptrX , int *ptrY){ /* pointer variables */ int temp = *ptrX; *ptrX = *ptrY ; *ptrY = temp; return; } Example-good Swap
  • 194. www.cyberlabzone.com x 1000 Main Memory before call to swap 1 y 2 Main Memory while executing swap, after temp = *ptrX; but before *ptrX = *ptrY ; 10001 ptrX 1000 3000 2 x y 1004 1004 3008 30041004ptrY temp 1 Example-good Swap
  • 195. www.cyberlabzone.com x y Main Memory while executing swap, after *ptrX = *ptrY ; but before *ptrY = temp; 10002 ptrX 1000 3000 2 1004 3008 30041004ptrY temp 1 Example-good Swap
  • 196. www.cyberlabzone.com x y Main Memory while executing swap, after *ptrY = temp; but before return; 10002 ptrX 1000 3000 1 1004 3008 30041004ptrY temp 1 Example-good Swap
  • 197. www.cyberlabzone.com The array name in C is assigned the address of the first element of the array. The following code will assign the address of xArray[0] to xArrayPtr : float xArray[50]; float * xArrayPtr; xArrayPtr = xArray; The assignment statement above is equivalent to: xArrayPtr = &xArray[0]; Array Names are Constant Pointers
  • 198. www.cyberlabzone.com A string literal (e.g. “A – your course graden”) is actually represented in C by a pointer to an address in memory that holds the first byte of the array of characters. Therefore the following declaration of the pointer variable “string” is valid: char * string = “A – your course graden”; and to print the value of “string” , use the “%s” conversion specifier, printf(“%s”,string); Although a pointer can be used as an array name, we cannot modify the values of “string” by using the square brackets of array notation. string[0] = ‘B’; /* error !!! */ The error is due to the fact that the literal “A – your course graden” is stored in a location in memory that cannot be accessed by pointers. String Literal is pointer to an array
  • 199. www.cyberlabzone.com One use of char * pointers is ragged arrays. In slide 15-24 we used the following code fragment in the “Morse Code” example to declare and initialize the array “morse” as : typedef char string[5]; string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..","--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." }; An alternative would be the use of a ragged “morse” array declared as: typedef char * string; string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..","--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." }; String Literal is Pointer to an Array
  • 200. www.cyberlabzone.com The later declaration of the array “morse” is called ragged since each element of the array , morse[0], morse[1], … takes up exactly the number of bytes necessary in memory to hold the initialized strings whereas in the previous declaration of “morse” each element of the array takes exactly five character values in memory no matter what length of the initializing string. As discussed on slide 15, we cannot change the values of the ragged “morse” array. But in the “Morse Code” problem we know that the morse strings should never be changed. Ragged Arrays
  • 201. www.cyberlabzone.com To sort means to put in place or rank according to kind, class or nature. For example, consider a herd of cows. We can sort the cows by weight, age, amount of milk produced, etc. . The sort can be in ascending or descending order. Note that we could not include a lizard in among the sort if we were sorting with respect to amount of milk produced. That is, the items we want to sort must have the same nature. In C we will use arrays to do our sorting. Since the data-type(kind, class or nature) for each element of the array must be the same we are able to compare any two elements in the array (no lizards in the array of milk producing cows). Why sort? Sorting
  • 202. www.cyberlabzone.com One method of sorting is called “selection sort”. The algorithm: find the smallest element in the list and swap the first item in the list with the smallest value. For example, suppose you are given the values(below): 5 3 7 2 4 ( 2 is the smallest value ) step 1 2 3 7 5 4 ( swap 2 with 5, now 3 is the smallest element) step 2 2 3 7 5 4 ( 3 is in place don’t swap, now 4 is the smallest element) step 3 2 3 4 5 7 ( swap 4 with 7, now 5 is the smallest element) step 4 2 3 4 5 7 ( 5 is in place don’t swap, 7 is in place )
  • 203. www.cyberlabzone.com Another method of sorting is called “insertion sort”. You use insertion sort when you sort a hand of cards. For example, suppose you are given the five cards (below): 5 3 7 2 4 (cards in Right hand) empty (cards in Left hand) step 1 3 7 2 4 (Right hand) 5 (Left hand) step 2 7 2 4 ( R ) 3 5 ( L ) step 3 2 4 ( R ) 3 5 7 ( L ) step 4 4 ( R) ) 2 3 5 7 ( L ) step 5 empty ( R ) 2 3 4 5 7 ( L ) ( the cards are now sorted )
  • 204. www.cyberlabzone.com 1. Problem Definition Write a program that sorts the values in an array in ascending order. Use the built-in function ‘qsort’ to do the work of sorting. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = Array of integers. Output= Sorted array of integers (ascending order) is printed. Qsort-Sorting an array
  • 205. www.cyberlabzone.com #include <stdio.h> #include <stdlib.h> int compare(int *ptr1, int *ptr2) { if ( *ptr1 > *ptr2) return 1; else if ( *ptr1 < *ptr2) return -1; else return 0; } void main(void) { int numbers[100]; int k,i=0; printf(“Enter an array of no more than 100 integers.n”); while (EOF != scanf(“%d”,&numbers[i])) ++i; qsort(numbers, i, sizeof(numbers[0]), compare); for (k=0; k<i; k++) printf("%d ", numbers[k]); printf(“n”); }
  • 206. www.cyberlabzone.com Execution: dclsn67>./a.out Enter an array of no more than 100 integers. 3 4 2 1 5 (hit Enter and then Control-d to signal EOF) 1 2 3 4 5 (this is the output the program produces) dclsn67> Qsort-Sorting an array
  • 207. www.cyberlabzone.com arrayname - is the name of an existing array. This array can have any data-type. It can even be an array of pointers. We will refer to the array’s type as datatype . elts is the number of elements of array. qsort(arrayname,elts,size_of_elts,compare_function) The qsort function is a built-in C function that sorts values in an array. The algorithm behind qsort is called “Quick Sort” . In CS101 we are interested only in how to call this function. The general format of the qsort function is: Sorting Example-qsort
  • 208. www.cyberlabzone.com size_of_elts is the size in bytes of each element in the array. Use the built-in operator sizeof that returns an integer value representing the number of bytes a variable or data-type takes up in RAM. Example: sizeof(integer) returns the value 4 on the Lab machines. sizeof(numbers[0]) returns the number of bytes the variable numbers[0] takes up in RAM, which is 4 since numbers is an integer array. compare_function is the name of the user defined function that actually does the comparison. qsort(arrayname,elts,size_of_elts,compare_function) Sorting Example-qsort
  • 209. www.cyberlabzone.com The general format of the header for the user defined compare function is: int compare_function( datatype * ptr1,datatype * ptr2) qsort will call the compare_function and pass two pointers ptr1 and ptr2 . Both ptr1 and ptr2 “point” to values in the array arrayname (see previous slide). The user must code the function compare_function so that it returns an integer value back to qsort (the function that called compare_function) . qsort will use this integer to determine whether or not to swap the values in the array. To sort in ascending order the return value is: 0 if the elements *ptr1 and *ptr2 of the array are equal positive if *ptr1 > *ptr2 (i.e. swap the array values) negative if *ptr1 < *ptr2 (i.e. don’t swap the array values) Sorting Example- compare_function
  • 210. www.cyberlabzone.com Writing the code for compare_function depends on the data-type datatype and whether the data is sorted in ascending order, descending order, ... or by some other rule. Therefore it’s not possible to write one version of compare_function that does all. Sorting Example- compare_function
  • 211. www.cyberlabzone.com The datatype in the sorting example is int . Therefore the header for the compare_function has the form: int compare( int * ptr1,int * ptr2) where ptr1 and ptr2 are pointers to values in the array numbers . As an example of how qsort works with compare see the pictures of memory in the following slides. Sorting Example
  • 212. www.cyberlabzone.com ptr1 ptr2 numbers[0] numbers[1] numbers[4] 3 4 Address 2000 2004 … 20042000 2 1 5 . . . Suppose qsort called the compare function and *ptr1 is “3” and *ptr2 is “4”. The picture above shows this situation. In this example, we want to tell qsort to sort 3 before 4(don’t swap the values). To do this, we use *ptr1 and *ptr2 . Since *ptr1 < *ptr2 ( 3 < 4) we return a -1 value to qsort. That’s why we have the code(slide 20): else if ( *ptr1 < *ptr2) { return -1; Sorting Example
  • 213. www.cyberlabzone.com ptr1 ptr2 numbers[1] numbers[2] numbers[4] 3 4 Address 2000 2004 2008… 20082004 2 1 5 . . . Now suppose qsort called the compare function and *ptr1 is “4” and *ptr2 is “2”. The picture above shows this situation. In this example, we want to tell qsort to sort 2 before 4( swap the values). To do this, we use *ptr1 and *ptr2 . Since *ptr1 > *ptr2 ( 4 > 2) we return +1 value to qsort. That’s why we have the code(slide 20): if ( *ptr1 > *ptr2) { return 1; } Sorting Example
  • 214. www.cyberlabzone.com The previous code works correctly but will generate a warning message. We can avoid the error messages if we obey the rules that qsort expects the compare_function to observe. The code on the next slide will sort the numbers as before but gcc will not display any warning messages. In the compare function (on the next slide), note the use of the void pointer data-type and the use of the cast operators on the pointer variables. const int x = 1; x = 2; /* illegal */ Compiler Warning Messages
  • 215. www.cyberlabzone.com #include <stdio.h> #include <stdlib.h> int compare(const void *ptr1, const void *ptr2) { if ( *(int *)ptr1 > *(int *)ptr2) return 1; else if ( *(int *)ptr1 < *(int *)ptr2) return -1; else return 0; } void main(void) { int numbers[100]; int k,i=0; printf(“Enter an array of no more than 100 integers.n”); while (EOF != scanf(“%d”,&numbers[i])) ++i; qsort(numbers, i, sizeof(numbers[0]), compare); for (k=0; k<i; k++) printf("%d ", numbers[k]); printf(“n”); }
  • 216. www.cyberlabzone.com #include <stdio.h> void main(void){ int z = 3; float w = 4.0; void * ptr; ptr = &z; /* add one to z */ *(int *)ptr = *(int *)ptr + 1; /* cast ptr */ ptr = &w; /* add 1.0 to w */ *(float *)ptr = *(float *)ptr + 1.0; /* cast ptr */ printf("z = %i n",z); /* prints 4 */ printf("w = %f n",w); /* prints 5.000 */ }
  • 217. www.cyberlabzone.com 1. Problem Definition Write a program that creates a new data type named “vector”. A “vector” represents a 2 dimensional vector v =<x,y> in the plane. The values of v are of type double. Along with this new data-type, create functions add, sub, and dot which will add , subtract and take the vector dot product of two vectors. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) We first define a new data type “vector”. Then in main we will declare v1,v2,v3 of data type “vector”. We will assign values to these vectors and then perform addition, subtraction and the dot product. Input = None Output= The values of v1,v2 will be printed along with the results from add, sub and dot. Example-Defining a 2D “vector data type”
  • 218. www.cyberlabzone.com #include <stdio.h> #include <stdlib.h> typedef struct { /* user defined data-type called vector */ double x; /* this is a definition*/ /* no variables are declared */ double y; /* location is outside any block */ } vector; vector add(vector vec1, vector vec2) ; /* prototype */ vector sub(vector vec1, vector vec2) ; /* prototype */ double dot(vector vec1, vector vec2) ; /* prototype */ /* see explanation of the above in subsequent slides */ void main(void){ vector v1,v2,v3 ={1.0,2.0}; /* three variables of type vector*/ /* v3 initialized to {1.0,2.0} */ v1.x = 2.5; /* use the . to access individual fields */ v1.y = -1.5; v2 = v3; /* can assign all the values with one statement */ /* continued on next slide */
  • 219. www.cyberlabzone.com printf(“v1 = [%f,%f]n”,v1.x,v1.y); printf(“v2 = [%f,%f]n”,v2.x,v2.y); v3 = add(v1,v2); printf(“add(v1,v2) = [%f,%f]n”,v3.x,v3.y); v3 = sub(v1,v2); printf(“sub(v1,v2) = [%f,%f]n”,v3.x,v3.y); printf(“dot(v1,v2) = %fn”,dot(v1,v2)); } /* end of main */ vector add(vector vec1, vector vec2){ vector v4 = {vec1.x + vec2.x, vec1.y + vec2.y}; return v4; } /* end of add */ vector sub(vector vec1, vector vec2){ vector v4 = {vec1.x - vec2.x, vec1.y - vec2.y}; return v4; } /* end of sub */ double dot(vector vec1, vector vec2){ return (vec1.x * vec2.x) + (vec1.y * vec2.y); } /* end of dot */
  • 220. www.cyberlabzone.com > a.out v1 = [2.500000,-1.500000] v2 = [1.000000,2.000000] add(v1,v2) = [3.500000,0.500000] sub(v1,v2) = [1.500000,-3.500000] dot(v1,v2) = -0.500000 Example-Execution