Você está na página 1de 34

Programming

The act of a programmer writing code or instructions (program) in a programming language that
instructs a computer or other electronic device how to operate or function.
The process of designing, writing, testing, debugging / troubleshooting, and maintaining the source
code of computer programs, where Code is Computer instructions written in a programming
language.

Low-level language
Programming language that is more arcane and difficult to understand. Some good examples of low-
level languages are assembly and machine languages.

High-level language
A type of advanced computer programming language that isn't limited by the type of computer or
for one specific job and is more easily understood. Today, there are dozens of high-level languages;
some commonly used high-level languages are BASIC, C, FORTAN and Pascal.

Machine language
Sometimes referred to as machine code or object code, machine language is a collection of binary digits
or bits that the computer reads and interprets. Machine language is the only language a computer is
capable of understanding

Assembly language

Sometimes referred to as assembly or ASL.


An assembly language is the low-level programming language designed for a specific processor.
Assembly language uses structured commands as substitutions for numbers allowing humans to
read the code more easily than looking at binary.

C language is a middle level computer language.

Overview of Compilers and Interpreters


A program can be written in assembly language as well as high level language. The written program
is called a source program. The source program is to be converted to machine language, which is
called an object program. Either an Interpreter or Compiler will do this activity.

Interpreters
An Interpreter reads only one line of a source program at a time and converts it into object codes.
If an error occurs, it will instantly be indicated.
The disadvantage of interpreters is that it consumes more time for converting a source program to
an object program.

Compilers
A compiler reads the entire program and converts it to object code. It provides errors not of one
line but of the entire program. Only error free programs are executed. It consumes little time for
converting a source program to object program. Compilers are preferred when the program length
of an application is large.

Compile
The process of creating an executable program from code written in a compiled programming
language that allows the computer to run the program without the need of the programming
software used to create it. es.
When a program is compiled it is often compiled for a specific platform such as an IBM platform,
which would work with any IBM compatible computers but not other platforms such as the Apple
Macintosh platform. Below are some examples of compiled programming language:
C, C++, C#, D, Pascal

The Edit-Compile-Link-Execute Process


Developing a program in a compiled language such as C requires at least four steps:
1. editing (or writing) the program
2. compiling it
3. linking it
4. executing it

Structure of a C program
Every C program contains a number of several building blocks known as functions. Each functions
performs a task independently. A function is a subroutine that may consist of one or more
statements. A C program is comprised of the following sections:

preprocessor directives
global declarations
main ()
{
Local variables to function main;
Statements associated with function main;
}

function 1()
{
local variables to function 1;
Statements associated with function 2;
}

function 2()
{
local variables to function 2;
Statements associated with function 2;
}
Basic C Program

Question: Comment on the following code:

#include <stdio.h> /* This is a preprocessor directive */


int main (void) /* This identifies the function main () */
{ /* This marks the beginning of main () */
printf ("Hello World!"); /* This line displays a quotation */
getchar();
return 0; /* This returns control to the operating system */
} /* This marks the end of main () */

Preprocessing Directives

The symbol # indicates this is a preprocessing directive, which is an instruction to your compiler to do
something before compiling the source code.
The compiler handles these directives during an initial preprocessing phase before the compilation
process starts.

#include <stdio.h>: The compiler is instructed to include the contents of a header file called stdio.h.
A header file is a file that contains the declaration of functions and data constants, and they specify
information that the compiler uses to integrate any predefined functions or other global objects
with a program.
Because youre using the printf() function from the standard library, you have to include the stdio.h
header file.
Note the use of the angle brackets (< and >) around the header's name. These indicate that the
header file is to be looked for on the system disk which stores the rest of the C program application.
Some text books will show the above statement as follows:
#include "stdio.h"
The double quotes indicate that the current working directory should be searched for the required
header file. This will be true when you write your own header files but the standard header files
should always have the angle brackets around them.

Main Function
A function is a named block of code between braces that carries out some specific set of operations.
Every C program consists of one or more functions, and every C program must contain a function
called main ()a program will always start execution from the beginning of this function.
Program execution starts with the opening brace { and ends with the closing brace }. The curly
Brackets mark the start and end of the list of instructions that make up the program.

int main(void) /* This identifies the function main()-It is the function header */
/* Function body enclosed within the braces*/
return 0; /* This returns control to the operating system */
You return a zero value from main() to indicate that the program terminated normally; a nonzero
value would indicate an abnormal return, which means, in other words, things were not as they
should be when the program ended.

The parentheses that immediately follow the name of the function, main, enclose a definition of
what information is to be transferred to main() when it starts executing. In this example, however,
you can see that theres the word void between the parentheses, and this signifies that no data can
be transferred to main().

