Sie sind auf Seite 1von 72

Lesson 01: Introduction to C

C Programming

Why c was developed?


C language was developed to write UNIX
OS. Why?
earlier version of UNIX OS written in Assembly
language for PDP-7 (Programmed Data
Processor-7) computer
Writing in assembly proved awkward; it took
longer to code data structures, and it was harder
to debug and understand

C Programming

Early C, UNIX, and Associated


Hardware

C Programming

B Language
In 1969, Thompson (researcher at Bell Labs)
created the language B by simplifying the
research language Basic Combined
Programming Language (BCPL) so its
interpreter would fit in the PDP-7's 8K word
memory
the hardware memory limits only provided
room for an interpreter, not a compiler. The
resulting slow performance prevented B from
being used for systems programming of
UNIX itself.
C Programming

Shortcomings of B Language
B also retained the typelessness of BCPL;
the only operand was a machine word
New computer PDP-11 featured hardware
support for data types of several different
sizes, and the B language had no way to
express this
Performance was also a problem, leading
Thompson to reimplement the UNIX OS in
PDP-11 assembler rather than B

C Programming

Language New B
Dennis Ritchie capitalized on the more
powerful PDP-11 to create "New B," which
solved both problems, multiple data types,
and performance. "New B"the name
quickly evolved to "C"was compiled rather
than interpreted, and it introduced a type
system, with each variable described in
advance of its use

C Programming

BCPL->B->New B->C
The initial development of C occurred at
AT&T Bell Labs between 1969 and 1973;
according to Ritchie, the most creative period
occurred in 1972. At that year a great part of
Unix was rewritten in C.
By 1973, with the addition of struct types, the
C language had become powerful enough
that most of the Unix kernel was in C. The
new language was named "C" because its
features were derived from "B
Unix was one of the first operating system
kernels implemented in a language other
C Programming
than assembly.

C Standardization
K & R C in
1978

ANSI C/C89

ISO C/C90

ISO/IEC
9899:1999/C99
C Programming

The C Programming Lang. 1st edition by


Kernighan & Ritchie
Different versions of C were implemented for
a wide variety of computers, so c was not
portable
90% K& R C; the non-portable portion of the
Unix C library was removed; standardized c
library; function prototypes
ANSI C adopted by ISO, ISO/IEC 9899; no
change

Mostly backward compatible; Inline


functions; Single line comments; long long
int; complex data type; not completely
implemented in many compilers

C/C++ Applications
Operating Systems:
UNIX, Windows 95, 98, 2000, XP, Apple OS X,
Symbian OS

Language Compilers:
Portable C Compiler (PCC)

Simulators
GEMS, gem5

Applications:
Adobe Systems, MySQL, Winamp Media Player,
Mozilla Firefox browser

Embedded Systems
Microcontroller programming
C Programming

C influence on other languages


Many later languages have borrowed directly
or indirectly from C
including C++, D, Go, Rust, Java, JavaScript,
Limbo, LPC, C#, Objective-C, Perl, PHP, Python,
Verilog and Unix's C shell.
drawn many of their control structures and other
basic features from C.
Most of them (with Python being the most
dramatic exception) are also very syntactically
similar to C in general,

C Programming

Strengths and Weaknesses of C


Like any other programming language, C has
strengths and weaknesses. Both stem from
the language's original use (writing operating
systems and other systems software) and its
underlying philosophy:
C is a low-level language. To serve as a suitable language
for systems programming, C provides access to machinelevel concepts (bytes and addresses, for example) thal
other programming languages try to hide. C also provides
operations that correspond closely to a computer's buill-in
instructions, so that programs can be fast. Since application
programs rely on it for input/output, storage management,
and numerous other services, an operating system can't
afford to be slow.
C Programming

Strengths and Weaknesses of C


C is a small language. C provides a more limited
set of fealures than many languages. To keep the
number of features small, C relies heavily on a
"library" of standard functions.
C is a permissive (not strict) language. C
assumes that you know what you' re doing, so it
allows you a wider degree of freedom than many
languages. Moreover, C doesn't mandate the
detailed error-checking found in other languages.

C Programming

