0% found this document useful (0 votes)
0 views

Lecture 2 - C-Fundamentals

The document provides an overview of C programming fundamentals, covering topics such as program structure, compilation process, data types, variables, functions, and input/output operations. It explains the compilation stages including preprocessing, compiling, and linking, and introduces the use of an Integrated Development Environment (IDE). Additionally, it discusses the syntax for defining constants, operators, and basic console input/output functions like printf and scanf.

Uploaded by

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

Lecture 2 - C-Fundamentals

The document provides an overview of C programming fundamentals, covering topics such as program structure, compilation process, data types, variables, functions, and input/output operations. It explains the compilation stages including preprocessing, compiling, and linking, and introduces the use of an Integrated Development Environment (IDE). Additionally, it discusses the syntax for defining constants, operators, and basic console input/output functions like printf and scanf.

Uploaded by

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

C-Fundamentals

Programming for Engineers


UFMFGT-15-1
Lesson
Plan
► Intro to C Programming
► C-Program Structure
► Compiling and Linking
► Directives, Statements and Functions
► Data Types
► Constants and Variables
► Operators
► Introduction to Console I/O
► Comments
C Program
Structure

Output – function returns Header file


a value

C #include <stdio.h>
compiler
int main(void){
//declare variables

statement 1; body
statement 2;

return 0;
}
return keyword
need to be used
when an output is
specified
Compilation
Process
Editing Compilation Execution

Pre-processor

Compiler

Assembler

myFile.c myFile.out
Linker and/or
myFile.exe

Object files and


libraries
Compiling and
Linking
• Before a program can be executed, three steps are usually
necessary:
– Preprocessing. The preprocessor obeys commands that
begin with # (known as directives); the preprocessor is
usually integrated with the compiler.
– Compiling. A compiler then translates the source code
program into machine instructions (object code).
– Linking. A linker combines the object code produced by the
compiler with any additional code needed to yield a
complete executable program.
• An integrated development environment (IDE) is a software
package that makes it possible to edit, compile, link, execute,
and debug a program without leaving the environment (e.g.
Visual Studio, Matlab, C Lion etc.)
C Lion
IDE
Use AppsAnywhere
https://appsanywhere.uwe.ac.uk/

Or install at home
https://
www.jetbrains.com/help/clion/quick-tutorial-on
-configuring-clion-on-windows.html
General form of a C-
Program
Pre-processor directives
#include <stdio.h> #include <stdio.h>

int main(void) function

int main(void){
{ statement
return 0;
}
1;
statement
Statements
2; statement 1;
statement 2;
return 0;
}
Preprocessor
directives
• Begin with a # symbol, and are NOT terminated by a semicolon.
• Traditionally, preprocessor statements are listed at the beginning of
the source file.
• Preprocessor statements are handled by the compiler (or
preprocessor) before the program is actually compiled. All #
statements are processed first, and the symbols which occur in the C
program are replaced by their value.
#include <stdlib.h>

#define N 30
#define TRUE 1

Once this substitution has taken place by the preprocessor, the


program is then compiled.
Header
files
• Header files contain definitions and declarations of constants,
variables and functions used in C-programs. Have extension .h
and are placed at the beginning of source files (extension .c).
• pre-processor #include statement enables header files to be
included in source files.
• Standard header files are provided with each compiler, and cover
a range of areas: string handling, mathematics, data conversion,
printing and reading of variables, etc.
#include <stdio.h>
• The use of angle brackets <> informs the compiler to search the
compiler’s include directories for the specified file. The use of the
double quotes "" around the filename informs the compiler to
start the search in the current directory for the specified file.
Function
s • A function is a series of statements that have
been grouped together and given a name.
• Each function is essentially a small program
to perform a particular task, with its own
declarations and statements.
• Library functions are provided as part of the
C implementation.
• A function that computes a value uses a
return statement to specify what value
it “returns”:
return x;
The main
Function
• The main function is mandatory.
• main is special: it gets called
automatically
when the program is executed.
• main returns a status code; the value
0 indicates normal program
termination.
• If there’s no return statement at the
end of the main function, many
compilers will produce a warning
Statement
s
• A statement is a command to be executed
when the program runs.
• Asking a function to perform its assigned
task is known as calling the function.
• C requires that each statement end with a
semicolon.
– With one exception: the compound statement
(also called a block).
Statements – HelloWorld.c
example
HelloWorld.c
#include <stdio.h>