A function will stop execution when a return statement in the body of the function is reached, and
control will then transfer to the calling function (or the operating system in the case of the function
main().

Declaration part
The declaration part declares the entire variables that are used in the executable part.
Local variables are variables that are used within the current program unit (or function).
The initializations of variables are also done in this section.
Initialization means providing an initial value to the variables.

Comments
Comments are statements that help programmers understand the flow of programs. Comments are
useful for documentation. /* comments are statements placed between delimiters */
/* the compiler does not execute comments. */
// single line comments

Syntax
a set of rules that are associated with the language or command.
When referring to an error, a syntax error is an error that is encountered when the programmer or
individual who wrote the code has not followed the rules of the language, causing the program to
fail.

Keywords
In C, a keyword is a word with special significance, so you shouldnt use keywords for any other
purposes in your program. For this reason, keywords are also referred to as reserved words.
Auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for,
goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef
union, unsigned, void, volatile
while

Arguments
Items enclosed between the parentheses following a function name, as with the printf() function in the
previous statement, are called arguments, which specify data that is to be passed to the function.

Control Characters
Example: If you want to display a double quote character, you can use \".

#include <stdio.h>
int main(void)
{
printf("\n\"It is a wise father that knows his own child.\" Shakespeare");
return 0;
}

Escape Sequence Description


\n : a newline character
\r : a carriage return
\b : a backspace
\f : a form-feed character
\t : a horizontal tab
\v : Represents a vertical tab
\a : Inserts a bell (alert) character
\? : Inserts a question mark (?)
\" : Inserts a double quote (")
\' : Inserts a single quote (')
\\ : Inserts a backslash (\)

Functions in C

A function will have a specific interface to the outside world in terms of how information is transferred
to it and how results generated by the function are transmitted back from it.

Advantages:

It allows each function to be written and tested separately. This greatly simplifies the process of
getting the total program to work.
Several separate functions are easier to handle and understand than one huge function.
Libraries are just sets of functions that people tend to use all the time. Because theyve been
prewritten and pretested, you can use them without worrying about their code details.
You can accumulate your own libraries of functions that are applicable to the sort of programs that
youre interested in. e.g. If you find yourself writing a particular function frequently.
In the development of large programs, development can be undertaken by teams of programmers,
with each team working with a defined subgroup of the functions that make up the whole program.

The C Character Set


Characters in C are classified in the following Categories:
1. Letters
2. Digits
3. White spaces
4. Special characters
Letters
Capital A to Z
Small a to z

Digits
All decimal digits 0 to 9

space . , : ; ' $ # % & ! _ {} [] () < > |+ - / * =

Delimiters
Are special kind of symbols:
: Colon Useful for label
; Semi colon Terminates statements
() Parenthesis used in expressions and
functions
[] Square brackets for array
declaration
{} Curly Brace Scope of statement
# Hash Preprocessor Directive
, Comma Variable separator
Variables

What Is a Variable?

A variable is just a named area of storage that can hold a single value (numeric or character).
A variable is a specific piece of memory in your computer that consists of one or more contiguous
bytes.
You create variables to store values in.
Is a data name used for storing a data value. or
Is defined as a location in the computer memory which stores a data type according to the
declaration.
Also named an Identifier.
A variable is a data object that may change in value. Variables are used in C to store data values
during the execution of a program.

Every variable has a name, and you can use that name to refer to that place in memory to retrieve what
it contains or store a new data value there.
A variable can be assigned different values at different times during the execution of a program.

There are five basic data types:


int: integer, whole Number.
Range: -32,768 to 32,767
float: floating point value, I.e. No with fractional part.
Range: 3.4e -38 to 3.4e +38
double: a double-precision floating point No. (No with a larger fractional part)
Range: 1.7e -308 to 1.7e +308
Char: a single character enclosed within a pair of single qoute marks. E.g. a, 8, , &
Range: -128 to 127
void: valueless special purpose type.

Identifiers
Are names of variables, functions, and arrays.
They are user-defined names, consisting of sequences of letters and digits, with the letter as the first
character.
Constants: are identifiers whose value does not change during program execution.

Declaring Constants
By adding the keyword const before the declaration. E.g. const int m=10;
The compiler protects the value of m from modification. The user cannot assign any value to m.
#define N 10
#define a 15
Where N and a are user-defined identifiers.

Declaring a variable tells the compiler the type and the name of the variable.
Syntax for Variable Declaration:
Data_Type Variable_Name;
int mark1;
float sum, ave;
double answer;
char yr_initial;

Rules for Variable Formulation


1. No variable must be the same as one of the keywords.
2. Identifiers or variable names must start with a letter or the underscore, without spaces.
3. The variable name cant begin with a digit.
4. Variable names can be alphanumeric, i.e. A variable name cant include any other characters besides
letters, underscores, and digits.
5. Variable names are case sensitive such that A and a are viewed differently in C.
6. A variable name can be 8 characters excluding the extension, however the ANSI standard recognizes
the maximum length of a variable up to 31 characters long.
7. You must also declare the variable before you use it.

