[go: up one dir, main page]

0% found this document useful (0 votes)
21 views73 pages

C Language

The document provides an overview of the C programming language, its history, and its features, including its multi-purpose nature and portability across different systems. It outlines the process of writing and compiling a C program, along with examples of basic syntax, data types, and the importance of comments and variable naming. Additionally, it discusses the structure of C programs, including the main function and the use of standard libraries.

Uploaded by

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

C Language

The document provides an overview of the C programming language, its history, and its features, including its multi-purpose nature and portability across different systems. It outlines the process of writing and compiling a C program, along with examples of basic syntax, data types, and the importance of comments and variable naming. Additionally, it discusses the structure of C programs, including the main function and the use of standard libraries.

Uploaded by

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

Programming 1

Basics of C Language
Part II: C Programming and Problem Solving
C-Language

University of Oulu
Background
‒ Bell Labs, designed for UNIX-system programming
‒ Is based on BCPL and B languages
‒ Many UNIX-system functionalities have been implemented in C
‒ Multi-purpose programming language, standardized in 1990
‒ Portable, i.e., a program can be be compiled and executed in
different operating systems and in different machines
‒ Includes characteristics from both low level and high level
programming language

University of Oulu
‒ The core of C is small, complex
Background wholenessess are built with
libraries
With C, it is possible to write compact ‒ Use of directives & pre-compiler
and confusing code.
‒ Somewhat difficult language, easy
A good program should be easy to read to make serious errors
and understandable.
‒ Compact format, comments are
Keep it simple! preferred
‒ Weakly categorized, no run-time
verification (as in e.g., Java)
‒ Perhaps not the best
programming language for a
novice… on the other hand – a
very good one.

University of Oulu
Writing a program in C
1. A programmer creates program in the editor and stores it on disk. The file is a text file including the
source code, e.g., my_program.c
2. The programmer compiles the source code
gcc –std=c99 –Wall –lm –o my_program my_program.c

3. Preprocessor program processes the code.


4. Compiler creates object code (my_program.obj) and stores it on disk. The text file is converted to a
format that is understood by the machine.
5. Linker links the object code with the libraries (binary code), creates an executable file and stores it on
disk. We have a new file my_program.exe.
6. To run the program in Windows, e.g.,
my_program

7. Loader puts program in memory.


8. CPU takes each instruction and executes it, possibly storing new data values as it proceeds.

5 University of Oulu
Writing a program in C
C systems generally consist of a program-development environment,
the language and the C Standard Library

Editor
Loader
Preprocessor
CPU
Disk
Compiler

Linker
6 University of Oulu
Writing a program in C
#include <stdio.h> my_program.c
int main(void) {
printf(”Hello!\n”);
return(0);
}

Errors Errors Compiler

Object Code my_program.obj

library
Errors Linker
library library

Executable Code my_program.exe


7 University of Oulu
Writing a program in C – An Example
Printing a line of text to greet the user (hello.c)

8 University of Oulu
Writing a program in C – An Example
Requirements specification

‒ Problem: The distances on the map are shown in miles. The task is to
convert all mileages to kilometers.
‒ Analysis: The program will have mileage as numeric input and provide the
equivalent distance in kilometers as numeric output.
‒ Requirements for the data and the key formula
- Input: miles, distance in miles
- Output: kmeters, distance in kilometers
- Formula: One mile is 1.609 kilometers

9 University of Oulu
Writing a program in C – An Example
‒ The labels miles and kmeters are named memory elements which will
hold the input (miles) and output (kmeters) of the program.
‒ Design: The algorithm at general level
1. Provide the distance in miles
2. Convert the distance in miles to kilometers
3. Display the distance in kilometers
‒ The first and the third instructions are clear. Let’s redefine the second
instruction…
Distance in kilometers is the distance in miles * 1.609
10 University of Oulu
University of Oulu
Writing a program in C – An Example
‒ Compiling the program from the command line
gcc –std=99 –Wall –lm –o milesToKilometers milesToKilometers.c

‒ Executing the program from the command line


milesToKilometers

