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

C Programming Basic Lecture 1

Uploaded by

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

C Programming Basic Lecture 1

Uploaded by

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

INTRODUCTION

TO C
C LANGUAGE HISTORY
Dennis MacAlistair Ritchie was C programming language
• The C programming
an American computer features were derived from an
language is a structure-
scientist. He created the C earlier language called “B”
oriented programming
programming language and, (Basic Combined
language, developed at Bell
with long-time colleague Ken Programming Language –
Laboratories in 1972 by
Thompson, the Unix operating BCPL)
Dennis Ritchie
system and B language.

C language is considered as
the mother language of all the
In 1978, Dennis Ritchie and modern programming
C language was invented to Brian Kernighan published the languages because most of
construct utilities running on first edition “The C the compilers, JVMs, Kernels,
UNIX operating system Programming Language” and etc. are written in C language,
commonly known as K&R C and most of the programming
languages follow C syntax, for
example, C++, Java, C#, etc.
LEVELS OF PROGRAMMING
LANGUAGES
Middle level languages do not provide all the built-in
Middle functions found in high level languages, but to
Level provide all building blocks needed to produce the
result desired. Examples: C, C++
High level languages provide almost everything that
High Level the programmer might need to do as already built
into the language. Example: Java, Python

Low level languages provide nothing other than