Variables starting with one or two underscore characters are often used in the header files, so it is not
advisable to use the underscore as the first letter when naming your variables;

Initializing Variables
Syntax: variable_name=constant;
Or data_type Variable_name=constant;

Simple Example

/* Program 2.2 Using a variable */


#include <stdio.h>
int main (void)
{
int salary; /* Declare a variable called salary */
salary = 10000; /* A simple arithmetic assignment statement */
printf("My salary is %d.", salary);
return 0;
}

printf ("My salary is %d.", salary);


There are now two arguments inside the parentheses, separated by a comma.
An argument is a value thats passed to a function. In this program statement, the two arguments to the
printf () function are as follows:
Argument 1 is a control string, so called because it controls how the output specified by the following
argument (or arguments) is to be presented.
This is the character string between the double quotes. It is also referred to as a format string because it
specifies the format of the data that is output.
Argument 2 is the name of the variable salary. How the value of this variable will be displayed is
determined by the first argumentthe control string.
Basic Arithmetic Operations

In C, an arithmetic statement is of the following form:


Variable_Name = Arithmetic_Expression;

The = symbol defines an action. It doesnt specify that the two sides are equal, as it does in
mathematics. It specifies that the value resulting from the expression on the right is to be stored in
the variable on the left.
Any expression that results in a numeric value is described as an arithmetic expression.
Evaluating these expressions produces a single numeric value.

1. Table below shows the operators:

1. Binary Operators
Operator Action
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus(remainder operator-calculates the remainder after dividing the
value of the expression on the left of the operator by the value of the expression on the right.)

2. Unary Operators
- Minus
++ Increment
-- Decrement
& Address Operator
Size of Gives the size of a variable
Minus (-): Unary minus is used to indicate or change the algebraic sign of a value.

Increment and Decrement Operators


++ Increases a value by One
-- Decreases a value by One
E.g. num++; num--;
Equivalent to: num = num+1; num = num-1;

Increment and Decrement Operators


Both these operators may either follow or precede the operand (prefixed).
E.g. ++x; or x++;
If ++ or - - are used as a suffix to the variables name then the post increased/ decreased operations
take place.
E.g. x=20; y=10; then
z=x*y++; results in 200.

If ++ or - - are used as a prefix to the variables name then the pre increased/ decrement operations
take place.
E.g. x=20; y=10; then
z=x*++y; results in 220.

Arithmetic Ordering:
a=10.0 + 2.0 * 5.0 - 6.0 / 2.0
a=10.0 + (2.0 * 5.0) - (6.0 / 2.0)
a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0

Sizeof()
The sizeof() operator gives the bytes occupied by a variable. The number of bytes occupied
varies from variable to variable depending on its data types.
E.g. int x=2; float y=2;
printf(%d : %d,sizeof(x), sizeof(y));
Ans: 2 : 4

& Address of
The & address of operator prints address of the variable in the memory.
E.g. int x=2; float y=2;
printf(%d : %d,sizeof(x), sizeof(y));
printf(%u : %u, &x, &y);
Ans: 2:4

4066 : 25096

Relational Operators
> greater than
>= greater than or equal to
< less than
<= less than or equal to
== equal to
!= not equal to

These Operators are used to distinguish between two values depending on their relations.If the
relation is true then it returns a value 1 otherwise 0 for false relation

Logical Operators
&& AND T AND T = T
T AND F = F
|| OR T OR T = T and
T OR F = T,
F OR F = F
! NOT

Example: The modulus Operator


#include <stdio.h>
int main(void)
{
int cookies = 45; /* Number of cookies in the jar */
int children = 7; /* Number of children */
int cookies_per_child = 0; /* Number of cookies per child */
int cookies_left_over = 0; /* Number of cookies left over */

/* Calculate how many cookies each child gets when they are divided up */
cookies_per_child = cookies/children; /* Number of cookies per child */
printf("You have %d children and %d cookies", children, cookies);
printf("\nGive each child %d cookies.", cookies_per_child);

/* Calculate how many cookies are left over */


cookies_left_over = cookies%children;
printf("\nThere are %d cookies left over.\n", cookies_left_over);
return 0;
}
Input and Output (I/O)

A C program uses standard Input and Output to read its input from the keyboard and to write its
output to the screen.
Such input and output consists of streams which are simply sequences of characters that either
come from or go to an input or output device.

The printf() function

One invaluable function provided by the standard input/output library is called printf or `print-
formatted'.
The simplest way to use it is to print out a literal string:
printf ("..some string...");

To print out the contents of variables.


These can be inserted into a text string by using a `control sequence' inside the quotes and listing
the variables after the string which get inserted into the string in place of the control sequence. To
print out an integer, the control sequence %d is used:
printf ("Integer = %d",someinteger);
The variable someinteger is printed instead of %d.