University of Oulu
Writing a program in C
Comments can be used to clarify the functionality or use of the program…
‒ Comments including several consequtive lines of code…
/* This would be a comment of several
consequtive lines of text…
until here */.
‒ One line comment…
// Any text aftre double slashes until the end of string is a comment
‒ Do not comment obvious issues but those that may e.g., be difficult to
understand (by you or others) or explain why some choices have been made.

13 University of Oulu
Writing a program in C
‒ Several lines of comments

‒ Single line comments

University of Oulu
Writing a program in C
‒ Pre-compiler directives, starting with # character, e.g.

‒ Information about the data elements we use in the


program, how those are named, what type of information
can be stored to them, i.e., definition of the variables.

University of Oulu
Writing a program in C
‒ Statements in C-language which are equivalent to the instructions
in the algorithm or directives

‒ Our example program consists of two parts:


- Directives to the pre-compiler (see previous slide) and
- Main function, which includes the variable definitions and executable instructions

University of Oulu
Writing a program in C

17 University of Oulu
Typical Features
C
of C-Language

University of Oulu
Features of C
preprocessor directives

start of main function {


definition of the variables
block
executable statements
}

19 University of Oulu
Features of C
‒ Every C-program will include one or more header files
(depending on the required library functions).
‒ C-preprocessor interprets the preprocessor directives
(starting with # character) which are executed before the
actual compilation, e.g.,
- #include defines the libraries used
- #define declares e.g., symbolic constants and macros
- Enables conditional compilation

University of Oulu
Features of C
C-language is rather compact, a few
functionalities only
- Usage of the standard libraries
- C-standard requires that specific standard libraries will be
delivered with the compiler
- All library headers have a file extension .h
(h= header)

University of Oulu
Features of C
For example
#include <stdio.h>
The directive tells the preprocessor to add the definitions (for e.g., printf &
scanf) from the file stdio.h to the source code before the actual compilation.

#define KM_MILES 1.609


The directive creates a symbolic constant KM_MILES and preprocessor
replaces all subsequent occurrences of the symbolic constant with the
numeric constant 1.609 before the program is compiled.

22 University of Oulu
Features of C
‒ All C programs contain one or more functions, one of which must be main.
‒ Every program in C begins executing at the function main
int main( void )
‒ Rest of the lines form the body of the program.
‒ A left brace { begins the body of a function. A corresponding right brace }
ends the body of a function. This pair of braces and the portion of the program
between the braces is called a block.
‒ A program will end to } character.
‒ Usage of indentation, white spaces and splitting lines is important
for clarity and readability!

23 University of Oulu
Features of C
The body of the program is composed of two parts
‒ Definitions
‒ Executable statements
‒ An example C-program

24 University of Oulu
Features of C
‒ The program has two executable statements

‒ The statement on line 5 prints the text “Welcome to learn C!” on display
(note, the quotation marks are not printed).

‒ The statement on line 6 returns the control back to the operating system, i.e.,
the execution of main function has ended (value 0 indicates the operating
system that the execution of the program ended normally, without any
errors).
25 University of Oulu
Features of C
‒ Reserved words = special meaning to the C compiler.
‒ Do not use these as identifiers such as variable names!
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
26 University of Oulu
Features of C
Standard identifiers
‒ E.g., scanf and printf – do not redefine.

User defined identifiers (variable names, to be defined before use)


‒ An identifier is a series of characters (letter, digits and underscore)
‒ An identifier must not begin with a digit!
‒ Avoid starting identifiers with the underscore character
‒ C is case sensitive, uppercase and lowercase letters are different
‒ The first letter of an identifier used as a variable should be a lowercase letter
‒ Multiple-word variables

27 University of Oulu
Features of C
User defined identifiers
‒ Naming of the memory locations and functions used in the program
Naming in short
‒ Meaningful variable names increase clarity
‒ Letters a-z, A-Z
‒ Digits 0-9 (note, cannot begin with a digit)
‒ Underscore _
‒ A reserved word must not be used as an identifier!
‒ Do not redefine identifiers of the standard library!