int main(void)

{ printf(“Hello World.\

n”);

return 0;
}
• Only two kinds of statements
used:
1. A
function call
2. A return statement
• Function printf is used to
Variable
s•
A variable is named reference to a value stored in the
system’s memory.
• Each variable has to be declared before use.
• Each variable occupies one or more bytes in memory
based on their type.
• e.g.
Variable Memory
Allocated Definition

char A; 1 byte = 8 bits


int B; usually 4 bytes – depends on system
int C[10]; 10 x 4 bytes
Variables – Memory
Storage
int val =10, num=20, count=30; char Ch = “A”;
int val =10;

0x120 0x120
4 4
0x120 0x120
0 0

30 0x100 30
0x100 count
8 8
20 20 val
num
0x100 0x100
10 A
4 val 4 Ch

0x100 0x100
0 0
Data
Types
• ANSI C has five “atomic” data
types, and several modifications to
the atomic types
Modifiers
Basic Data Types
signed
int
unsigned
char
long
float
short
double
static
void
volatile
Data
Types
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

-32,768 to 32,767 or -2,147,483,648 to


int 2 or 4 bytes
2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 4 bytes -2,147,483,648 to 2,147,483,647

unsigned long 4 bytes 0 to 4,294,967,295


Variable Types (Global vs
Local)
local variables
#include <stdio.h>
int Foo(int var); int Foo(int var){
global variable int try;
int val=10;
try = var + val;
int main()
{ int num = return try;
4; }
...
num =
Foo(num);
...
return 0;
}
Declaration
s • Variables must be declared before they
are used.
• Variables can be declared one at a
time:
int height;
float profit;

• Alternatively, several can be declared at


the same time:
int height, length, width, volume;
float profit, loss;
Assignme
nt
• A variable can be given a value by means of
assignment:
height = 8;
The number 8 is said to be a constant.
• A variable of type float can be defined as
follows:
salary = 1025.50f;
• A float variable usually contains a decimal
point. An f is included to indicate the type to
the compiler.
• Note: variables need to be declared before they
are assigned values.
Assignme
nt
•Variables with assigned values can be used to
compute values for other variables
• E.g Consider Area = length* width;
length = 10.0f;
width =
5.5f;
area =
length * width
;
/* area is
assigned the
value 55.0f */
• The right side of an assignment can be a
Initialisatio
n
• Variables that are not assigned a value when
declared are called unintialised.
• Some variables are automatically set to zero
when a program begins to execute, but
most are not.
• Attempting to access the value of an
uninitialised variable may yield an
unpredictable result.
• May even lead to program crash.
Variable declaration and
initialisation

• The initial value of a variable may


be included in its declaration:
int height = 8;
int height = 8, length = 12, width = 10;

• Initialisation depends on data


type:
int numSwitches = 10;
float cost = 20.0f;
int switch_value = 0x20;
int trigger_value = 0b11;
“static”
variables
static int myglobal;
• A static global variable or …..
a function is "seen" only int main(void){
in the file it's declared //
in. statements;
• A static variable return 0;
inside a function keeps }
its value between
invocations.
• e.g int Foo(int b)
• c = Foo(3); //returns { static int
a=5; a = a +
8 b; return( a);
• d = Foo(3); //returns }
11
Constant
s • A constant is an identifier that is similar to a variable
except that it holds the same value during its entire
existence
#define symbolic-name value_of_constant

#define N 3000
#define FALSE 0
#define PI 3.14159
#define FIGURE
"triangle"
• Pre-processor replaces the symbolic name with
defined value within the whole program
Defining Constants in C – an
Example
/* add.c
A simple C program to print the sum of integers from 1 to MAX
*/

#include <stdio.h>
#define MAX 10