The data type for an input stream is stdi, while that of an output stream is stdo.
These are all supplied by the library called stdio.
A C program gains access to this library and other libraries by including them as header files.

printf() and scanf() Functions

These functions use the standard input and output to read input from the keyboard and to write
output to the screen.

1. Input functions, called scanf ()


2. Output functions, called printf ()
printf("The value stored in a is %d",a );
The printf (and scanf) functions do differ from the sort of functions that you will create for yourself
in that they can take a variable number of parameters. In the case of printf the first parameter is
always a string (c.f. "Hello World") but after that you can include as many parameters of any type
that you want to. That is, the printf function is usually of the form

Format Specifiers

FS Type display
%c char single character
%d [%i] int signed integer
%e[%E] float/double exponential formt
%f float/double
%s array of characters sequence
(a string)
Scanf()

scanf(control string,variable,variable,...)
scanf("%d %d",&i,&j);
In this case the control string specifies how strings of characters, usually typed on the
keyboard, should be converted into values and stored in the listed variables. However there
are a number of important differences as well as similarities between scanf() and printf().

write a program gets input from the user and adds the two numbers together and prints the result.

#include <stdio.h>
main()
{
int a,b,c;
printf("\nEnter the first number :");
scanf("%d",&a);
printf(\nEnter second number :");
scanf("%d",&b);
c=a+b;
printf("The answer is %d \n",c);
}
Control Loops

Compound statement

Any list of statements enclosed in curly brackets is treated as a single statement, a


compound statement. So to repeat a list of statements all you have to do is put them
inside a pair of curly brackets :

Conditions or Logical Expressions:


The condition can be any test of one value against another.
For example:
a>0
is true if a contains a value greater than zero;

A test for equality uses two equal-signs, as in a==0, while an assignment, as in a=0, uses
one.

If Statement

Lets you execute or skip an instruction depending on the value of the condition.
Another possibility is that you might want to select one of two possible statements
one to be obeyed when the condition is true and one to be obeyed when the condition
is false.

Syntax:
if( expression ) statement1;

or

if( expression ) statement1;


else statement2 ;

Example:
if (loop<3)
counter++;

if(x==y) x++;
else y++;

if(z>x) {z=5; x=3; }


else { z=3; x=5; }

Switch
Allows a single variable to be compared with several possible constants.
If the variable matches one of the constants, then an execution jump is made to that point.
A constant cannot appear more than once, and there can only be one default expression.

Syntax:
switch ( variable )
{
case const:
statements...;
default:
statements...;
}

Example:
switch(betty)
{
case 1: printf("betty=1\n");
case 2: printf("betty=2\n"); break;
case 3: printf("betty=3\n"); break;
default: printf("Not sure.\n");
}

Loop Control Statements


A loop is a block of statements which are repeatedly executed for a certain number of
times.
Steps in Loop
Loop Variable: is a variable used in the loop.
Initialization: Is the first step in which starting and final value is assigned to the loop
variable. Each time the updated value is checked by the loop itself.
Iteration:
Allows for repeated execution of the same block of statements until a specified
condition is encountered. Some of the loops include for loop, while loop and do..while.
A while loop is most suitable when a condition that terminates the loop can terminate
unexpectedly.

While

Provides an iterative loop.

Syntax: while (expression) statement...


Statement is executed repeatedly as long as expression is true. The test on expression
takes place before each execution of statement.
In the case of the while loop before the compound statement is carried out the
condition is checked, and if it is true the statement is obeyed one more time. If the
condition turns out to be false, the looping isn't obeyed and the program moves on to
the next statement.

Examples:

while(*pointer!='j') pointer++;
while(counter<5)
{
printf("counter=%i",counter);
counter++;
}

#include <stdio.h>
main()
{
while (1 == 1) printf("Hello World!\n");
}
dowhile

Most suited to a situation where it is required to execute the loop statements for at least
once.

Syntax:
do statement... while( expression );

Statement is executed repeatedly as long as expression is true.


The test on expression takes place after each execution of statement.
The loop will always execute the code within the loop at least once, since the condition
controlling the loop is tested at the bottom of the loop.

Examples:

do {
betty++;
printf("%i",betty);
} while (betty<100);

#include <stdio.h>
main()
{
do
{
printf("Hello World!\n");
}while (1 == 1);
}

For loop

Used when the condition limits of the loop are known in advance.

Syntax:

for( expression1 ; expression2 ; expression3 ) statement... ;


OR
for ( counter=start_value; counter <= finish_value; ++counter )
compound statement;

Expression1 is evaluated before the first iteration.


The test on expression2 occurs before each execution of statement.

Examples:
for(loop=0;loop<1000;loop++) printf("%i\n",loop);
Prints numbers 0 through 999.
for(x=3, y=5; x<100+y; x++, y--)
{
printf("%i\n",x);
some_function();
}
Prints numbers 3 through 53. some_function is called 51 times.

Break Statement

Can only appear in a switch body or a loop body.


It causes the execution of the current enclosing switch or loop body to terminate.

Example:
switch(henry)
{
case 1: print("Hi!\n");
break;
case 2: break;
}
If henry is equal to 2, nothing happens.

Example2:
for(loop=0;loop<50;loop++)
{
if(loop==10)
break;
printf("%i\n",loop);
}
Only numbers 0 through 9 are printed.

The continue statement

Can only appear in a loop body. It causes the rest of the statement body in the loop to
be skipped.

Example:
for(loop=0;loop<100;loop++)
{
if(loop==50)
continue;
printf("%i\n",loop);
}
The numbers 0 through 99 are printed except for 50.

Example2:
joe=0;
while(joe<1000) {
for(zip=0;zip<100;zip++) {
if(joe==500)
continue;
printf("%i\n",joe);
}
joe++; }
Each number from 0 to 999 is printed 100 times except for the number 500 which is not
printed at all.

Goto statement

The goto statement transfers program execution to some label within the program.
Example:
goto skip_point;
printf("This part was skipped.\n"); skip_point:
printf("Hi there!\n");
Only the text "Hi there!" is printed.

The return statement causes the current function to terminate. It can return a value to
the calling function. A return statement cannot appear in a function whose return type
is void. If the value returned has a type different from that of the function's return type,
then the value is converted.
Using the return statement without an expression creates an undefined result. Reaching
the } at the end of the function is the same as returning without an expression.