28 University of Oulu
Features of C
User defined identifiers
‒ There is no maximum length for the identifier, but some ANSI C-
compilers require that identifiers must differ in the first 31
characters (to be sure the programs are portable)
‒ Avoid having identifiers that are too much alike, e.g. big and BIG,
unless there is a very good reason for that
‒ Remember case-sensitivity, e.g., netSalary and netsalaray cannot be
used interchangeably (two different identifiers)
‒ Meaningful identifiers increase readability (self-documenting)
29 University of Oulu
Features of C
Variable definitions
‒ Variable is a memory locations that can hold input, output or temporary values
‒ Every variable has a name, type and value.
‒ The type of the data determines the characteristics of the data that may be
stored and the methods (operations) of processing that are permitted

‒ User defined variables, constants, functions and types are identifiers


‒ All variables in a C program must be defined before they are used!
30 University of Oulu
Data Types

University of Oulu
Data Types
The type of the variable determines…
‒ How much space is occupied in storage
‒ How the bit pattern stored is interpreted
‒ Types in C
- Standard, basic types
- Enumerated types
- Void
- Derived types
32 University of Oulu
Data Types – Basic types
Standard data types in C
- Integers (whole numbers): short, int, long
- Real numbers (decimal numbers): float, double
- Character: char
- Truth values: bool (false (0), true (!=0), since c99, included in stdbool.h)

The “-” sign for a number is interpreted as an operator (i.e., not part of the number itself) that
changes the sign of its argument (positive number becomes negative and vice versa), e.g.,

33 University of Oulu
Data Types int
‒ int type of memory location can hold integer numbers (whole numbers)
‒ Storage size of int depends upon the processor in the CPU
‒ Storage size of int is minimum 16 bits (2 bytes, ANSI C)
‒ Thus, able to store values (minimum) from -32768 to 32767
‒ To get the exact size of data type or a variable on a particular platform, you
can use the sizeof operator, e.g.,

34 University of Oulu
Data Types int
Possible arithmetic operations

Operation Arithmetic operator Algebraic expression C expression


Addition + a +2 a+2
Subtraction - a–b a–b
Multiplication * ab a*b
Division / a/b a/b
Remainder % a mod b a%b
‒ You may use == for comparing two integers
‒ The results of arithmetic operations on integers are integers

35 University of Oulu
Data Types double
‒ double type of memory location can hold real numbers
‒ Numerator and decimal are separated with period, e.g., 32.99
‒ Storage size of double is 64 bits (8 bytes)
‒ Able to store values from 2.3E-308 to 1.7E+308 (15 decimal
places)
‒ Very small or large values can be represented with scientific
notation (e or E is interpreted as number 10 which is raised to the
power of the number following it), e.g, 1.23e5 and 1.23E5 equal to
1.23*105
36 University of Oulu
Data Types double
Possible arithmetic operations

Operation Arithmetic operator Algebraic expression C expression


Addition + a +2 a+2
Subtraction - a–b a–b
Multiplication * ab a*b
Division / a/b a/b

‒ Preferably, do not use == for comparing two real numbers


‒ Instead, e.g., check if (fabs(a-b) < epsilon), where epsilon is some small value (e.g., 0.000001)
‒ Never assume that a simple numeric value is accurately represented in the computer, e.g.,
10.0 * 0.1 may not necessarily be 1.0
37 University of Oulu
Data Types double

38 University of Oulu
Data Types char
‒ char type of memory location can hold a single character
‒ Storage size of char is 8 bits (1 byte)
‒ Basically, a char is an integer (as C stores integer numbers)
‒ Able to store values from -128 to 127, or from 0 to 255 (as unsigned)
‒ To represent characters, the computer must map each integer with a
corresponding character using a numerical code, the most common of which
is ASCII (American Standard Code for Information Interchange)
‒ A single character can be represented within single quotes (‘A’, ‘2’,…)
‒ You may compare characters and arithmetic operations are possible

39 University of Oulu
Data Types char

40 University of Oulu
Data Types bool
‒ bool type of memory location can hold a truth value
‒ Storage size of bool is 8 bits (1 byte)
‒ Can have values true and false
‒ Used in logical operations

41 University of Oulu
Data Types enum
‒ enum is an enumeration data type, a list of named integer constants
‒ By default, the value starts from 0 (zero) and is incremented by 1 for the
sequential identifiers in the list
‒ Syntax enum identifier [optional{enumeratr-list}];

University of Oulu
Data Types void
‒ void is an empty data type that has no value
‒ void can be used in functions and pointers, e.g.,
void myFunction(void);
void *pData;