Low Level access to the machines basic instruction set.
Example: Assemble
BASIC INPUT AND
OUTPUT IN C
C PROGRAMMING BASICS
C Basic commands Explanation
#include <stdio.h> This is a preprocessor command that includes
standard input output header file(stdio.h) from
the C library before compiling a C program
int main() This is the main function from where execution of
any C program begins.
{ This indicates the beginning of the main function
/*_some_comments_*/ whatever is given inside the command “/* */” in
any C program, won’t be considered for
compilation and execution
printf(“Hello_World! “); printf command prints the output onto the
screen.
getch(); / getche(); This command waits for any character input from
keyboard
return 0; This command terminates C program (main
PREPROCESSOR
DIRECTIVES
#include preprocessor – it is used to
include header files to a C program.

#define – it is used to define a fragment


of code that is given with a name.
stdio.h – input and output
functions.
conio.h – console input
BASIC and output functions.
ctype.h – character
LIST OF handling functions
HEADE math.h – mathematics
functions
R FILES string.h – string functions
time.h – date and time
functions
C PROGRAM STRUCTURE
Preprocessor Directives
Program defined by:
 global declarations
Global Declarations  function definitions
Function Definitions May contain
int main () { preprocessor
Local Declarations directives
Statements Always has one
function named main,
} may contain others
DECLARATIONS
Global
 visible throughout program
 describes data used throughout program

Local
 visible within function
 describes data used only in function
PREPROCESSOR DIRECTIVES
Begin with #
Instruct compiler to perform some transformation to file before
compiling
Example: #include <stdio.h>
 add the header file stdio.h to this file
 .h for header file
 stdio.h defines useful input/output functions
VARIABLES
Naming a Variable
 Must be a valid identifier.
 Must not be a keyword
 Names are case sensitive.
 Variables are identified by only first 32 characters.
 Library commonly uses names beginning with _.
 Naming Styles: Uppercase style and Underscore style
 lowerLimit lower_limit
 incomeTax income_tax

Lectures on Numerical Methods 11


DECLARATIONS
Declaring a Variable
 Each variable used must be declared.
 A form of a declaration statement is
data-type var1, var2,…;
 Declaration announces the data type of a variable and allocates appropriate
memory location. No initial value (like 0 for integers) should be assumed.
 It is possible to assign an initial value to a variable in the declaration itself.
data-type var = expression;
 Examples
int sum = 0;
char newLine = ‘\n’;
float epsilon = 1.0e-6;

Lectures on Numerical Methods 12


GLOBAL AND LOCAL
VARIABLES
/* Compute Area and Perimeter of a circle */
Global Variables
#include <stdio.h>
float pi = 3.14159; /* Global */
 These variables are declared outside all functions.
 Life
main() { time of a global variable is the entire execution period of the
float rad;
program. /* Local */

printf(
Can be“Enter
accessed by “any
the radius ); function defined below the declaration, in a file.
scanf(“%f” , &rad);

if ( rad > 0.0 ) {


float area = pi * rad * rad;
float peri = 2 * pi * rad;

printf( “Area = %f\n” , area );


printf( “Peri = %f\n” , peri );
}
else
printf( “Negative radius\n”);

printf( “Area = %f\n” , area );


}

Lectures on Numerical Methods 13


VARIABLE NAME
Legal identifier
Not a reserved word
Must be unique:
 not used before
 variable names in functions (local declarations) considered to be qualified by
function name
 variable x in function main is different from x in function f1
MULTIPLE VARIABLE
DECLARATIONS
Can create multiple variables of the same type in one statement:
int x, y, z;
is a shorthand for
int x;
int y;
int z;
- stylistically, the latter is often preferable
VARIABLE INITIALIZATION
Giving a variable an initial value
Variables not necessarily initialized when declared (value is
unpredictable - garbage)
Can initialize in declaration:
Syntax: Type Name = Value;
Example:
int x = 0;
INITIALIZATION VALUES
Literal constant (token representing a value, like 5 representing the
integer 5)
An expression (operation that calculates a value)
Function call

The value, however specified, must be of the correct type


MULTIPLE DECLARATION
INITIALIZATION
Can provide one value for variables initialized in one statement:
int x, y, z = 0;

Each variable declared and then initialized with the value


VARIABLE TYPE
Indicates how much memory to set aside for the variable
Also determines how that space will be interpreted
Basic types: char, int, float
 specify amount of space (bytes) to set aside
 what can be stored in that space
 what operations can be performed on those vars
FUNCTIONS
Consists of header and body
 header: int main ()
 body: contained between { and }
 starts with location declarations
 followed by series of statements

More than one function may be defined


Functions are called (invoked) - more later
SYNTAX OF C
Rules that define C language
 Specify which tokens are valid
 Also indicate the expected order of tokens

Some types of tokens:


 reserved words: include printf int ...
 identifiers: x y ...
 literal constants: 5 ‘a’ 5.0 ...
 punctuation: { } ; < > # /* */
IDENTIFIER
Names used for objects in C
Rules for identifiers in C:
 first char alphabetic [a-z,A-Z] or underscore (_)
 has only alphabetic, digit, underscore chars
 first 31 characters are significant
 cannot duplicate a reserved word
 case (upper/lower) matters
RESERVED WORDS
Identifiers that already have meaning in C

Examples:
 include, main, printf, scanf, if, else, …
 more as we cover C language
VALID/INVALID IDENTIFIERS
Valid
Invalid
sum
7of9
c4_5
x-name
A_NUMBER
name with spaces
longnamewithmanychars
1234a
TRUE
int
_split_name
AXYZ&
MAIN FUNCTION
Every program has one function main
Header for main: int main ()
Program is the sequence of statements between the { } following
main
Statements are executed one at a time from the one immediately
following to main to the one before the }
COMMENTS
Text between /* and */
Used to “document” the code for the human reader
Ignored by compiler (not part of program)
Have to be careful
 comments may cover multiple lines
 ends as soon as */ encountered (so no internal comments - /* An /* internal */
comment */)
COMMENT EXAMPLE
#include <stdio.h>

/* This comment covers


* multiple lines
* in the program.
*/

int main () /* The main header */ {


/* No local declarations */

printf(“Too many comments\n”);


} /* end of main */
TYPE
Set of possible values
 defines size, how values stored, interpreted

Operations that can be performed on those possible values


Data types are associated with objects in C (variables, functions,
etc.)
LITERAL CONSTANTS
Sequences of characters (tokens) that correspond to values from
that type
-35 is the integer -35
3.14159 is the floating pointer number 3.14159
‘A’ is the character A

Can be used to initialize variables


VOID TYPE
Type name: void
Possible values: none
Operations: none
Useful as a placeholder
INTEGER TYPE
Type name:
 int
 short int
 long int

Possible values: whole numbers (within given ranges) as in 5, -35,


401
Operations: arithmetic (addition, subtraction, multiplication, …),
and others
INTEGER TYPES/VALUES
Type Bytes Bits Min Val Max Val

short int 2 16 -32768 32767

int 4 32 -2147483648 2147483647

long int 4 32 -2147483648 2147483647


UNSIGNED INTEGERS
Type: unsigned int
No negative values
unsigned int:
 possible values: 0 to 65536

Representation: binary number


STANDARD TYPES
Atomic types (cannot be broken down)
 void
 char
 int
 float, double

Derived types
 composed of other types
INTEGER LITERAL
CONSTANTS
Syntax:
1 or more digits
Optional leading sign (+ or -)
Optional l or L at the end for long
Optional u or U for unsigned

Examples:
5, -35, 401, 4010L, -350L, 2000UL
FLOATING-POINT TYPE
Type names:
 float
 double
 long double

Possible values: floating point numbers, 5.0 -3.5, 4.01


Operations: arithmetic (addition, subtraction, multiplication, …),
and others
FLOATING-POINT
REPRESENTATION
float: 4 bytes, 32 bits
double: 8 bytes, 64 bits
long double: 10 bytes, 80 bits
Representation:
 magnitude (some number of bits) plus exponent (remainder of bits)
 3.26 * 10^4 for 32600.0
FLOATING-POINT
LIMITATIONS
Maximum, minimum exponents
 maximum possible value (largest positive magnitude, largest positive exponent)
 minimum value (largest negative magnitude, largest positive exponent)
 can have overflow, and underflow

Magnitude limited
 cannot differentiate between values such as 1.00000000 and 1.00000001
FLOATING-POINT LITERALS
Syntax:
 Zero or more digits, decimal point, then zero or more digits (at least one digit)
 Whole numbers also treated as float
 Optional sign at start
 Can be followed by e and whole number (to represent exponent)
 f or F at end for float
 l or L at end for long double

Examples: 5, .5, 0.5, -1.0, 2.1e+3, 5.1f


CHARACTER TYPE
Type name: char
Possible values: keys that can be typed at the keyboard
Representation: each character assigned a value (ASCII values), 8
bits
 A - binary number 65
 a - binary number 97
 b - binary number 98
 2 - binary number 50
CHARACTER LITERALS
Single key stroke between quote char ‘
Examples: ‘A’, ‘a’, ‘b’, ‘1’, ‘@’
Some special chars:
 ‘\0’ - null char
 ‘\t’ - tab char
 ‘\n’ - newline char
 ‘\’’ - single quote char
 ‘\\’ - backslash char
STRING LITERALS
No string type (more later)
Contained between double quote chars (“)
Examples:
“” - null string
“A string”
“String with newline \n char in it”
“String with a double quote \” in it”
CONSTANTS
Literal constants - tokens representing values from type
Defined constants
 syntax: #define Name Value
 preprocessor command, Name replaced by Value in program
 example: #define MAX_NUMBER 100
CONSTANTS (CONT)
Memory constants
 declared similar to variables, type and name
 const added before declaration
 Example: const float PI = 3.14159;
 Can be used as a variable, but one that cannot be changed
 Since the value cannot be changed, it must be initialized
FORMATTED INPUT/OUTPUT
Input comes from files
Output sent to files
Other objects treated like files:
 keyboard - standard input file (stdin)
 monitor - standard output file (stdout)

Generally send/retrieve characters to/from files


FORMATTED OUTPUT
Command: printf - print formatted
Syntax: printf(Format String, Data List);
 Format string any legal string
 Characters sent (in order) to screen

Ex.: printf(“Welcome to\nCS 1621!\n”);


causes
Welcome to
CS 1621!
to appear on monitor
FORMATTED OUTPUT (CONT)
Successive printf commands cause output to be added to previous
output
Ex.
printf(“Hi, how “);
printf(“is it going\nin 1621?”);
prints
Hi, how is it going
in 1621?
To the monitor
FIELD SPECIFICATIONS
Format string may contain one or more field specifications
 Syntax: %[Flag][Width][Prec][Size]Code
 Codes:
 c - data printed as character
 d - data printed as integer
 f - data printed as floating-point value
 For each field specification, have one data value after format string, separated
by commas
FIELD SPECIFICATION
EXAMPLE
printf(“%c %d %f\n”,’A’,35,4.5);
produces
A 35 4.50000
(varies on different computers)

Can have variables in place of literal constants (value of variable


printed)
WIDTH AND PRECISION
When printing numbers, generally use width/precision to determine
format
 Width: how many character spaces to use in printing the field (minimum, if more
needed, more used)
 Precision: for floating point numbers, how many characters appear after the
decimal point, width counts decimal point, number of digits after decimal,
remainder before decimal
WIDTH/PRECISION EXAMPLE
printf(“%5d%8.3f\n”,753,4.1678);
produces
753 4.168
values are right justified

If not enough characters in width, minimum number used


use 1 width to indicate minimum number of chars should be used
LEFT JUSTIFICATION (FLAGS)
Put - after % to indicate value is left justified
printf(“%-5d%-8.3fX\n”,753,4.1678);
produces
753 4.168 X

For integers, put 0 after % to indicate should pad with 0’s


printf(“%05d”,753);
produces
00753
SIZE INDICATOR
Use hd for small integers

Use ld for long integers

Use Lf for long double

Determines how value is treated


PRINTF NOTES
Important to have one value for each field specification
 some C versions allow you to give too few values (garbage values are formatted
and printed)

Values converted to proper type


 printf(“%c”,97); produces the character a on the screen
FORMATTED INPUT
Command: scanf - scan formatted
Syntax: scanf(Format String, Address List);
 Format string a string with one or more field specifications
 Characters read from keyboard, stored in variables

scanf(“%c %d %f”,&cVar,&dVar,&fVar);
attempts to read first a single character, then a whole number, then a floating
point number from the keyboard
FORMATTED INPUT (CONT)
Generally only have field specifications and spaces in string
 any other character must be matched exactly (user must type that char or
chars)
 space characters indicate white-space is ignored
 “white-space” - spaces, tabs, newlines
 %d and %f generally ignore leading white space anyway (looking for numbers)
 %d and %f read until next non-number char reached
FORMATTED INPUT (CONT)
More notes
 can use width in field specifications to indicate max number of characters to
read for number
 computer will not read input until return typed
 if not enough input on this line, next line read, (and line after, etc.)
 inappropriate chars result in run-time errors (x when number expected)
 if end-of-file occurs while variable being read, an error occurs
ADDRESS OPERATOR
& - address operator
Put before a variable (as in &x)
Tells the computer to store the value read at the location of the
variable
More on address operators later
SCANF RULES
Conversion process continues until
 end of file reached
 maximum number of characters processed
 non-number char found number processed
 an error is detected (inappropriate char)

Field specification for each variable


Variable address for each field spec.
Any character other than whitespace must be matched exactly
SCANF EXAMPLE
scanf(“%d%c %f”,&x,&c,&y);
and following typed:
-543A

4.056 56
-543 stored in x, A stored in c, 4.056 stored in y, space and 56 still
waiting (for next scanf)
PROMPTING FOR INPUT
Using output statements to inform the user what information is
needed:
printf(“Enter an integer: “);
scanf(“%d”,&intToRead);

Output statement provides a cue to the user:


Enter an integer: user types here
OPERATORS
Arithmetic Operators
 +, - , *, / and the modulus operator %.
 + and – have the same precedence and associate left to right.
3 – 5 + 7 = ( 3 – 5 ) + 7  3 – ( 5 + 7 )
3 + 7 – 5 + 2 = ( ( 3 + 7 ) – 5 ) + 2
 *, /, % have the same precedence and associate left to right.
 The +, - group has lower precendence than the *, / % group.
3 – 5 * 7 / 8 + 6 / 2
3 – 35 / 8 + 6 / 2
3 – 4.375 + 6 / 2
3 – 4.375 + 3
-1.375 + 3
1.625
Lectures on Numerical Methods 62
OPERATORS
Arithmetic Operators
 % is a modulus operator. x % y results in the remainder when x is divided by y
and is zero when x is divisible by y.
 Cannot be applied to float or double variables.
 Example
if ( num % 2 == 0 )
printf(“%d is an even number\n”, num)’;
else
printf(“%d is an odd number\n”, num);

Lectures on Numerical Methods 63


TYPE CONVERSIONS
 The operands of a binary operator must have a the same type and the result is
also of the same type.
 Integer division:
c = (9 / 5)*(f - 32)
The operands of the division are both int and hence the result also would be int.
For correct results, one may write
c = (9.0 / 5.0)*(f - 32)
 In case the two operands of a binary operator are different, but compatible, then
they are converted to the same type by the compiler. The mechanism (set of
rules) is called Automatic Type Casting.
c = (9.0 / 5)*(f - 32)
 It is possible to force a conversion of an operand. This is called Explicit Type
casting.
c = ((float) 9 / 5)*(f - 32)
Lectures on Numerical Methods 64
AUTOMATIC TYPE CASTING
1. char and short operands are converted to int
2. Lower data types are converted to the higher
Hierarchy
Double
data types and result is of higher type.
3. The conversions between unsigned and signed float
types may not yield intuitive results. long
4. Example
Int
float f; double d; long l;
int i; short s; Short and
d + f f will be converted to double char
i / s s will be converted to int
l / i i is converted to long; long result

Lectures on Numerical Methods 65


EXPLICIT TYPE CASTING
 The general form of a type casting operator is
 (type-name) expression
 It is generally a good practice to use explicit casts than to rely on automatic type
conversions.
 Example
C = (float)9 / 5 * ( f – 32 )
 float to int conversion causes truncation of fractional part
 double to float conversion causes rounding of digits
 long int to int causes dropping of the higher order bits.

Lectures on Numerical Methods 66


PRECEDENCE AND ORDER
OF EVALUATION

Lectures on Numerical Methods 67


PRECEDENCE AND ORDER
OF EVALUATION

Lectures on Numerical Methods 68


OPERATORS
Relational Operators
 <, <=, > >=, ==, != are the relational operators. The expression
operand1 relational-operator operand2
takes a value of 1(int) if the relationship is true and 0(int) if relationship is false.
 Example
int a = 25, b = 30, c, d;
c = a < b;
d = a > b;
value of c will be 1 and that of d will be 0.

Lectures on Numerical Methods 69


OPERATORS
Logical Operators
 &&, || and ! are the three logical operators.
 expr1 && expr2 has a value 1 if expr1 and expr2 both are nonzero.
 expr1 || expr2 has a value 1 if expr1 and expr2 both are nonzero.
 !expr1 has a value 1 if expr1 is zero else 0.
 Example
 if ( marks >= 40 && attendance >= 75 ) grade = ‘P’
 If ( marks < 40 || attendance < 75 ) grade = ‘N’

Lectures on Numerical Methods 70


OPERATORS
Assignment operators
 The general form of an assignment operator is
 v op= exp
 Where v is a variable and op is a binary arithmetic operator. This statement is
equivalent to
 v = v op (exp)
a = a + b can be written as a += b
a = a * b can be written as a *= b
a = a / b can be written as a /= b
a = a - b can be written as a -= b

Lectures on Numerical Methods 71


OPERATORS
Increment and Decrement Operators
 The operators ++ and –- are called increment and decrement operators.
 a++ and ++a are equivalent to a += 1.
 a-- and --a are equivalent to a -= 1.
 ++a op b is equivalent to a ++; a op b;
 a++ op b is equivalent to a op b; a++;
 Example
Let b = 10 then
(++b)+b+b = 33
b+(++b)+b = 33
b+b+(++b) = 31
b+b*(++b) = 132

Lectures on Numerical Methods 72


FLOATING POINT
ARITHMETIC
0.d1d 2  d p B e
Representation
 All floating point numbers are stored as

 such that d1 is nonzero. B is the base. p is the precision or number of significant


digits. e is the exponent. All these put together have finite number of bits
(usually 32 or 64 bits ) of storage.
 Example
 Assume B = 10 and p = 3.
 23.7 = +0.237E2
 23.74 = +0.237E2
 37000 = +0.370E5
 37028 = +0.370E5
 -0.000124 = -0.124E-4
Lectures on Numerical Methods 73
FLOATING POINT
ARITHMETIC
Representation
 Sk = { x | Bk-1 <= x < Bk }. Number of elements in each Sk is same. In the
previous example it is 900.
 Gap between seuccessive numbers of Sk is Bk-p.
 B1-p is called machine epsilon. It is the gap between 1 and next representable
number.
 Underflow and Overflow occur when number cannot be represented because it is
too small or too big.
 Two floating points are added by aligning decimal points.
 Floating point arithmetic is not associative and distributive.

Lectures on Numerical Methods 74


KEY POINTS TO REMEMBER
IN C PROGRAMMINGEach
BASICS
C
programming
C programming is statement is
a case sensitive ended with
programming semicolon (;)
language. which are referred
as statement
C programs are
terminator.
printf() command
compiled using C
is used to print
compilers and
the output onto
displays output
the screen.
when executed.

You might also like