Example:

int alice(int x, int y)

{
if(x<y)
return(1);
else
return(0);
} return type
Functions

A function is a routine which performs some task whose implementation is independent


of the main program.
There are two types of Functions:
1. User Defined Functions: functions that are defined by the user according to his/her
requirement.
2. Standard Library Functions: Functions stored in C libraries which you call into your
program whenever you need them. Are pre-defined set of functions. User can only use
the functions but cant change or modify them.

Standard Library vs User defined Functions


UDF: Defined by the user
SLF: pre-defined set of functions
UDF: User can modify function
SLF: User can only use the functions but cant change or modify
UDF: User understands the internal working of the function
SLF: User does not understand the internal working of the function
UDF: User has full scope to implement his/her own ideas in the function

E.g. a UDF square which gives the result 81 when called.

int square(int a)
{ int sq;
sq=a*a;
return sq;
}
A function is a self contained block or a sub-program of one or more statements that
performs a special task when called.
When a program starts the main() function is executed first. main() calls another
function to share the work.
Every program in C has at least one function which is main().
Functions are used to make a program modular and to avoid repetition of code. Any
piece of code which is often used in a program is a likely candidate for being a function.
Procedures, also known as routines, subroutines, methods, or functions simply contain
a series of computational steps to be carried out (set of instructions). Any given
procedure might be called at any point during a program's execution, including by other
procedures or itself.

Syntax:

In C a function has the following structure :


<return type> function_name (arguments list)
{
local variables;
code performing the necessary action;
return expression;
}

Example:
#include <stdio.h>
void print_message(); //function declaration

void main ()
{
print_message (); // function call
printf ("Back in the main program\n");
} // end of main () function
void print_message() //function Definition
{
printf ("Inside print_message function\n");
}

Example2:

#include<stdio.h>
int sum(int num1, int num2);

main()
{ int x, y, z;
x=6; y=5; z=0;
z=sum(x,y);
printf(Ans is %d, z);
return 0;
}

int sum (int num1, int num2)


{ int sum; sum=0;
sum=num1+num2;
return sum;
}

Function prototype
In C the function prototype(function declaration) has to be declared before a function is
used. A function prototype is information to the C compiler about the return type of a
function and the parameter types that a function expects. Usually all function
prototypes are declared at the start of a program (before main() function).
Example:
int Min(int a, int b);

Function call
In the previous program, main() is the entry point of the program, once program
execution begins, the control is transferred to the print_message() function.
Inside the function it prints the statement on the terminal and the control returns to
the main routine.
After the function call the program execution will continue at the point where the
function call was executed.
One can call a function from anywhere within a program.
The best use of functions is to organize a program into distinct parts.
The function main() can only contain calls to the various functions. The actual work of
the program is performed in the functions following main().
The printf() and scanf() routines are functions too. But since these are part of the C
standard library, one has to just make a call to them.
Whenever we use a printf() routine, execution is transferred to the printf() function
which performs the required task, then control is returned back to the calling program.
If you do not want to return a value you must use the return type void, and the return
statement must not be present in the body of the called function.return type

Return Type
Note : If the return type of a function is omitted, then the C compiler assumes that the
function will return an integer. In case a function is returning an integer value, it is a
good programming practice to declare the return type instead of omitting it. This
improves the readability of a program.

