Você está na página 1de 68

Getting Started in C

History
Dennis Ritchie of Bell Labs created C in 1972.
It was developed in AT & Ts Bell Laboratories.
The concept of C derives its origin from a primitive form
of C which was called Basic Combined Programming
Languages (BCPL) developed by Ken Thompson of Bell
Laboratories which he referred to as B.
The important point is that C was created as a tool for
working programmers, so its chief goal is to be a useful
language.
History of C
Language Year Founder
ALGOL 1960
International Group
BCPL 1967
Martin Richards
B 1970
Ken Thompson
C 1972
Dennis Ritchie
K & RC 1978
Kernighan and Ritchie
ANSI C 1989
ANSI Committee
ANSI/ISO C 1990
ISO Committee
Why C?
C is a powerful, concise programming language.
Why C? (cont.)
Design Features
Its design makes it natural for users to use top-down planning,
structured programming, and modular design. The result is a more
reliable, understandable program.
Efficiency
C is an efficient language. C programs tend to be compact
and to run quickly.
Portability
C is a portable language. That means that C programs written
on one system can be run on other systems with little or no
modification.
Why C? (cont.)
Power and Flexibility
C is powerful and flexible (two favorite words in computer
literature). For example, most of the powerful, flexible UNIX
operating system is written in C.
Programmer Oriented
C is oriented to fulfill the needs of programmers. It gives you
access to hardware, and it enables you to manipulate individual
bits in memory.
Features of C language
C is a general purpose, structured programming
languages.
C is a powerful, efficient, compact and flexible.
C is highly portable.
C has the ability to extend itself.
C is well suited for writing System Software as well as
Application software.
Features of C language (cont.)
C is a middle level language.
C language allows reference to a memory allocation
with the help of pointers.
C language allows dynamic memory allocation.
C is widely available, commercial C compiler are
available on most PCs.
Features of C language (cont.)
C programs are fast and efficient.
C has got rich set of operators.
C can be applied in systems programming areas like
Compliers, Interpreters and Assemblers etc.
Where is C used?
Lucas
Films
Computer
Languages
Pc
Applications
Star
Wars
Robot
factories
embedded
systems
Computer
games
Unix
Operating
Systems
C
Middle-Level Computer Languages and
Compilers
C is a Middle level computer language.
C is a compiled language. C compilers and linkers are
programs that convert C language source code into
executable code.
The compiler is a program that translates the high-level
language program into the detailed set of machine
language instructions the computer requires.
Summary
C is a general-purpose programming language.
C forms the basis for many advanced, highly powerful
and effective programming languages.
C is a middle level language that has the advantages of
readability, maintainability, and portability.
C is a very efficient language that allows you to get
control of computer hardware and peripherals.
Summary (Cont.)
C is a small language that you can learn easily in a
relatively short time.
Programs written in C can be reused.
Programs written in C must be compiled and translated
into machine-readable code before the computer can
execute them.
C provides many programming languages, such as Perl,
C++, and Java, with basic concepts and useful features.
Introducing C
Using C: Seven Steps
The seven steps of programming
1
2
3
4
5
6
7
Define the program objectives.
Design the program.
Write the code.
Compile.
Run the program.
Test and debug the program.
Maintain and Modify
the program.
C Prompt screen Elements
Menu bar
Insertion point
Error mess.
Status bar
File name
A Simple C Program :
#include<stdio.h>
main()
{
printf( Welcome to C world);
}
Preprocessor
instructions
Header file
First function or function name
Beginning of the body of the function
A print statement
End of the body of the function
{
}
( )
[ ]
Open brace & close brace
Parentheses
Brackets
/* Sample program in C */
#include<stdio.h>
main()
{
int a;
A=10;
printf( The value of a is:,a);
}
Declaration statement
Assignment statement
Function statement
Variable Assignment & Declaration
/* Sample program in C */
A comment (/*,*/)
The symbols /* and */ enclose comments, remarks that
help clarify a program. They are intended for the
reader only and are ignored by the compiler.
For example,
/* this is the addition statement */
/* A simple program*/
/* variable declaring */
// Here is a comment confined to one line.
// this is main function.
Variables
Declaring the variable:
All variables in a C program must be declared before
they can be used. The general form of a variable
definition is:
type (name)
So, for example to declare a variable a", of data
type "int" so that it may store a value in the range -
32767 to 32767, you use the statement;
int a;
Data Types
Different types of data is called Data Types. C has a
variety of data types,
Some data are letters or, more generally,
characters. Some data are numbers. The computer
needs a way to identify and use these different kinds.
C does this by recognizing several fundamental data
types.
auto double int struct
break else long switch
case enum register typeof
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Keywords in C
!
#
%
^
&
*
(
)
-
_
+
=
~
[
]
\
|
;
:

{
}
,
.
<
>
/
?
Character sets in C
Execution character set
Character Escape Sequence
Bell (Alert) \a
Backspace \b
Horizontal Tab \t
Vertical Tab \v
New line \n
Form feed \f
Quotation Mark \
Question Mark \?
Back slash \\
Null \0
Types of Operators
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Increment and Decrement Operators
Conditional Operators
Bitwise Operators
Special Operators
Arithmetic Operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division
Relational Operators
Operator Meaning
< is less than
< = is less than or equal to
> is greater than
> = is greater than or equal to
= = is equal to
! = is not equal to
Logical Operators
Operator Meaning
& & Logical AND
| | Logical OR
! Logical NOT
Assignment Operators
Compound Assignment
Ex. X + = Y, X * = Y
Nested or Multiple Assignments
Ex. I=j=k=w;
Increment and Decrement Operators (Unary Operators)
Operator Meaning
+ + x Pre increment
- - x Pre decrement
x + + Post increment
x - - Post decrement
Conditional Operators (or) Ternary Operators
Condition? exp1:exp2;
Syntax:
Bitwise Operators
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
< < Shift left
> > Shift right
~ Ones complement
The Special Operators
Operator Meaning
, Comma Operators
size of size of operators
& * Pointer operators
- - > Member selection op.
Scanf function
Scanf(%d, &weight);
To provide keyboard input to the program, use the
scanf() function. The %d instructs scanf() to read a
integer-point number from the keyboard, and the &
weight tells scanf() to assign the input value to the
variable named weight. The scanf() function uses the &
notation to indicate where it can find the weight
variable.
The scanf() function reads data from the keyboard
and delivers that data to the program, and printf()
reads data from a program and delivers that data to
your screen.
Scanf function
Main()
{

scanf(....);

printf(...);

}
Are you
Control string
Format code Meaning
%c Single Character
%d Decimal integer up to 32768 to +32767
%s Strings
%f Float Values
%ld Long integer up to 65536 to +65535
%u Unsigned decimal
%o Octal Number
%x Hexadecimal number
%e Floating point value
%h Short integer
Scanf() function (contd.)
Rules for writing scanf() function:
The control string must be preceded with (%) sign and
must be within quotations.
If there is a number of input data items, that items
must be separated by commas and must be preceded
with (&) sign except for string input.
The control string and the variables going to input
should match with each other.
It must have termination with semicolon.
Control Structures
If
Else if
for
While
Do-while
If statement
Syntax:
If (condition is true)
{
True statements;
}
Condition
True Statements
False
True
If.Else statement
Syntax:
If (condition)
{
True statements;
}
Else
{
False statements;
}
Condition
False Statements
False True
True Statements
Array
Array Declaration
Array Initialization
Single dimensional array
Multi dimensional array
Array
Array is a collection of same data elements stored in the
consecutive memory location that is a single variable
holding multiple data. It also defined as a set of
homogeneous data items. In other words, without
arrays a variable cannot store more than one value.
Properties of Array:
The types of an array is the data type of its elements.
The location of an array is the location of its first
element.
The length of an array is the number of data elements
in the array.
Array (Cont.)
Array Declaration:
An array declaration tells the compiler how many
elements the array contains and what the type is for
these elements.
float days[365]; /* array of 365 floats */
char code[12]; /* array of 12 chars */
int states[50]; /* array of 50 ints */
Array (Cont.)
Array Initialization:
You can initialize the array at the beginning of a program.
int powers[8] = {1,2,4,6,8,16,32,64} ;
int powers[8] = {1 2 4 6 8 16 32 64} ;
int powers[] = {1,2,4,6} ;
You can initialize an array by using a comma-separated
list of values enclosed in braces. You can use spaces
between the values and the commas, if you want.
Functions
Declaring a Function
Calling a Function
Variables
Passing Argument to a Function
Passing Array to Function
Call by Value and Call by reference
Functions (Cont.)
What is Functions?
A function is a self-contained unit of program code
designed to accomplish a particular task. Some
functions cause action to take place. For example,
printf() causes data to be printed on your screen.
Why should you use functions?
They save you from repetitious programming. If you
have to do a certain task several times in a program,
you need to write an appropriate function only once.
The program can then use that function wherever
needed, or you can use the same function in different
programs.
Functions (Cont.)
What do you need to know about functions?
You need to know how to define them properly,
how to call them up for use, and how to set up
communication between functions.
Note:
A function prototype that tells the compiler what
sort of function add() is, a function call that causes the
function to be executed, and a function definition that
specifies exactly what the function does.
Functions (Cont.)
Declaring a Function:
The declaration process is a two-step procedure.
Function and argument declaration
Implementation or the body of the function.
Pointers
Content of Pointers
Introduction to Pointer
Pointers and Arrays
Array of Pointers
Pointers with multidimensional Arrays
Pointer to Pointers
Pointers to Strings
Pointers to functions
Pointers to Data Structures
Introduction to Pointers
What is Pointers?
Characteristic of Pointers
Pointer Declaration
Initialization of Pointers
Pointers Manipulation
Pointer Arithmetic
Pointer Comparison
Pointers Operations
What is Pointer?
Simply stated, A Pointer is an address. Pointer is
nothing but a variable that contains the address of
another variables. Consider an example,
int intvar = 10;
Here, intvar is the name of a variable that stores the
value 10, and is stored in memory in the address, say 108.
108 the address of the variable
the variable intvar
10
Now consider another variable, ptr_intvar, which
holds the address of the variable intvar. This ptr_intvar
is said to be a pointer points to intvar.
108
ptr_intvar intvar
MEMORY AIDS
Think of & as an address.
Think of * as a star referring to stored.
108 108
Characteristic of Pointers
A pointer can hold the address of any valid data object,
including an array, a singular variable, a structure, and
a union.
A pointer can hold the address of a function.
A pointer cannot hold the address of a constant, with
one possible exception: A string constant has an
address, which can be stored in a pointer variable
indirectly (usually as the result of being passed as a
function call parameter).
Pointer Declaration
int *ptr_intvar;
Here, ptr_intvar is a pointer pointing to a
variable of type int. The unary operator * makes all
the difference between an ordinary variable and a
pointer type variable. This operator, also called the
indirection or dereferencing operator.
Initialization of Pointers
Ptr_intvar = &intvar;
The unary operator &, also called the address operator,
when applied to a variable, refers to the address of
that variable.
Int x=10, y=20, z[5];
Int *good; /* good is a pointer to int*/
Good = &x; /* good now points to x i.e.,
contains the address of x */
Pointers Manipulation
Complicated manipulation of pointers is possible through
the use of the address and the differencing operators
and also by combining them with relational operators
+ and -.
1. Int x=1, y=2;
2. Int *xptr, *yptr;
3. xptr=&x;
4. yptr=&y;
Pointer Arithmetic
Addition:
Addition of a number to a
pointer.
For example,
int i=4, *j,*k;
j=&I;
j=j+1;
j=j+9;
k=j+3;
Subtraction:
Subtraction of a number
from a pointer.
For example,
int i=4, *j,*k;
j=&I;
j=j-2;
j=j-5;
k=j-6;
Pointer Comparison
The comparison between pointer can be done provided
both the variables point the object of same data type.
For example,
#include<stdio.h>
main()
{
static int sub[]={10,20,30,40,50,60};
int *a, *b;
a=&sub[4];
b=(sub+4);
if (a==b)
printf(pointers point to the same location.);
else
printf(They do not point);
}
Pointers Operations
Six basic operations:
Assignment
Value finding
Taking a pointer address
Incrementing a pointer
Decrementing a pointer
Differencing
Assignment:
You can assign an address to a pointer. You do this
by using the address operator (&).
Value Finding:
The * operator gives the value stored in the
pointed-to location.
Taking a pointer address:
Like all variables, pointer variables have an address
and a value. The & operator tells you where the
pointer itself is stored.
Incrementing a pointer:
You can do this by regular addition or by using the
increment operator(+). Incrementing a pointer to
an array element makes it move to the next
element of an array.
Decrementing a pointer:
you also can decrement a pointer. You can do this
by regular addition or by using the decrement
operator(-).
Differencing
You can find the difference between two pointers.
Normally, you do this for two pointers to elements
that are in the same array to find out how far apart
the elements are. The result is in the same units as
the type size.
Dereferencing an Uninitialized Pointer
Note: There is one rule you should burn into your
memory. Do not dereference an uninitialized
pointer. For example, consider the following:
int pt; // an uninitialized pointer
*pt = 5; // a terrible error
Pointers and Arrays
Pointers and Arrays have always been closely related to
each other, so closely that any operation that could be
performed by array subscripting can be achieved by
using pointers.
#include<stdio.h>
Main()
{
Static char arr[15]=RAJ SOFTWARE;
Char *a=RAJ SOFTWARE;
Printf(%s\n,arr);
Printf(%s,a);
}
Array of Pointers
An array of pointers means a collection of addresses.
For example, a telephone directory which stores many
telephone numbers sequentially and whenever needed
any address can be retrieved. The addresses present in
the array of pointers can contain addresses of isolated
variables or address of the array elements.
#include<stdio.h>
Main()
{
int *sub[4];
int a=11, b=12, c=13, d=14, e;
sub[0]=&a;
sub[1]=&b;
sub[2]=&c;
sub[3]=&d;
for (e=0;e<3;e++)
printf(%d,*(sub[e]));
}
Pointers with Multidimensional Array
#include<stdio.h>
Main()
{
static int a[3][3]={
1,2,3,
4,5,6,
7,8,9
};
static int
*ptr[3]={a[0],a[1],a[2]};
int **ptr1=ptr;
int I;
printf(\n);
for(i=0;i<=2;i++)
printf(%d,*ptr[i]);
printf(\n);
for(i=0;i<=2;i++)
printf(%d,*a[i]);
printf(\n);
for(i=0;i<=2;i++)
{
printf(%d,**ptr1);
ptr1++;
}
}
Output:
147
147
147
Consider the following example,
Pointer to Pointers
A pointer variable has to store the address of the another
pointer variable (this is possible only in pointers). And
declaration pattern slightly altered. If the pointer
variable has to store the address of another pointer
variable that variable will have two* i.e.(**)followed by
the variable.
Int a;
Int *b;
Int **c;
Pointers to Strings
Consider the following example and understand the concept,
#include<stdio.h>
Main()
{
char name[]=Klinsman;
int I;
i=0;
While(name[i])
{
printf(\n%c%c%c%c,name[i],*(name+1),*(i+name),i[name]);
i++;
}
}
Array of Pointers to Strings
#include<stdio.h>
Main()
{
Char *names[]={
akshay,
parag,
raman,
srinivas,
gopal,
rajesh,
};
Char *temp;
Printf(\nOriginal:%s%s,names[2
], names[3]);
Temp=names[2];
Names[2]=names[3];
Names[3]=temp;
Printf(\nNew:%s%s,names[2],
names[3]);
}
Output:
Original:raman srinivas
New:srinivas raman
Pointers to Functions
Pointers to functions are interesting when you pass them to other
functions. One of the most important uses of pointers (and perhaps
the easiest
to understand) lies in the implementation of function parameters.
#include<stdio.h>
Main()
{
int *a;
Int *func();
A=func();
printf=(value of A is,a);
}
Int *func()
{
Int x=13;
Return(&x);
}

Você também pode gostar