int main()
{
int i; /* General purpose counter*/
int sum = 0; /* Cumulative sum */

for ( i = 1; i <= MAX; i++ ) {


sum = sum + i;
} /* end for */
printf(“%d\n", sum);

return 0;
}

Note: we could easily change this program to add numbers from 1 to 100
by redefining MAX near the top of the program as #define MAX 100
Operators in
C
• C emphasizes on expression statements.
• Expressions are built from variables,
constants, and operators.
• Some common operators used in C:
– assignment operators
– arithmetic operators
– relational operators
– logical operators
– increment and decrement operators
Arithmetic
Operators
• C provides five binary arithmetic operators:
+ addition
- subtraction
* multiplication
/ division
% remainder
• Arithmetic operators are either binary
(uses two operands) or unary (only one
operand)
Unary Arithmetic Operators
• There are also two unary arithmetic
operators:
+ unary plus
- unary minus
• Examples
i = +1;
j = -i;
• The unary + operator does nothing.
It’s used primarily to emphasize that a
numeric constant is positive.
Behaviour of / and %
Operators
– The operator / “truncates” the
result when both operands are
integers.
• E.g. 1 / 2 is 0 (not 0.5).
– The % operator requires integer
operands; if either operand is not an
integer, the program won’t compile.
– Using zero as the right operand of
either
/ or % causes undefined behavior.
Operator precedence
• The arithmetic operators have the
following relative precedence:
Highest: + - (unary)
* / %
Lowest: + - (binary)

• If the parentheses are omitted, C uses operator


precedence
rules to determine the meaning of the expression.
• Examples: If unsure, use brackets!
i + j * k is i + (j *
equivalent to k) (-i)
-i * -j is * (-j)
equivalent to (+i) + (j
+i + j / k is / k)
equivalent to
Increment and Decrement
Operators
• In the simplest form, used to add or
subtract 1 to/from an integer variable.
e.g. i++; is equivalent to i = i +
1; i--; is equivalent to i = i -
• Note 1; i++ and ++i are
e.g.different
j = i++; /* Copy i into j then increment i */
j = + /* Increment i then copy into j
+i; */
Introduction to Console I/O -
printf
• A function provided in <stdio.h> to write character strings
and variable values to the standard output stream (stdout) -
usually on a console screen.
• e.g.
printf(“Hello Universe\n");

• In this case, the printf function displays a string literal


— characters enclosed in double quotation marks—it
doesn’t show the quotation marks.
• printf doesn’t automatically advance to the next output
line when it finishes printing. To make printf advance one
line, include \n (the new-line character) in the string to be
printed.
Printing the Value of a
Variable
• printf can be used to display the
current value of a variable.
• e.g. To print the message
Resistance: R ohms
where R is the current value of an int
variable called resistance we can
make the following call of printf:
printf(“Resistance: %d ohms\n", resistance);
• %d is a placeholder indicating where
the value of height is to be filled in.
Printing the Value of a
Variable
• %d works only for int variables; for a float variable, use %f
instead.
• By default, %f displays a number with six digits after the
decimal point.
• To force %f to display p digits after the decimal point, put .p
between % and f.
• e.g. to print the line
Resistance: 2150.48 ohms
use the following call of
printf:
printf(“Resistance: %.2f
ohms\n", resistance);
• The values of several
variables can be printed by
a single call of
printf e.g.
Introduction to Console I/O-
scanf
• A function provided in <stdio.h> for reading in
variable values from the standard input stream
(stdin) usually the keyboard.
• scanf requires a format string to specify the
appearance of the input data.
• Example of using scanf to read an int value:
scanf("%d", &i); /* reads an integer; stores
into i */
• The & symbol is usually (but not always) required
when using scanf.
• Reading a float value requires a slightly different call
of scanf: scanf("%f", &x);
• "%f" tells scanf to look for an input value in float
format (the number may contain a decimal point,
but doesn’t have to).
Example Simple
Program
/* Converts a Fahrenheit temperature to Celsius*/
#include <stdio.h>
int main(void)
{
float fahrenheit, celsius;

printf("Enter Fahrenheit
temperature: ");
scanf("%f", &fahrenheit);
celsius = (fahrenheit – 32.0) *
(5.0/9.0); printf("Celsius
equivalent: %.1f\n", celsius);

return 0;
}
Comment
s
• Comments: /∗ this is a simple comment ∗/
• Can span multiple lines (as in programme
banners)
/ ∗ This
comment spans
multiple lines ∗ /
• Completely
ignored by
compiler
• Can appear
almost
anywhere
Comment
s
• Warning: Forgetting to terminate a
comment may cause the compiler to
ignore part of your program:
printf("My "); /* forgot to close this comment...
printf("cat ");
printf("has "); /* so it ends here */
printf("fleas");
Summar
yIn this lesson you have learnt:
1. How to implement a simple C-
Program
2. What are derivatives,
functions and statements
3. How to define constants and
variables
4. A brief introduction to I/O
console
5. Commenting your program

You might also like