When a function is declared the number of arguments passed to the function and their
names must also be indicated. The name chosen for an argument is called its formal
parameter name. Formal parameters must be declared inside a function before they
are used in the function body.
<return type> function_name (arguments list)

Automatic variables
One point to remember is that variables defined inside a function are known as
automatic variables since they are automatically created each time the function is
called and are destroyed once the function is executed.
Their values are local to the function, they can be accessed only inside the function in
which they are defined and not by other functions.

Example
#include <stdio.h>
int square(int n);
main()
{
int i; int result; i = 10; result = square(i);
printf ("Square of %d is %d\n", i, result);
}
int square(int n)
{
int temp; temp = n*n; return temp;
}

Returning a value
When functions return a value to the calling routine, a return() statement needs to be
used in the called function.
Also when the function is declared we must declare the return type.
In the above program the value returned by the function square is stored in the variable
result in the calling program.

Scope of Function variables


Variables defined inside a function are known as automatic variables. Their values are
local to the function, they can be accessed only inside the function in which they are
defined and not by other functions. Therefore they have Local Scope.

Global variables
Global variables are declared outside all functions. The value stored in global variables is
available to all functions within a program/application.
A global variable is visible anywhere within the program.
Another word for visibility is scope. Therefore global variables have global scope.

How long do variables Last?


By default, Local variables have automatic duration, they spring into existence when the
function is called and they (and their values) disappear when the function returns (ends
its task).
Global variables have static duration, they last for as long as the program does, and the
values stored in them persist.

Static variables
Static variables are declared by prefixing the keyword static to a variable declaration.
Unlike local variables these are not destroyed on return from a function, they continue
to exist and retain their value. These variables can be accessed upon re-entering a
function.

Call By Value and Reference


There are two ways in which we can pass arguments to a function.
1. Call by value
2. Call by reference

Call By Value

The value of actual arguments are passed to the formal arguments and the operation is
done on the formal arguments.
Any change made to the formal argument does not affect the actual arguments because
formal arguments are a copy/photocopy of actual arguments.
When a function is called by value, it does not affect the actual contents of the actual
arguments. Changes made to the formal arguments are local to the block of the called
function.

#include<stdio.h>
change(int a, int b);
main()
{
int x,y;
printf(\n Enter values of X&Y:);
scanf(%d %d, &x,&y);
change(x,y);
printf(\n In main() X=%d Y=%d, x,y);
return 0;
}

change(int a, int b)
{
int k;
k=a;
a=b;
b=k;
Printf(\n In change() X=%d Y=%d, a,b);
}

Call By Reference
Instead of passing values, addresses (reference) are passed.
Called function operates on addresses rather than values. Here the formal arguments
are pointers to the actual arguments.
Therefore formal arguments point to the actual argument (same memory location that
the actual arguments reference).
Hence changes made in the formal arguments are permanent.
#include<stdio.h>
change (int *a, int *b);
main ()
{
int x, y;
printf(\n Enter values of X&Y:);
scanf(%d %d, &x, &y);
change(&x, &y); //pass address of x and y
printf(\n In main() X=%d Y=%d, x,y);
return 0;
}
change(int *a, int *b)
{
int *k; *k=*a; *a=*b; *b=*k;
printf(\n In change() X=%d Y=%d, *a,*b);
}

Example 2:

#include<stdio.h>
other(int a, int *b);
main()
{
int a, b;
printf(\nAddress of A&B in main():%u %u,&a,&b);
other(a,&b); //pass copy of a, && address of b
return 0;
}

other(int a, int *b)


{
printf(\n Address of A&B in other():%u %u,&a,b);
}

Recursive functions

#include <stdio.h>
long int factorial(int n); // function prototype
main () {
int num;
printf("Enter an integer value : ");
scanf("%d", &num);
printf("factorial of %d is %ld\n", num, factorial(num)); } //end of main()
long int factorial(int n)
{
if (n &lt;= 1) return(1);
else return(n * factorial(n-1));
}
Function Pointers

Functions can also be represented with a pointer. A function pointer is defined in the same way
as a function prototype, but the function name is replaced by the pointer name prefixed with an
asterisk and encapsulated with parenthesis. Such as:
int (*fptr)(int, char);
fptr=some_function;
To call this function:
(*ftpr)(3,'A');

To call this function: (*ftpr)(3,'A'); This is equivalent to: some_function(3,'A');

You can create pointers to functions as well as to variables. Function pointers can be tricky,
however, and caution is advised in using them.
Function pointers allow you to pass functions as a parameters to another function. This enables
you to give the latter function a choice of functions to call. That is, you can plug in a new
function in place of an old one simply by passing a different parameter. This technique is
sometimes called indirection or vectoring.
To pass a pointer for one function to a second function, simply use the name of the first
function, as long as there is no variable with the same name. Do not include the first function's
parentheses or parameters when you pass its name.