Strengths
Efficiency. Efficiency has been one of C's
advantages from the beginning. Because C was
intended for applications where assembly
language had traditionally been used. It was
crucial that C programs could run quickly and in
limited amounts of memory.
Portability. Although program portability wasn' t a
primary goal of C, it has turned out to be one of
the language's strengths. When a program must
run on computers ranging from PCs to
supercomputers, it is often written in C. Another is
that C compilers are small and easily written.
which has helped make them widely available.
C Programming

Strengths
Power. C's large collection of data types and
operators help make it a powerful language. In C,
it's often possible to accomplish quite a bit with
just a few lines of code.
Flexibility. Although C was originally designed for systems
programming, it has no inherent restrictions that limit it to
this arena. C is now used for appIications of all kinds, from
embedded systems to commercial data processing.
Moreover, C imposes very few restrictions on the use of its
features; operations that would be illegal in other languages
are often permitted in C. For example, C allows a character
to be added to an integer/ floating value. This flexibility can
make programming easier, although it may allow some bugs
to slip through.

C Programming

Strengths
Standard library. One of C's greal strengths is its
standard library, which contains hundreds of
functions for input/output, string handling, storage
allocation, and other useful operations.
Integration with UNIX. C is particularly powerful in
combination with UNIX (including the popular
variant known as Linux). In fact, some UNIX tools
assume that the user knows C.

C Programming

Weaknesses
C's weaknesses arise from the same source
as many of its strengths: C's closeness to the
machine. Here are a few of C's most
notorious problems:
C programs can be error-prone: In this respect, C
is a lot like assembly language, where most errors
aren't detected until the program is run. we' ll see
how an extra semicolon can create an infinite loop
or a missing & symbol can cause a program
crash.

C Programming

Weaknesses
C programs can be difficult to understand: C's
terse nature make programs hard to understand.
C was designed at a time when interactive
communication with computers was tedious at
best. As a result, C was purposefully kept terse to
minimize the time required to enter and edit
programs. C's flexibility can also be a negative
factor; programmers who are too clever for their
own good can make programs almost impossible
to understand.

C Programming

Weaknesses
C programs can be difficult to modify. Large
programs written in C can be hard to change if
they haven't been designed with maintenance in
mind. Modern programming languages usually
provide features such as classes and packages
that support the division of a large program into
more manageable pieces. C. unfortunately. lacks
such features.

C Programming

Compiling & Linking


Source
code
header
files

Preprocessor

Compiler
Library
or
other
files

Object
code
Linker
Executabl
e code

C Programming

Source Code

C Programming

Compiling and Linking

C Programming

Running

C Programming

Integer Data Types


Type

Size signed
(B)

unsigned

char
short
int

1
2
4

128 to +127
32,768 to +32,767
2,147,483,648 to
+2,147,483,647

0 to 255
0 to 65,535
0 to
4,294,967,29
5

long

9,223,372,036,854,775,80
8 to
+9,223,372,036,854,775,
807

0 to
18,446,744,0
73,709,551,6
15

C Programming

Integer Data Types


The individual sizes are machine/ compiler
dependent. However, the following is
guaranteed: char<short<=int<=long
The language does not specify whether
variables of type char are signed or unsigned
quantities, but printable characters are
always positive (a-z,A-Z,0-9,!,@,#,$,%,^,
etc).

C Programming

Integer Data Types


char c=a;//fine
char c=\x61;//also a but not portable if
character set is other than ASCII
short s; short int s; signed short s; signed
short int s;
int i; signed int i;
long l; long int l; signed long l; signed long int
l;

C Programming

Size of Integer Data Types


