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

Lect02a Overview of C Programming-1

Lecture #2 provides an overview of C programming, covering topics such as the structure of a simple C program, the von Neumann architecture, variables, data types, and input/output operations. It emphasizes the importance of proper initialization of variables and the use of preprocessor directives. The lecture also includes examples of C code and comparisons with Python syntax.

Uploaded by

maleliufb
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lect02a Overview of C Programming-1

Lecture #2 provides an overview of C programming, covering topics such as the structure of a simple C program, the von Neumann architecture, variables, data types, and input/output operations. It emphasizes the importance of proper initialization of variables and the use of preprocessor directives. The lecture also includes examples of C code and comparisons with Python syntax.

Uploaded by

maleliufb
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

http://www.comp.nus.edu.

sg/~cs2100/

Lecture #2a

Overview of C Programming
Questions?
IMPORTANT: DO NOT SCAN THE QR CODE IN THE
VIDEO RECORDINGS. THEY NO LONGER WORK

Ask at
https://sets.netlify.app/module/676ca3a07d7f5ffc1741dc65

OR

Scan and ask your questions here!


(May be obscured in some slides)
Lecture #2: Overview of C Programming 3

Lecture #2: Overview of C Programming (1/2)

1. A Simple C Program
2. von Neumann Architecture
3. Variables
4. Data Types
5. Program Structure
5.1 Preprocessor Directives
5.2 Input/Output
5.3 Compute
Arithmetic operators
Assignment statements
Typecast operator
Lecture #2: Overview of C Programming 4

Lecture #2: Overview of C Programming (2/2)

6. Selection Statements
6.1 Condition and Relational Operators
6.2 Truth Values
6.3 Logical Operators
6.4 Evaluation of Boolean Expressions
6.5 Short-Circuit Evaluation
7. Repetition Statements
7.1 Using ‘break’ in a loop
7.2 Using ‘continue’ in a loop
Lecture #2: Overview of C Programming 5

Introduction
 C: A general-purpose computer programming
language developed in 1972 by Dennis
Ritchie (1941 – 2011) at Bell Telephone Lab
for use with the UNIX operation System
Lecture #2: Overview of C Programming 6

Quick Review: Edit, Compile, Execute


Edit Compile

Source code Execute


Edit produces
first.c
eg: vim first.c

Executable code
Compile produces
a.out Cannot
eg: gcc first.c
compile?

Program output Incorrect


Execute produces result?
eg: a.out The value of c is 3.
Lecture #2: Overview of C Programming 7

1. A Simple C Program (1/3)


General form
preprocessor directives
main function header
{
declaration of variables
executable statements
} “Executable statements”
usually consists of 3 parts:
 Input data
 Computation
 Output results
Lecture #2: Overview of C Programming 8

1. A Simple C Program (2/3)


MileToKm.py
MileToKm.c
// Converts distance in miles to kilometres.
#include <stdio.h> /* printf, scanf definitions */
KMS_PER_MILE
#define KMS_PER_MILE
= 1.609 1.609
# conversion
/* conversion
constant
constant */