43 University of Oulu
Data Types Derived types
‒ Array
‒ Pointer
‒ Structure
‒ Union

These data types will be introduced later on…

44 University of Oulu
Comments

University of Oulu
Comments
‒ Comments are used to document programs and improve
program readability
‒ Compiler will ignore comments (no machine language
object code will be generated)
‒ Two ways to write comments
- // comment will continue to the end of the line
- /* …. */ any text in between /* and */ are in comments

46 University of Oulu
Comments
Many times // style is preferred as that is shorter and
eliminate common programming errors…

47 University of Oulu
Executable
Statements

University of Oulu
Executable statements
‒ The executable statements in the program are translated into
machine language, loaded into memory and executed (run).
‒ Assignment statement
- Assigns the result of the expression to a variable
- Old value is overwritten (destructive process)
- Common format

result = expression;

University of Oulu
Executable statements
‒ It is also possible to increase or decrease an existing value of a
variable, e.g.,
sum = sum +1; // Increase existing value by 1
myBalance = myBalance – outSum // Subtract outSum from myBalance

‒ A statement is an expression with a value


‒ The data type of an expression depends on the operands, e.g., the
value of a statement (operand operator operand), e.g. (x + y) is int, if
both of the operands are of type int. If one or both of the operands are of
type double, the value of the statement is double.

University of Oulu
Executable statements
For an assignment statement of format
x=y+z
- The value for the expression (y + z) is calculated first
- The type of the value will depend on the operands y and z
- If type of variable x and the type of the expression are the same, OK
- If type of variable x is double and the type of the expression is int,
the resulting integer will be converted to a real number (double)
- If type of variable x is int and the type of the expression is double,
the decimal part of the real number will be removed (no rounding)

University of Oulu
Executable statements
Precedence of arithmetic operators
Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the expression in the
innermost pair is evaluated first. If there are several pairs of
parentheses ”on the same level” (i.e., not nested), they are evaluated
from left to right.
* Multiplication Evaluated second. If there are several, they are evalauted from left to
/ Division right.
% Remainder
+ Addition Evaluated third. If there are several, they are evalauted from left to
- Subtraction right.
= Assignment Evaluated last.

52 University of Oulu
Executable statements
Associativity of the operators
- Unary operator (only one operand) from right to left
int num = 12;
num++;
num--;
- Binary operator (two operands) from left to right
int a = 5, b = 6;
int c = a + b;

53 University of Oulu
Input and
Output (I/O)

University of Oulu
I/O
‒ Most C programs input and/or output data.
‒ A program receives data via input operations and a program reports results
via output operations.
‒ C programming language provides a set of built-in library functions for
feeding input data into the program and providing output to screen, or to a
text or binary file.
‒ In C, most input and output functions use buffering.
‒ Data is first stored to a buffer which is a temporary storage area.
‒ Data is sent to the program when the user has pressed ’enter’ (return).
‒ In C, streams represent input/output data to/from the program
55 University of Oulu
I/O
‒ Standard streams
Stream Description Device
stdin Input stream Keyboard
stdout Output stream Display
stderr Error stream Display

‒ Standard streams are automatically defined & provide access to the keyboard
& screen
‒ Data can also be read without buffering, data returned without waiting for the
enter key, e.g., getch()

56 University of Oulu
I/O Output
‒ I/O-functions usually taken into use with the following directive

‒ Output single character with putchar

‒ Formatted output with printf


printf can format the output according to the needs.

57 University of Oulu
I/O Output
Function argument(s), separated by comma(s)

Function name Conversion specifier for data of type double (myBalance)

List of values to be printed


Format control string
58 University of Oulu
I/O Output
printf function has the common form…
printf(format_control_string, other_arguments);
‒ The format control string in quotation marks…
"The balance in my bank account is %lf Chinese Yuans\n"

‒ List of values to be printed…


Variable myBalance of type double

E.g., if the variable myBalance had the value 5599.15…


The conversion specifier %lf will be replaced with the value from myBalance
The balance in my bank account is 5599.150000 Chinese Yuans