For example, the following code passes a pointer for the function named fred_function to the
function barbara_function:
void fred(); barbara (fred); Notice that fred is declared with a regular function prototype before
barbara calls it. You must also declare barbara, of course:
void barbara (void (*function_ptr)() );
Notice the parentheses around function_ptr and the parentheses after it. As far as barbara is
concerned, any function passed to it is named (*function_ptr)(),

this is how fred is called in the example below:


#include <stdio.h> void fred();
void barbara ( void (*function_ptr)() );
int main();
int main() {
barbara (fred);
return 0;
}
void fred() {
printf("fred here!\n");
}
void barbara ( void (*function_ptr)() )
{
/* Call fred */
(*function_ptr)();
} The output from this example is simply fred here!.
The output from this program reads:
do_math here.
Addition = 15.

do_math here.
Subtraction = 35.

Arrays

Is a variable that can hold more than one value.

Declaration of arrays:

Like any other variable arrays must be declared before they are used. The general form
of declaration is:
type variable_name[size];

The type specifies the type of the elements that will be contained in the array, such as
int float or char and the size indicates the maximum number of elements that can be
stored inside the array for example:
float height[50];

Declares height to be an array containing 50 real elements. Any subscripts 0 to 49 are


valid. In C the array elements ,index or subscript begins with number zero. So height [0]
refers to the first element of the array. (For this reason, it is easier to think of it as
referring to element number zero, rather than as referring to the first element).

int grades [100]=95;


for(i=0;i < 100;++i);
sum = sum + grades [i];
Will sequence through the first 100 elements of the array grades (elements 0 to 99) and
will add the values of each grade into sum. When the for loop is finished, the variable
sum will then contain the total of first 100 values of the grades array (Assuming sum
were set to zero before the loop was entered)
The initialisation of simple variables in their declaration has already been covered. An
array can be initialised in a similar manner. In this case the initial values are given as a
list enclosed in curly brackets. For example initialising an array to hold the first few
prime numbers could be written as follows:
int primes[] = {1, 2, 3, 5, 7, 11, 13};
Note that the array has not been given a size, the compiler will make it large enough to
hold the number of elements in the list. In this case primes would be allocated space for
seven elements. If the array is given a size then this size must be greater than or equal
to the number of elements in the initialisation list. For example:
int primes[10] = {1, 2, 3, 5, 7};
would reserve space for a ten element array but would only initialise the first five
elements.
We can initialize the elements in the array in the same way as the ordinary variables
when they are declared. The general form of initialization off arrays is:
type array_name[size]={list of values};
The values in the list care separated by commas, for example the statement
int number[3]={0,0,0};

Will declare the array size as a array of size 3 and will assign zero to each element if the
number of values in the list is less than the number of elements, then only that many
elements are initialized. The remaining elements will be set to zero automatically.
In the declaration of an array the size may be omitted, in such cases the compiler
allocates enough space for all initialized elements. For example the statement

Strings

A string is a sequence of characters. Any sequence or set of characters defined within


double quotation symbols is a constant string.
In c it is required to do some meaningful operations on strings they are:
Reading string displaying strings.
Combining or concatenating strings.
Copying one string to another.
Extraction of a portion of a string.

Strings are stored in memory as ASCII codes of characters that make up the string
appended with \0(ASCII value of null). Normally each character is stored in one byte,
successive characters are stored in successive bytes.
The last character is the null character having ASCII value zero.

A string is an array of characters. Strings must have a \0 or null character after the last
character to show where the string ends. The null character is not included in the string.
There are 2 ways of using strings. The first is with a character array and the second is
with a string pointer.
A character array (array of characters) is declared in the same way as a normal array.
char ca[10];

You must set the value of each individual element of the array to the character you want
and you must make the last character a 0. Remember to use %s when printing the
string.
char ca[10];
ca[0] = 'H';
ca[1] = 'e';
ca[2] = 'l';
ca[3] = 'l';
ca[4] = 'o';
ca[5] = 0;
printf("%s",ca);

Initializing Strings
Charmonth1[] ={j,a,n,u,a,r,y};

String operations (string.h)

C language recognizes that string is a different class of array by letting us input and
output the array as a unit and are terminated by null character. C library supports a
large number of string handling functions that can be used to array out many o f the
string manipulations such as:

Length (number of characters in the string).


Concatentation (adding two are more strings)
Comparing two strings.
Substring (Extract substring from a given string)
Copy(copies one string over another)

strlen() function

This function counts and returns the number of characters in a string. The length does
not include a null character.

Syntax n=strlen(string);
Where n is integer variable. Which receives the value of length of the string.
Example
length=strlen(Hollywood);
The function will assign number of characters 9 in the string to a integer variable length.

strcat() function
when you combine two strings, you add the characters of one string to the end of other
string. This process is called concatenation. The strcat() function joins 2 strings together.
It takes the following form