def main(void)
int main(): {
float miles, // input – distance in miles
kms; // output – distance in kilometres

#/*Get
Getthe
thedistance
distanceininmiles
miles */
miles
printf("Enter
= float(input("Enter
distance in miles:
distance
");in miles: "))
scanf("%f", &miles);

#//Convert
Convertthe
thedistance
distancetotokmkilometres
kms
kms == KMS_PER_MILE
KMS_PER_MILE ** miles
miles;

#//Display
Displaythe
thedistance
distanceininkmkilometres
print("That
printf("Thatequals",
equals %9.2f
kms, km.");
km.\n", kms);

return
return 00; Sample run
} $ gcc MileToKm.c
if name == "__main__": $ a.out
main() Enter distance in miles: 10.5
That equals 16.89 km.
(Note: All C programs in the lectures are available on LumiNUS as well
as the CS2100 website. Python versions are also available.)
Lecture #2: Overview of C Programming 9

1. A Simple C Program (3/3)


// Converts distance in miles to kilometres.
standard header file
preprocessor #include <stdio.h> /* printf, scanf definitions */
directives #define KMS_PER_MILE 1.609 /* conversion constant */
constant
int main(void) {
reserved
float miles, // input – distance in miles
words kms; // output – distance in kilometres

/* Get the distance in miles */


variables printf("Enter distance in miles: "); comments
scanf("%f", &miles); (Only /* … */
functions is ANSI C)
// Convert the distance to kilometres
kms = KMS_PER_MILE * miles;
special // Display the distance in kilometres
symbols printf("That equals %9.2f km.\n", kms);

return 0;
} In C, semi-colon (;) terminates a statement.
Curly bracket { } indicates a block.
In Python: block is by indentation
Lecture #2: Overview of C Programming 10

2. von Neumann Architecture (1/2)


What happens in the computer memory?
memory memory memory

Executable code of Executable code of Executable code of


MileToKm.c MileToKm.c MileToKm.c

miles miles miles


? 10.5 10.5

kms kms kms


? ? 16.89

At the beginning
After user enters: 10.5 to After this line is executed:
Do not assume that
uninitialised variables scanf("%f", &miles); kms = KMS_PER_MILE * miles;
contain zero! (Very
common mistake.)
Lecture #2: Overview of C Programming 11

2. von Neumann Architecture (2/2)


 John von Neumann (1903 – 1957)
 von Neumann architecture*
describes a computer consisting
of:
 Central Processing Unit (CPU)
 Registers
 A control unit containing an instruction
register and program counter
 An arithmetic/logic unit (ALU)
 Memory
 Stores both program and data in
random-access memory (RAM)
 I/O devices
(* Also called Princeton architecture, or stored-program architecture)
Lecture #2: Overview of C Programming 12

3. Variables float miles, kms ;

 Data used in a program are stored in variables


 Every variable is identified by a name (identifier), has a
data type, and contains a value which could be modified
 (Each variable actually has an address too, but for the
moment we will skip this until we discuss pointers.)
 A variable is declared with a data type Python
 int count; // variable ‘count’ of type ‘int’ Declaration via
assignment in
 Variables may be initialized during declaration: function/global
 int count = 3; // ‘count’ is initialized to 3 count = 3

 Without initialization, the variable contains an unknown


value (Cannot assume that it is zero!)
Lecture #2: Overview of C Programming 13

3. Variables: Mistakes in Initialization


InitVariable.c
 No initialization int main(void) {
int count; Python
-Wall option turns count = count + 12; Cannot declare
on all warnings return 0; without
} initialization

$ gcc –Wall InitVariable.c


InitVariable.c: In function 'main':
InitVariable.c:3:8: warning: 'count' is used
uninitialized in this function
count = count + 12;
^

 Redundant initialization
int count = 0; int count = 0;
count = 123; scanf("%d", &count);
Lecture #2: Overview of C Programming 14

4. Data Types (1/3) float miles, kms;

 Every variable must be declared with a data type


 To determine the type of data the variable may hold
 Basic data types in C:
Python JS
 int: For integers int number
 4 bytes (in sunfire); -2,147,483,648 (-231) through
+2,147,483,647 (231 – 1) Python JS
 float or double: For real numbers float number
 4 bytes for float and 8 bytes for double (in sunfire)
 Eg: 12.34, 0.0056, 213.0
 May use scientific notation; eg: 1.5e-2 and 15.0E-3 both refer
to 0.015; 12e+4 and 1.2E+5 both refer to 120000.0
 char: For characters
Python JS
 Enclosed in a pair of single quotes
str string
 Eg: 'A', 'z', '2', '*', ' ', '\n’
Lecture #2: Overview of C Programming 15

4. Data Types (2/3)


 A programming language can be strongly typed or
weakly typed
 Strongly typed: every variable to be declared with a data
type. (C: int count; char grade; )
 Weakly typed: the type depends on how the variable is used
(JavaScript: var count; var grade;)
 The above is just a simple explanation.
 Much subtleties and many views and even different definitions.
Other aspects include static/dynamic type checking, safe type
checking, type conversions, etc.
 Eg: Java, Pascal and C are strongly typed languages. But Java
/Pascal are more strongly typed than C, as C supports implicit
type conversions and allows pointer values to be explicitly cast.
 One fun video:
https://www.youtube.com/watch?v=bQdzwJWYZRU
Lecture #2: Overview of C Programming 16

4. Data Types (3/3)


DataTypes.c
// This program checks the memory size
// of each of the basic data types
#include <stdio.h>

int main(void) {
printf("Size of 'int' (in bytes): %d\n", sizeof(int));
printf("Size of 'float' (in bytes): %d\n", sizeof(float));
printf("Size of 'double' (in bytes): %d\n", sizeof(double));
printf("Size of 'char' (in bytes): %d\n", sizeof(char));

return 0; Python
} Use sys.getsizeof

$ gcc DataTypes.c –o DataTypes import sys


sys.getsizeof(1)
$ DataTypes
Size of 'int' (in bytes): 4 -o option
Size of 'float' (in bytes): 4 specifies name of
Size of 'double' (in bytes): 8 executable file
Size of 'char' (in bytes): 1 (default is ‘a.out’)
Lecture #2: Overview of C Programming 1 - 17

Programming Samples
• All sample programs are available at the Lecture Slides
section here:
https://www.comp.nus.edu.sg/~cs2100/2_resources/lecture
s.html
Lecture #2: Overview of C Programming 18

5. Program Structure
 A basic C program has 4 main parts:
 Preprocessor directives:
 eg: #include <stdio.h>, #include <math.h>, #define PI 3.142
 Input: through stdin (using scanf), or file input
 Compute: through arithmetic operations and assignment
statements
 Output: through stdout (using printf), or file output
Lecture #2: Overview of C Programming 19

Preprocessor
5.1 Preprocessor Directives (1/2) Input
Compute
Output
 The C preprocessor provides the following
 Inclusion of header files
 Macro expansions
 Conditional compilation
 We will focus on inclusion of header files and simple application
of macro expansions (defining constants)
 Inclusion of header files
 To use input/output functions such as scanf() and printf(), you
need to include <stdio.h>: #include <stdio.h>
 To use functions from certain libraries, you need to include the
respective header file, examples:
 To use mathematical functions, #include <math.h>
(In sunfire, need to compile with –lm option)
 To use string functions, #include <string.h>
Lecture #2: Overview of C Programming 20

Preprocessor
5.1 Preprocessor Directives (2/2) Input
Compute
Output
 Macro expansions
 One of the uses is to define a macro for a constant value
 Eg: #define PI 3.142 // use all CAP for macro

#define PI 3.142 Preprocessor replaces all instances


of PI with 3.142 before passing the
int main(void) { program to the compiler.
...
areaCircle = PI * radius * radius;
volCone = PI * radius * radius * height / 3.0;
} In Python, there is no parallel, but closest is simply
declare global variable
What the compiler sees:
PI = 3.142
int main(void) { areaCircle = PI * radius * radius
... volCone = PI * radius * height / 3.0
areaCircle = 3.142 * radius * radius;
volCone = 3.142 * radius * radius * height / 3.0;
}
Lecture #2: Overview of C Programming 21

Preprocessor

5.2 Input/Output (1/3) Input


Compute
Output
 Input/output statements:
age Address of variable
 scanf
input (( prompt
format string,
= Noneinput
) list ); ‘age’ varies each
20
 printf
print ((value
formatliststring
) ); time a program is
 printf ( format string, print list ); run.

One version: “age” refers to value in the variable age.


int age; “&age” refers to (address of) the memory
double cap; // cumulative average cell where the value of age is stored.
point
age = int(input("What
printf("What is your age?
is your
"); age?"))
scanf("%d", &age);
cap = float(input("What
printf("What is your CAP?
is");
your CAP?"))
scanf("%lf", &cap);
print("You are",
printf("You are %d
age,
years
"years
old,old,
and and
youryour
CAP CAP
is %f\n",
is", cap);
age, cap);
InputOutput.py
InputOutput.c
Another version:
int
user_input
age; = input("What are your age and CAP?") InputOutputV2.py
InputOutputV2.c
double
age, cap
cap;
= user_input.split("
// cumulative average
") point
printf("What
age, cap = int(age),
are yourfloat(cap)
age and CAP? ");
scanf("%d %lf", &age, &cap);
printf("You
print("You are",
are %d
age,
years
"years
old, old,
and your
and your
CAP is
CAP%f\n",
is", cap);
age, cap);
Lecture #2: Overview of C Programming 22

Preprocessor

5.2 Input/Output (2/3) Input


Compute
Output

 %d and %lf are examples of format specifiers; they are placeholders


for values to be displayed or read
Placeholder Variable Type Function Use Python
%c char printf / scanf All inputs are
%d int printf / scanf read as
string
%f float or double printf
%f float scanf
%lf double scanf
%e float or double printf (for scientific notation)
 Examples of format specifiers used in printf():
 %5d: to display an integer in a width of 5, right justified
 %8.3f: to display a real number (float or double) in a width of 8, with 3
decimal places, right justified
 Note: For scanf(), just use the format specifier without indicating
width, decimal places, etc.
Lecture #2: Overview of C Programming 23

Preprocessor

5.2 Input/Output (3/3) Input


Compute
Output

 \n is an example of escape sequence


 Escape sequences are used in printf() function for certain special
effects or to display certain characters properly
 These are the more commonly used escape sequences:

Escape Meaning Result


sequence
\n New line Subsequent output will appear on the next line
\t Horizontal tab Move to the next tab position on the current line
\" Double quote Display a double quote "
%% Percent Display a percent character %

Try out TestIO.c and compare with TestIO.py


Lecture #3: Data Representation and Number Systems 24

End of File

You might also like