University of Oulu
I/O Output
‒ The conversion specifiers define how the values will be displayed
‒ The conversion specifier always begins with % sign
‒ Every data type has its own conversion specifier, e.g.,
Conversion specifier Data type Function
%d int printf / scanf
%f double printf
%lf double printf / scanf
%c char printf / scanf
%s character string printf / scanf

‒ Please note, %d for printing integers (whole numbers, decimal system), not for doubles

60 University of Oulu
I/O Output
‒ The conversion specifier(s) will be replaced with the variable value(s)
‒ Precision controls the max number of characters to print
‒ Width controls the minimum number, and has the same format as
precision, except without a decimal point
‒ We can control the width of the output by providing a number in
between % and the specifier, indicating the minimum width for the data
- For example, %8d reserves 8 characters for displaying an integer, right
aligned
- In case we want to align the data to left, we need – in between % and
the width of the data, e.g., %-8d

61 University of Oulu
I/O Output
By default, the decimals (for real numbers) are displayed with the system
precision (with six decimals)

The minimum width for displaying the value and the maximum number of
decimals (for a real number) can be controlled, e.g., %7.3lf

62 University of Oulu
I/O Output
‒ For a real number, the decimal part may be rounded for printing (not affecting
the original value).
‒ The specifier for minimum width of the value can be left out.
‒ The maximum number of decimals (for a real number) can be controlled by
providing a period and required number of decimals in between % and the
conversion specifier, e.g., %.2lf

‒ Format control string includes also an escape sequence for newline, \n


‒ In C, all escape sequences begin with a backslash \

63 University of Oulu
I/O Output
‒ A printf statement can be used to display values from multiple variables
‒ If more than one specifier-variable value pairs, be sure the values are in correct order
‒ The conversion specifiers are replaced by the variables in the list of values, in that particular
order

64 University of Oulu
I/O Output
‒ printf statement may have only character string (message or literal)
‒ printf statement may not have any variable values (just text)

65 University of Oulu
I/O – Escape Escape
sequence
Description

\a Alarm
sequences \b Backspace
\r Carriage return (to the beginning of the
line)
\f Form feed (skips to the start of the next
page)
\n Newline
\t Horizontal tabulator
\v Vertical tabulator
\\ Backslash
\0 NUL-value
\” Quotation mark
\’ Single quote
\? Question mark
University of Oulu
I/O Input
In C, there are many functions for feeding data into a
program

Normally, keyboard is used as One character at a time


an input device One line at a time

All data is read as characters and the conversion to the user


defined data type will be done in the process

University of Oulu
I/O Buffered Input
Buffered reading
‒ Reading single characters with function getchar()
int getchar(void);
- Inputs the next character from the standard input and returns it as
an integer.
- Does not care about buffering (reads a single character)
- No arguments

68 University of Oulu
I/O Formatted Input
Formatted Input
‒ Read input from the standard input (usually the keyboard)
int scanf(const char *format, ...);

* Format = string that contains one or more of the following items,


whitespace character, non-whitespace character and format specifiers.
* Depending on the format string, the function may expect a sequence of
additional arguments. There should be the same number of additional
arguments as the number of %-tags that expect a value.

69 University of Oulu
I/O Formatted Input
• Data from the keyboard is copied
scanf into variable mySalary.

• The format %lf specifies the data is


to be stored as a real number.

• The ampersand (&) character is an


address operator and it tells scanf
the storage location (addess in the
memory) of the variable mySalary.

• Scanf waits for the user to enter an


input value. The press of the enter
key sends the value to the
computer & assigns it to the
variable mySalary.

70 University of Oulu
I/O Formatted Input
scanf
‒ Characters typed on the keyboard can be changed until the ’Enter’
key has been pressed
‒ Return value: If successful, the total number of characters written is
returned, otherwise a negative number is returned.
‒ In case there is an error reading the data, the unread data is left in
the buffer!
‒ It is possible to read one or more data values in one scanf function
call. It is recommended to read one data value in a function call.
71 University of Oulu
I/O Formatted Input
Scanf – reading multiple values in one call, NOT recommended though…
The user would have to enter the data values separated by space (or one by one)

The user would have to enter the data values with no spaces in between

72 University of Oulu
I/O Formatted Input
Scanf – reading multiple values in one call, NOT recommended though…
In this case, the program expects the user to input the data
separated by commas

73 University of Oulu

You might also like