strcat(string1,string2)
string1 & string2 are character arrays. When the function strcat is executed string2 is
appended to string1. the string at string2 remains unchanged.
Example
strcpy(string1,sri);
strcpy(string2,Bhagavan);
Printf(%s,strcat(string1,string2);
From the above program segment the value of string1 becomes sribhagavan. The string
at str2 remains unchanged as bhagawan.

strcmp function
In c you cannot directly compare the value of 2 strings in a condition like
if(string1==string2)
Most libraries however contain the strcmp() function, which returns a zero if 2 strings
are equal, or a non zero number if the strings are not the same. The syntax of strcmp() is
given below:
Strcmp(string1,string2)
String1 & string2 may be string variables or string constants. String1, & string2 may be
string variables or string constants some computers return a negative if the string1 is
alphabetically less than the second and a positive number if the string is greater than
the second.
Example:
strcmp(Newyork,Newyork) will return zero because 2 strings are equal.
strcmp(their,there) will return a 9 which is the numeric difference between ASCII i
and ASCII r.
strcmp(The, the) will return 32 which is the numeric difference between ASCII T &
ASCII t.

strcmpi() function
This function is same as strcmp() which compares 2 strings but not case sensitive.
Example
strcmpi(THE,the); will return 0.

strcpy() function
C does not allow you to assign the characters to a string directly as in the statement
name=Robert;
Instead use the strcpy(0 function found in most compilers the syntax of the function is
illustrated below.
strcpy(string1,string2);

strcpy() function assigns the contents of string2 to string1. string2 may be a character
array variable or a string constant.
strcpy(Name,Robert);
In the above example Robert is assigned to the string called Name.

strlwr () function
This function converts all characters in a string from uppercase to lowercase.
syntax
strlwr(string);
For example:
strlwr(EXFORSYS) converts to exforsys
strrev() function
This function reverses the characters in a string.
Syntax
strrev(string);
For ex strrev(program) reverses the characters in a string into margrop.

strupr() function
This function converts all characters in a string from lower case to uppercase.
Syntax
strupr(string);

For example strupr(exforsys) will convert the string to EXFORSYS.

String pointers
String pointers are declared as a pointer to a char.
char *sp;
When you assign a value to the string pointer it will automatically put the \0 in for you
unlike character arrays.
char *sp;
sp = "Hello";
printf("%s",sp);

You can read a string into only a character array using scanf () and not a string pointer. If
you want to read into a string pointer then you must make it point to a character array.
char ca[10],*sp;
scanf("%s",ca);
sp = ca;
scanf("%s",sp);

Multi dimensional Arrays:


Often there is a need to store and manipulate two dimensional data structure such as
matrices & tables. Here the array has two subscripts. One subscript denotes the row &
the other the column.
The declaration of two dimension arrays is as follows:
data_type array_name[row_size][column_size];
int m[10][20] ;
Here m is declared as a matrix having 10 rows( numbered from 0 to 9) and 20
columns(numbered 0 through 19). The first element of the matrix is m[0][0] and the last
row last column is m[9][19]
Physically array elements are stored in one continuous form in the memory.
The two-dimensional array is a collection of a number of one-dimensional arrays which are
placed one after the another

Two-dimensional Array
A two dimensional array can be thought of as a rectangular display of elements with
rows and columns. Eg. int x[3][3];
The first element of the matrix is x[0][0] and the last row last column is x[2][2].

Col1 Col2 Col3


Row1 x[0][0] x[0][1] x[0][2]
Row2 x[1][0] x[1][1] x[1][2]
Row3 x[2][0] x[2][1] x[2][2]

Elements of multi dimension arrays:


A 2 dimensional array marks [4][3] is shown below figure. The first element is given by
marks [0][0] contains 35.5 & second element is marks [0][1] and contains 40.5 and so
on.
marks [0][0] 35.5 Marks [0][1] 40.5
Marks [0][2]45.5 marks [1][0] 50.5
Marks [1][1] 55.5 Marks [1][2] 60.5
marks [2][0] Marks [2][1]
Marks [2][2]marks [3][0]
Marks [3][1] Marks [3][2]

Initialization of multidimensional arrays:


Like the one dimension arrays, 2 dimension arrays may be initialized by following their
declaration with a list of initial values enclosed in braces
Example:
int table[2][3]={0,0,01,1,1};
Initializes the elements of first row to zero and second row to 1. The initialization is
done row by row. The above statement can be equivalently written as :
int table[2][3]={{0,0,0},{1,1,1}}
Questions:
1. Write a program to read five values into an array and print them out in reverse order
(Use two independent for loops).
2. What is meant by an array?
3. How do you declare an array?
4. What do you mean by an index of an array?
5. how many elements are there in the following array : int arr[10]?
Why do you need to specify the size of an array?

Você também pode gostar