/*Testing sizeof*/
#include <stdio.h>
int main(){
printf(Size in Bytes:\n);
printf(char size: %ld\n,
sizeof(char));
printf(short size: %ld\n,
sizeof(short));
printf(int size: %ld\n, sizeof(int));
printf(long size: %ld\n,
sizeof(long));
C Programming

limits.hinteger ranges
char
SCHAR_MIN, SCHAR_MAX, UCHAR_MAX

short
SHRT_MIN, SHRT_MAX, USHRT_MAX

int
INT_MIN, INT_MAX, UINT_MAX

long
LONG_MIN, LONG_MAX, ULONG_MAX

C Programming

Printing integer limits


/*Testing sizeof*/
#include <stdio.h>
#include <limits.h>
int main(){
printf(Min char No.: %d\n, SCHAR_MIN );
printf(Max char No.: %d\n, SCHAR_MAX );
printf(Unsigned char No.: %d\n, UCHAR_MAX );
//print rest of yourself
return 0;
}

C Programming

Floating-Point Data types


Type
float

double

Size(bytes signed
)
4
3.4E +/- 38
8

1.7E +/- 308

The individual sizes are machine/


compiler dependent. However,
the following is guaranteed:
float<=double

C Programming

float.hfloating point range


#include <stdio.h>
#include <float.h>
int main() {
printf("The maximum value of float
= %.10e\n", FLT_MAX);
printf("The minimum value of float
= %.10e\n", FLT_MIN);
//print for double, DBL_MIN,
DBL_MAX
return 0;
}
C Programming

Adding Two Integers


Write a program which adds two integer
numbers, number1 & number2, and finally
display result?
use two variables, namely number1 and number2
store the result in some variable, namely result
print the result on the screen

C Programming

Adding Two Integer inputs


/*Adding 2 numbers */
#include <stdio.h>
int main(){
int number1;
int number2;
int result;
printf(Enter first
number:\n);scanf(%d,&number1);
printf(Enter sec
number:\n);scanf(%d,&number2);
result = number1 + number2;
printf(Adding %d with %d equals to %d,
number1, number2,result);
return 0;
C Programming

Variable
Variable is a named location in a computers
memory
0
1
2
3
.
.
.

4G-1
C Programming

R
A
M

Variable name
Letters(a-z, A-Z), Digits(0-9), underscore(_)
First character must be a letter
Don't begin variable names with underscore,
but you can.
C language is case sensitive. So Upper and
lower case letters are distinct
Traditional C practice is to use lower case for
variable names
No keyword as variable name
variable name should describe the purpose
of it.
C Programming

Variable name
Examples:
number1
1number //illegal
_1number //ok
_result_12
long //illegal
total values//illegal

C Programming

printf
/*printf() usage
int printf ( const char * form, ... );
format: %[flags][width][.precision]
[length]specifier*/
#include <stdio.h>
int main(){
char c=A;
short s=12345;
int i=23;
long l=12121;
printf(c=%c, s=%d, i=%d, l=%ld\n,c,s,I,l);//d or i
printf(c=%d, s=%d, i=%d, l=%ld\n,c,s,I,l);//%c
replaced with %d
printf(c=%hhd, s=%hd, i=%d, l=%ld\n,c,s,I,l);//hhd,hd
return 0;
}
C Programming

printf
/*Breaking string in the printf() to multiple
lines*/
#include <stdio.h>
int main(){
printf(hello world\n);
printf(hello world
);//wrong
//one sol
printf("hello ");
printf("world");
printf("\n");
//or
printf("hello \
"world\n");

C Programming

scanf function
int scanf ( const char * format, ... );
Read formatted data from stdin
Reads data from stdin and stores them
according to the parameter format into the
locations pointed by the additional
arguments.
The additional arguments should point to
already allocated objects of the type
specified by their corresponding format
specifier within the format string.

C Programming

scanf parameters
format: C string that contains a sequence of
characters that control how characters
extracted from the stream are treated:
Whitespace character: the function will read and
ignore any whitespace characters encountered
before the next non-whitespace character
(whitespace characters include spaces, newline
and tab characters -- see isspace). A single
whitespace in the format string validates any
quantity of whitespace characters extracted from
the stream (including none).
scanf( %d,&number1); scanf( %d %d
,&num1,&num2);
C Programming

scanf parameters
Non-whitespace character, except format specifier
(%): Any character that is not either a whitespace
character (blank, newline or tab) or part of a format
specifier (which begin with a %character) causes the
function to read the next character from the stream,
compare it to this non-whitespace character and if it
matches, it is discarded and the function continues
with the next character of format. If the character
does not match, the function fails, returning and
leaving subsequent characters of the stream unread.
scanf( %d, %d ,&num1,&num2);
scanf( %d , %d,&num1,&num2);//different

C Programming

scanf parameters
Format specifiers: A sequence formed by an
initial percentage sign (%) indicates a format
specifier, which is used to specify the type
and format of the data to be retrieved from
the stream and stored into the locations
pointed by the additional arguments
scanf( %d\n,&num1);

C Programming

Arithmetic Operators
Operator

Meaning

Examples

Addition

x=3+2;
z=x+y;

Subtraction

x=3-2;
z=x-y;

Multiplication

x=3*2; z=x*y*23;

Division

x=3/2;
z=x/y;

Remainder

x=5%2;
z=x%y

C Programming

Relational Operators
Used for comparison
result is either 1(true) or 0 (false)
< less than
<= less than or equal to
> greater than
>= greater than or equal to

lower precedence than arithmetic operators

C Programming

Equality Operators
test if numbers are equal or not
result is either 1(true) or 0 (false)
== equal
!= not equal

lower precedence than relational operators

C Programming

Logical Operator
&& true (1) if both values are non-zero
|| true (1) if both either value is non-zero
&& and || evaluated left to right, and
evaluation stops as soon as the truth or
falsehood of the result is known
! converts non-zero value to false (0) and
zero value to true(1)
The precedence of && is higher than that of
||, and both are lower than relational and
equality operators
C Programming

Unary Increment & Decrement


++ increment
-- decrement
both can be used as prefix and postfix
n++;++n;

But the expression ++n increments n before


its value is used, while n++ increments n
after its value has been used. This means
that in a context where the value is being
used, ++n and n++ are different

C Programming

Unary Increment & Decrement


If n is 5, then
x = n++; sets x to 5, but
x = ++n; sets x to 6.
In both cases, n becomes 6

The increment and decrement operators can


only be applied to variables; an expression
like (i+j)++ is illegal

C Programming

Unary Increment & Decrement


s[j++] = s[i]; is equivalent to
s[j] = s[i]; j++;

C Programming

Bit-wise Operators
only applied to integral operands, that is,
char, short, int, and long, whether signed or
unsigned
& bitwise AND
| bitwise inclusive OR
^ bitwise exclusive OR
<< left shift
>> right shift
~ one's complement (unary)

C Programming

Bit-wise Operators
The bitwise AND operator & is often used to
mask off some set of bits
n = n & 0177; //sets to zero all but the low-order 7
bits of n.

The bitwise OR operator | is used to turn bits


on:
x = x | SET_ON; sets to one in x the bits that are
set to one in SET_ON.

The bitwise exclusive OR operator ^ sets a


one in each bit position where its operands
have different bits, and zero where they are
the same.
C Programming

Bit-wise Operators
&& and & are not same. if x is 1 and y is 2,
then x & y is zero while x && y is one.
The shift operators << and >> perform left
and right shifts of their left operand by the
number of bit positions given by the right
operand, which must be non-negative.
Thus x << 2 shifts the value of x by two positions,
filling vacated bits with zero; this is equivalent to
multiplication by 4.

Right shifting an unsigned quantity always


fits the vacated bits with zero.
C Programming

Bit-wise Operators
Right shifting a signed quantity will fill with bit
signs (``arithmetic shift'') on some machines
and with 0-bits (``logical shift'') on others.
The unary operator ~ yields the one's
complement of an integer; that is, it converts
each 1-bit into a 0-bit and vice versa.
x = x & ~077 better than x & 0177700 sets the
last six bits of x to zero.

C Programming

Bit-wise Operators
Note that x & ~077 is independent of word length,
and is thus preferable to, for example, x &
0177700, which assumes that x is a 16-bit
quantity. The portable form involves no extra cost,
since ~077 is a constant expression that can be
evaluated at compile time.

C Programming

Arithmetic assignment operators


+ =, - =, * =, / =,% =,<< =,>> =,&=, ^=, | =
expr1 op= expr2 is equivalent to expr1 =
(expr1) op (expr2)

C Programming

Conditional Expressions
expr1 ? expr2 : expr3
the expression expr1 is evaluated first. If it is nonzero (true), then the expression expr2 is
evaluated, and that is the value of the conditional
expression. Otherwise expr3 is evaluated, and
that is the value. Only one of expr2 and expr3 is
evaluated
z = (a > b) ? a : b; /* z = max(a, b) */
if f is a float and n an int, then the expression (n >
0) ? f : n is of type float regardless of whether n is
positive.

C Programming

Conditional Expressions
for (i = 0; i < n; i++)
printf("%6d%c", a[i], (i%10==9 || i==n-1) ?
'\n' : ' ');
A newline is printed after every tenth element, and
after the n-th. All other elements are followed by
one blank

printf("You have %d items%s.\n", n, n==1 ? ""


: "s");

C Programming

Constants
Character constants: a
char c=A;

Integer constants:
34565 signed int
123u or 123U unsgined int
23232L or 23232l signed long
121234UL unsigned long
can be written in octal(0) and hexadecimal (0X or
0x) format

C Programming

Constants
String: a sequence of zero or more
characters surrounded by double quotes
My name is abid
My name is Arif, studying IIU.\

I am a 2nd year student.

C Programming

Escape sequences
sequences look like two characters, but
represent only one:
\a alert (bell) character
\b backspace
\f form feed
\n newline or line feed
\r carriage return
\t horizontal tab
\v vertical tab
\\backslash

C Programming

Escape sequences
\?question mark
\' single quote
\" double quote
\ooo octal number --\xhh hexadecimal number ---leading x
'\0' represents the character with value zero, the
null character

C Programming

Escape sequences Usage


/* write a prog that shows how escape
sequences work */

C Programming

Some Program Exercises


#include <stdio.h>
/* print Fahrenheit to Celsius : C=5*(F-32) / 9*/
int main() {
int fahr, celsius;
fahr = 1;
celsius = 5 * (fahr-32) / 9;
printf(Fahrenheit Celsius\n);
printf("%-10d %-7d\n", fahr, celsius);
fahr = fahr + 50; celsius = 5 * (fahr-32) / 9;
printf("%-10d %-7d\n", fahr, celsius);
fahr = fahr + 50; celsius = 5 * (fahr-32) / 9;
printf("%-10d %-7d\n", fahr, celsius);
fahr = fahr + 50; celsius = 5 * (fahr-32) / 9;
printf("%-10d %-7d\n", fahr, celsius);
fahr = fahr + 50; celsius = 5 * (fahr-32) / 9;
printf("%-10d %-7d\n", fahr, celsius); return 0;
}
C Programming

constant
The qualifier const can be applied to the
declaration of any variable to specify that its
value will not be changed
const int decimal_base=10;

C Programming

Type Conversion
automatic conversions:
convert a ``narrower'' operand into a ``wider'' one
without losing information, such as converting an
integer i into floating point in an expression like f +
i.

assigning a wider data type to a lower one,


e.g. floating-point type to an integer, may
draw a warning, but they are not illegal.

C Programming

Type Conversion
If there are no unsigned operands, then
following conversion rules apply:
If either operand is long double, convert the other
to long double.
Otherwise, if either operand is double, convert the
other to double.
Otherwise, if either operand is float, convert the
other to float.
Otherwise, if either operand is long, convert the
other to long.
Otherwise, convert char and short to int.

C Programming

Type Conversion
Conversion on assignment:
the value of the right side is converted to the type
of the left, which is the type of the result.

int i; char c; long l, short s; float f;


l=i; l=c;l=s; i = c; //up conversion;
c = i; i=l; i=f//down conversion; lose info

C Programming

Type Conversion
Forced Conversion:
(Type name) expression
int i; float f; int res= i+(int)f;

The cast operator has the same high


precedence as other unary operators

C Programming

Evaluation Order
Operands Evaluation:
C, like most languages, does not specify the order
in which the operands of an operator are
evaluated. (The exceptions are &&, ||, ?:, and `,'.)
For example, in a statement like x = f() + g();
f may be evaluated before g or vice versa; thus if
either f or g alters a variable on which the other
depends, x can depend on the order of
evaluation.
Intermediate results can be stored in temporary
variables to ensure a particular sequence.
f=f();g=g();x=f+g;
C Programming

Evaluation Order
Arguments evaluation:
Similarly, the order in which function arguments
are evaluated is not specified, so the Statement
printf("%d %d\n", ++n, power(2, n)); /* WRONG */
can produce different results with different
compilers, depending on whether n is
incremented before power is called.
Solution, of course, is to write ++n; printf("%d
%d\n", n, power(2, n));

C Programming

Evaluation Order
Be careful when using Function calls, nested
assignment statements, and increment and
decrement operators in an expression
Moral lesson: Dont write code that depends
on order of evaluation

C Programming

Precedence and Order of Evaluation

C Programming

Main()
int main(void);//OK
int main();//DONT USE
int main(int argc, char **argv); //OK
int main(int argc, char *argv[]); //OK

C Programming

Das könnte Ihnen auch gefallen