Você está na página 1de 57

C Programming SSIT

Contents
1. C Fundamentals
1.1. C Characterset
1.2. Identifiers and Keywords
1.3. Variables
1.4. Literals
1.5. Data types
1.6. Where Variables are Declared
1.7. Scope and Life time of Variables
2. Operators
2.1. Introduction to Operators
2.2. Assignment Operator
2.3. Arithmetic Operators
2.4. Relational Operators
2.5. Arithmetic Assignment Operators
2.6. Increment and Decrement Operators
2.7. Logical Operators
2.8. Bitwise Operators
2.9. Pointer Operators
2.10. Conditional Operator
2.11. Precedence and associativity
3. Console I/O
3.1. Introduction to Files and Streams
3.2. Reading data from source
3.3. Writing data to sink
3.4. Standard Streams(stdin,stdout,stdprn)
3.5. Unformatted and formatted I/O Functions
4. Statements
4.1. Introduction
4.2. Selection Statements
4.2.1. If .....Else
4.2.2. If ladder
4.2.3. switch...case
4.3. Iteration statements
4.3.1. while Loop
4.3.2. do....while Loop
4.3.3. for Loop
4.4. Jump Statements
4.4.1. return
4.4.2. break
4.4.3. continue
5. Functions
5.1. Introduction
5.2. Function Declaration
5.3. Function Definition
2
C Programming SSIT
5.4. Function Call statement
5.5. Function Arguments
5.5.1. Call By Value and Call By Reference
5.6. Command Line Arguments
5.7. Recursive Function
6. Arrays and Strings
6.1. Introduction to Array
6.2. One Dimensional Array
6.3. Accessing Elements in Array
6.4. Passing Single Dimensional Array to Function
6.5. Strings
6.6. Two Dimensional Array
7. Pointers
7.1. Introduction to Pointers
7.2. Pointer Variables
7.3. The Pointer Operators
7.4. Pointer Arithmetic
7.5. Pointer Comparisons
7.6. Pointers and Arrays
7.7. Arrays of Pointers
7.8. Multiple Indirection
7.9. Pointer to Function
7.10. Cs Dynamic Memory Allocation Function
8. Structures, Union, Enumeration and typedef
8.1. Structures
8.2. Constructing Structure Object
8.3. Accessing Structure member
8.4. Structure Initialization
8.5. Arrays of Structure
8.6. Passing Structure to Function
8.7. Structure Pointer
8.8. Unions
8.9. Enumerations
8.10. Typedef
9. File I/O

3
C Programming SSIT

Overview of C
C seems a strange name for a programming language 'C' is one of the most
popular modern computer programming languages. The C language is developed in
1972 by Dennis M.Ritchie at Bell Laboratories (AT and T Bell Labs). The C language is
designed on BCPL (Basic combined programming language). The popularity of the C
language is due to its many characteristics.

Since it was developed along with the UNIX operating system it is strongly
associated with UNIX. This operating system was also developed at BELL laboratories
was coded almost entirely in C.

C FUNDAMENTALS
C Character set

C Character set includes


A-Z uppercase Letters

a-z lowercase Letters

4
C Programming SSIT
0-9 digits

Special Characters

+-*/=%&# !?^@`~\|

<>()[]{} : ; . , (_) Blank

Identifiers and Keywords


Identifiers are used to identify programming elements like variables, functions,
arrays and other user defined things.

Rules to construct valid identifiers

We have to use certain characters of C-character set only.

They are including


Alphabets, Digits, One special character (_) underscore

The first character must not be a digit.

The length of these identifiers can vary from one to several characters.

Identifier name should not be same as a C keyword.

Keywords

In All programming languages some words are reserved for some specific purpose. They are
playing key role to construct statements, hence they are called Keywords .In C89 ,32 words
are reserved and in C 99 ,37 words are reserved. They are

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

Variables

While solving a problem we may need to remember some data values temporarily. Such
values are placed in the named locations in the memory. These named locations in the memory are
called variables.

5
C Programming SSIT
To create a location in the memory, system needs three specifications

1. Name of the location.

2. Type of value the location has to hold.

3. Set of operations that are going to be performed against the location.

Variable Declaration Statement

You create location or locations in the memory with these specifications, we can specify to
the system through variable declaration statement. Its syntax is:

type variablelist;

To declare single variable:

type variablename;

Variable name should be valid identifier.Remaing two specifications we are specifying through data
type.

Literals

Constants are also called literals or values. C' supports 4 types literals. They are

1. Character constant

Any single valid character is enclosed in between single quotation marks is called
character constant.

Ex: A, 0, 9, $, %'

2. String constant

Some thing which is placed in between double quotation marks is called string constant.

Ex: "ssit" "234523" "C programming"

3. Numeric constant

Any particular sequence of 0 to 9 digits without any special character except a decimal point is
called numeric literal.

Ex. 125 - Integer constant


6
C Programming SSIT
135.25 Real constant

Data Types

Data type defines two things

1. Type of value location has to hold,

2. Set of operations may be performed against the location.

C supports 5 foundational data types

Character Integer Floating point Double floating point Value less

They are declared using the following keywords.

char int float double void

char
If we want to hold a character literal temporarily, we need a variable of type char . To
declare a variable of char type, use keyword char

Ex. char ch;

Here type is char and variable name is ch.

char variable needs 1 byte memory .

int
To store an integer constant we need a variable of type int

Ex: int n;

int variable takes two bytes memory in DOS operating system, four bytes in windows or unix.

float
To store real constant with less precision, we need a variable of type float

Ex. float basic;

float variable occupies 4 bytes in memory

double
To store real constant with double precision, we need a variable of type double

7
C Programming SSIT
Ex. double basic;

double variable occupies 4 bytes in memory

void
If a function is not to accept any arguments, specify the same by using void.

returntype functionname(void);

Second use of void is to declare that function doesnt return any thing back to calling
function.

void functionname (parameterlist);

The form of a C program

Preprocessor Directives

Global variables

Prototypes

int main(parameter list){

/*statements*/

returntype function1(parameter list){

/*statements*/

returntype function2(parameter list){

/*statements*/
8
C Programming SSIT
}

Where variables are declared


There are three places where we use to declare the variables

1. As a part of function definition(Formal Parameters) ex.int max(int a,int b);


2. Inside function body(local variables) Ex.void roots(int a,int b,int c){int d=b*b-4*a*c;}

3. Out side of all functions(Global variables)

Operators

An operator is a symbol which performs an operation. As an example + operator performs


an addition operation.

int no;

no=10+20;

Here 10, 20 are operands and + is an operator. Depends upon number of operands the
operator is expecting all these operators are broadly categorized into following groups.

1. Unary - Expects one operand


2. Binary - Expects two operands

3. Ternary - Expects three operands

Depends upon type of operation operator is performing all these operators are broadly
categorized into following groups

1. Assignment operator =

9
C Programming SSIT

2.Arithmetic operator + * / %

3.The increment and decrement operator ++

4.Relational operators < > <= >= = = !=

5. logical operators && || !

6.Bitwise operator ~, << , >> , & , | ,^

7.Arithmetic Assignment Operator +=,-=,*=,/=,%=

8. Conditional operator ? :

9. Pointer operators & *

10.The compile time operator sizeof()

11.Comma Operator ,

12. Structure Member Accessing Operator (.)dot , (->) Arrow

Assignment Operator

'=' is the assignment operator.

Assignment statement is constructed by using assignment

Syntax

Variable=value|expression;

Example

int no;

no=35;

no=10+28;

Multiple Assignments

To store five integers

int a, b, c, d, e;

a=10; b=10; c=10; d=10; e=10;


10
C Programming SSIT
Instead of above five assignment statements, we can write

a=b=c=d=e=10; this is called multiple assignments.

Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same ways that are used
in algebra.

The following lists are the arithmetic operators

Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% modulus

All Arithmetic operators are binary operators.


Both operands of / operator of int type it will do integer division and truncates the decimal portion

5/2 is evaluated as 2 rather than 2.5

Syntax to construct an expression is x%y. x and y should be int type only.

Relational Operators

Relational operators are used to determine relation between two operands.

The following lists are the Relational operators

< Less Than, > Greater than , >= Greater Than Equal To, <= Less Than Equal To

== Equal To, != Not Equal To.

The out come of relational expression always either 1 or 0.If relationship exists 1 otherwise
0.

Example:

14>8 (evaluated to 1)

34<=19 (evaluated to 0)

11
C Programming SSIT

Arithmetic Assignment Operators

a=a+4;

a=a-4;

a=a*4;

a=a/4;

a=a%4;

Above statements can be expressed in words as

Variable=variable operator value;

If statement is of above form it can be expressed in shorthand form as

Variable operator=value;

a+=4;

a-=4;

a*=4;

a/=4;

a%=4;

Here += -= *= /= %= are the arithmetic assignment operators.

Increment and Decrement Operator

++ is increment operator increments its operand value by 1

and

- is decrement Operator decrements its operand value by 1

Both are unary operators. They expect numeric type variable as an operand

Example:

int i=10, j=10;

i++;

J--;
12
C Programming SSIT
These operators can precede the operand or can follow the operand

++i; -prefix form

or

i++ -postfix form

There is no deference between prefix form and postfix form in short expressions. But there
is a difference in long expressions.

int i=10, j;

/*++i; and i++; are same i will be incremented by 1*/

j=++i;

In prefix form it fix the operation first and then uses the operand in that context.In this
example i will be incremented by 1 and i will be assigned to j.

j=i++;

In postfix form, operand value will be used in the context and performs operation. In this i
will be assigned to j first and i will be incremented by 1.

Logical Operators

There are three logical operators

Logical and &&


Logical Or ||

Logical not !

The truth table for && operator

Operand1 operand2 operand1&&operand2

1 1 1

1 0 0

0 1 0

0 0 0

13
C Programming SSIT
The truth table for || operator

Operand1 operand2 operand1||operand2

1 1 1

1 0 0

0 1 0

0 0 0

In and and or operation if left operand determines the answer right operand will not be
evaluated.

Logical not (!)

Logical not (!) is a unary operator .Syntax to construct an expression using logical not is

!(expression)

It reverse the outcome of its operand.

!(5>6) is evaluated to 1

!(6>5) is evaluated to 0

Bitwise Operators

The bitwise operators provided by C may only be applied to operands of type char, short, int
and long.

& Bitwise AND

| Bitwise inclusive OR

^ Bitwise exclusive OR

~ Ones complement(NOT)

>> Shift right

<< shift left

The & and * Pointer Operators


14
C Programming SSIT
A pointer is a variable that holds a memory address.A variable is going to be a pointer, it must be
declared as such

The general form for declaring a pointer is

type * variablename;

Ex: int * p;

Where type is the base type of the pointer.

Pointer Operators

There are two pointer operators: * and &.

1. & (Address Of):

The & is a unary operator that returns the memory address of its operand.

Example:

int count,*m;

m=&count;

The first statement will create one integer variable with name count and an integer pointer with
name m.

The second statement places address of count variable into the pointer variable m.

You can think of & has returning the address of. Therefore the preceding statement can be
verbalized as m receives the address of count".

To understand the above assignment better, assume that the variable count uses memory location
2000 to store its value, also assume that count has value of 100, then after preceding assignment
m will have the value 2000.

2. *( At address):

The second pointer operator is the compliment of & ,This is also a unary operator that returns the
value located at that address.

That follows

Example:

q=*m;

Places the value of count into q . Thus q will have the value 100, 100 is actually stored in the
memory address 2000, which is address that was stored in m.so you can think of * as at

15
C Programming SSIT
address. In this case the preceding statement can be verbalized as q receives the value at
address m".

Conditional Operator

The conditional expressions written with the ternary operator "?:" provides an alternate way
to write the if conditional construct. This operator takes three arguments.

The syntax to construct expression is

Expression1? Expression2:Expression3

If expression1 is true (i.e. value is non-zero) then the value returned would be expression2
otherwise the value returned would be expression3.

The Compile-Time Operator sizeof

sizeof is a unary compile-time operator that returns the length, in bytes, of the variable or
parenthesized type specifier that it precedes. For example, assuming that integers 4 bytes and
doubles are 8 bytes, this fragment will display 8 4.

double f;

Printf(%d ,sizeof( f)); /* prints the value as 8*/

Printf(%d ,sizeof(int)); /* prints the value as 4 */

Remember, to compute the size of a type, you must enclose the type name in parentheses.
This is not necessary for variable names, although there is no harm done.

Precedence and Associavity of Operator

In case of a tie between operations of same priority then they are evaluated based on their
associativity. You can use parenthesis to change the order of evaluated. If there is more than one
set of parenthesis the innermost parenthesis will be performed first followed by the operations with
in the second innermost pair and so on?

Operator Associativity

!,++,-- right to left

*,/,% left to right

+,- left to right

<,<=,>,>= left to right

==,!= left to right

& left to right

16
C Programming SSIT

^ left to right

| left to right

&& left to right

|| left to right

?: right to left

=,+=,-=,*=,/=,%= right to left

Casts

You can force an expression to be of a specific type by using a cast. The general form of a cast is

(type) expression

Where type is a valid data type. For example, to cause the expression x/2 to evaluate to type float,
write

(float)x/2

17
C Programming SSIT

EXERCISE-1

1. The no of binary operators of arithmetic in C is

a) 5 b) 4 c) 6 d) 7

2. The no of Unary Arithmetic Operators in C is

a) 1 b) 4 c) 3 d) 2

3. Identity the operator not used in C.

a)~ b)% c)^ d)**

4) The operator % yields

a) Quotient b) remainder value

c) Percentage value d) Fractional part of the division

5) The operator when applied to floating values yield

a)Remainder value b)quotient including fractional part

c) Negative value of remaindered d) integer quotient value

6) The operator % can be applied only to

a) Float values b) Double values

c) Options a & b d) Integral values

7) x%y is equal to

a)(x-(x/y)) b)(x-(x/y)*y)

c)(y-(x/y)) d)(y-(x/y)*y)

18
C Programming SSIT
8) The operator can be applied to

a) Integral values b) float values

c) Zero c) positive value

9) The second operand of the operator % must always be

a) Negative value b) Non-zero

c) Zero d) +ve value

10) If both the operands of the operator are integers the result is

a) a float value b)an integer value

c) Option a or b d) undefined

11) Integer division result in

a) Rounding of the fractional part of quotient

b) Truncating the fractional part of the quotient

c) Float value

d) Syntax error

12) Assume c1 and c2 as char variables if C1='A'; C2='2'; what are the
results of the statements putchar (C1+3) and putchar ((2-1);)

a)D,1 b)C,2 c)d,1 d)C,1

13) Which is not a valid expression?

a)+OXABS b)-0525 c)15- d)+a

14) Which is not a valid expression?

a)-p++ b)++p-- c)++b d)++x++

15) Which is not a valid expression?

a)++(a+b) b)y-- c)--x-- d)++p+q

16) The equality operator is represented by

a):= b).EQ c)= d)==17

17) Identify the logical operator

a)! b)! = c) ~ d) ==

19
C Programming SSIT
18) Identify the relational operator

a)&& b)> c)|| d)!

19) The number of binary bitwise operators in C is

a)3 b)4 c)5 d)6

20)The number of bitwise operators in C is

a)4 b)5 c)6 d)7

EXERCISE-2

1. The symbol of exclusive OR operator is

a) ^ b) ~ c) & d)1

2. The symbol of one's complement operator is

a) & b) ^ c) ~ d) 1

3. The symbol of bitwise AND operators is

a) << b) &= c) && d) &

4. The symbol of bitwise OR operator is

a)| b)|| c)!= d)>

5. The symbol of left shift operator is

a)>= b)>>> c)>> d)>

6. The symbol of right shift operator is

a)>= b)>>> c)>> d)>

7. The bitwise AND is used for

a) Masking b) comparison c) division d) shifting bits

8. The bitwise OR is used to

a) Set the desired bits to 1 b) multiply numbers

c) Divide numbers d) set the desired bits too

9. The bitwise XOR is used to

a) Complement the desired bits b) multiply the numbers


20
C Programming SSIT
c) Divide the numbers d) mask the bits

10. Logical right shift results in

a) Maintaining the left most bit position

b) Zero is shifted to the left most bit position

C) One is shifted to the right most bit value.

d) Zero is shifted to the right most position

11. Arithmetic right shift result in

a) zero is shifted the left most bit position

b) One is shifted to the right most bit

c) Maintain the left most bit value.

d) Zero is shifted to the most bit position

12. The result of the expression ~~> is

a)7 b)1 c)0 d)invalid expression

13. The operator that can be used for simple encryption is

a)~ b)& c)^ d)all the above

14. Identify the invalid compound assignment

a)+= b)^ c)<<= d)~

15. Identify the valid compound assignment

a)<<= b)>>= c)options a and b d)all the above

16. Explicit type conversion is known as

a) Casting b) coercion c) optional a and b d) upward type conversion

17. Which expression yields correct value for the expression 1/3?

a) 1/3 b)(float)1/3 c)options a and b d)(float)(1/3)

18. The associativity of ++ operator is

a) Right to left b) Left to right

c) A for arithmetic expression and b for pointer expression

d) A for pointer expression and lb for arithmetic expression


21
C Programming SSIT
19. The associativity of assignment operator is

a) Right to left b) Left to right

c) Option a for arithmetic expression and b for pointer expression

d) Option a for pointer expression and b for arithmetic expression

Console I/O

Introduction Files and streams

In C any physical device which is used to do input or output operations is called file.
Examples: Keyboard, Screen, Printer, Disk file, etc...

Stream

A stream is a logical device, which is an abstraction between the physical device and program.
Via stream only input output operations takes place. There are two types of streams.

Text Stream
Binary Stream

Reading Data from Source

From source we read data, to sink we write data. To read data from source do the following.

1. Open Text or Binary stream in read mode


2. Associate it with source

3. Read data from stream ,in turn it read it from associated source

Writing Data to Sink

To write data to sink do the following.

1. Open text or binary stream in write or append mode


2. Associate it with sink

3. Write data to stream in turn it writes to sink

Standard Streams

To read data from user via keyboard or to give output to the user via screen we need not do
first two steps in reading and writing because when C program execution is started some predefined
streams are opened automatically. They are

stdin : A text stream opened in read mode and associated to keyboard.

22
C Programming SSIT
stdout : A text stream opened in append mode and associated to screen.

stdprn : A text stream opened in write mode and associated to printer.

So to read data from user, we have to read from stdin, where as to give out put to the user write
data to stdout.To read data from stdin to write data to stdout we have built-in functions.

Unformatted and Formatted I/O Functions

To read data from stdin we have getchar(),getch(),getche(),gets(),scanf() built-in functions.

1. getchar()

Syntax:

#include<stdio.h>
int getchar( void );

The getchar() function returns the next character from STDIN, or EOF if the end of file is reached.

2. getch()

Syntax:

#include <conio.h>
int getch( void );

The getch() function returns the next character from STDIN, or EOF if the end of file is reached.

3. getche()

Syntax:

#include <conio.h>
int getche( void );

The getche() function returns the next character from STDIN, or EOF if the end of file is reached.

4. gets()

Syntax:

#include <stdio.h>
char *gets( char *str );

The gets() function reads characters from STDIN and loads them into str, until a newline or EOF is
reached. The newline character is translated into a null termination. The return value of gets() is
the read-in string, or NULL if there is an error.
23
C Programming SSIT
5. scanf()

Syntax:

#include <stdio.h>
int scanf( const char *format, ... );

The scanf() function reads input from stdin, according to the given format, and stores the data in
the other arguments. It works a lot like printf(). The format string consists of control characters,
whitespace characters, and non-whitespace characters. The control characters are preceded by a %
sign, and are as follows:

Control Character Explanation


%c a single character
%d a decimal integer
%i an integer
%e, %f, %g a floating-point number
%o an octal number
%s a string
%x a hexadecimal number
%p a pointer
%n an integer equal to the number of characters read so far
%u an unsigned integer
%[] a set of characters
%% a percent sign

To write data to stdout we have putchar (), puts (),printf() built-in functions.

1. putchar ()

Syntax:

#include <stdio.h>
int putchar( int ch );

The putchar() function writes ch to STDOUT. The code

putchar( ch );

2. puts()

Syntax:

#include <stdio.h>
int puts( char *str );
24
C Programming SSIT

The function puts() writes str to STDOUT. puts() returns non-negative on success, or EOF on
failure

3. printf ()

Syntax:

#include <stdio.h>
int printf( const char *format, ... );

The printf() function prints output to STDOUT, according to format and other arguments passed to
printf(). The string format consists of two types of items - characters that will be printed to the
screen, and format commands that define how the other arguments to printf() are displayed.
Basically, you specify a format string that has text in it, as well as "special" characters that map to
the other arguments of printf(). For example, this code

char name[20] = "Bob";

int age = 21;

printf( "Hello %s, you are %d years old\n", name, age );

Displays the following output:

Hello Bob, you are 21 years old

The %s means, "insert the first argument, a string, right here." The %d indicates that the second
argument (an integer) should be placed there. There are different %-codes for different variable
types, as well as options to limit the length of the variables and whatnot.

Code Format
%c Character
%d signed integers
%i signed integers
%e scientific notation, with a lowercase "e"
%E scientific notation, with a uppercase "E"
%f floating point
%g use %e or %f, whichever is shorter
%G use %E or %f, whichever is shorter
%o Octal
%s a string of characters
%u unsigned integer
%x unsigned hexadecimal, with lowercase letters
%X unsigned hexadecimal, with uppercase letters
%p a pointer
the argument shall be a pointer to an integer
%n into which is placed the number of characters
written so far

25
C Programming SSIT
%% a '%' sign

Statements

You do this, we can specify to the system by using statement. A statement is a complete instruction
categorizes statements into these groups:

Selection
Iteration

Jump

Label

Expression

Block

C program control statements can be put into the following categories.

26
C Programming SSIT

1. Selection Statements

C supports two selection statements: if and switch. In addition, the (? :) operator is an alternative
to if in certain circumstances.

If

The general form of the if statement is

If(expression)statement;
[else statement;]

Where a statement may consist of a single statement, a block of statements, or nothing. The else
clause is optional.

If expression evaluates to true (anything other


than 0), the statement or block that forms the
target of if is executed, otherwise the statement
the is the target of else is executed, if it exists.

The conditional statement controlling if must


produce a scalar result. A scalar is either integer,
character, pointer or floating point type.

27
C Programming SSIT
If Ladder

If we have several groups of statements and one of the group is to be executed selectively
specify that intension by using if Ladder or switch in some cases.

Syntax

if(expression)
statement;
else if(expression)
statement;
else if(expression)
statement;
.
.
.
else statement;

The conditions are evaluated from the top


downword.As soon as a true condition is
found, the statement associated with it is executed and the rest of ladder is bypassed. If none
of the conditions are true, the final else is executed. If the final else is not present, no action
takes place if all other conditions are false.

switch
C has a built-in multiple-branch selection statement, called switch, which successively
test the value of an expression against list of integer or character constant. When a match is
found, the statements associated with that constants are executed. The general form of switch
statement is

switch(expression){
case constant1:
statement sequence
[break];
case constant2:
statement sequence
[break];
case constant3:
statement sequence
[break];
.
.
28
C Programming SSIT
default: statement sequence;
}

The expression must be evaluated to an integer type thus we can use character or integer
values, but floating point expressions, for example, are not allowed.

The value of the expression is tested against the values, one after another, of the constants
specified in the case statements. When a match is found, the statement sequence associated
with that case is executed until the break statement or the end of the switch statement is
reached. The default statement is executed if no matches are found. The default is optional,
and if it is not present, no action takes place if all matches fail.

There are the three important things to know about the switch statement:

The switch differs from the if in that switch can only in equality, where as if can
evaluate any type of relational or logical expression.

No two case constants in the same switch can have identical values. If character
constants are used in the switch statement, they are automatically converted to
integers.

Iteration statements

You do these things repeatedly, we can specify to the system by using one of the three
repetition statements:

1. while loop

2. do-while loop

3. for loop

The while loop

The general form is

while(condition)
statement;

Where statement is an empty statement, a


single statement, or a block of statements.
The condition may be any expression, and true
is any non zero value. The loop iterates while
the condition is true. When the condition
becomes false, program control passes to the line of the code immediately following the loop.
Since where checking the condition at the entrance there is no guarantee of the execution of
the loop body at least once. If loop is executed at least once use do-while instead of while.

The do-while loop

29
C Programming SSIT
The general form of the do-while loop is

do
{
Statement;
}while(condition);

The do-while loop iterates until condition becomes false. The do-while loop checks its condition
at the bottom of the loop. This means that the do-while always executes at least once.

The for loop

You do this things repeatedly varying so and so variable value from so and so to so with
increment or decrement so and so to specify use for statement.

The general form of for loop is

for(Initialization;Condition;Increment)
{
//statements
}

To display first fifteen numbers

int no;
for(no=1;no<=15;no++)
{
printf(%d ,no);
}

Jump Statements

30
C Programming SSIT
C has four statements that perform an unconditional branch:

1. return
2. goto
3. break
4. continue

You can use return and goto anywhere inside the function. You can use break and
continue statements inside nay of the loop statements. You can also use break with switch.

The return statement

You return this value back to the calling area we can specify to the system by using
return statement.

The general form

return value|expression;

To ask the system to bring the control out of void method use return statement.

return value|expression;

The break Statement

The break statement has two uses

1. To break the switch


2. To break the loop

The general form

break;

The continue Statement

To opt for the early iteration use continue statement.

General form

continue;

int i;

for (i=1;i<-10; i++)

{
31
C Programming SSIT
printf(%d ,i);

if(i%2 !=0 ) continue;

printf(\n);

Introduction to Functions

Introduction

Cs main structural component is function. It allows compartmentalization of code and data.


Functions (sub programs) are used to carry out certain sub tasks. The form of C program is

Preprocessor Directives
Global variables
Prototypes
int main(parameter list){
/*statements*/
}

returntype function1(parameter list){


/*statements*/
}
returntype function2(parameter list){
/*statements*/
}

Generally in C, what are the functions we are writing other than main() function we declare them
before the main(), we call them in main() and define them after main(). So function contains
declaration and definition.

Function Declaration

32
C Programming SSIT
Function declaration syntax:

returntype functionname ( parameter list);

To write a function declaration easily tries to get answers for the following questions

1. With what name, the function is to be identified


2. What are the inputs it is expecting

3. What type of value it is going return

To determine maximum of two integers

int max(int a,int b);

Function Definition

Syntax.

returntype functionname (parameterlist)

/*statements*/

Example:

int max ( int a, int b)

if(a>b)return a;

else return b;

Function call statement

You run so and so function we can specify to the system by using function call statement. Syntax

Functionname(arguments)

To ask the system to run a function called max() which is expecting two integers

max(10,20);

33
C Programming SSIT
when this statement is executed control goes to max() function taking arguments to the formal
parameters and function executes, when function returns ,return value (if any)replaces the function
call statement. To receive the return value use the following syntax.

Variable=functionname(arguments);

Function Arguments

If function has to accept arguments it must declare the parameters that will receive the
values of the arguments, has shown in the following function the parameter declaration occur after
the function name.

/* return maximum of two integers */

int max(int a, int b)


{

if(a>b)
return a;
else
return b;
}

Call By Value and Call By Reference

In a computer language there are two ways to pass the arguments to a subroutine , The
first is call by value. This method copies the value of the argument into the formal parameter of the
function. In this case , changes made to the parameter have no effect on the argument.

Call by reference is second way of passing the arguments to the function. In this method the
address of the argument will be copied to the formal parameters. In side the sub routine the
address is used to access the actual argument used in the call. This means that the changes made
to the parameter effect to the argument.

Creating a call By reference

Example:

#include<stdio.h>
void swap(int *,int *);
int main(void)
{
int i,j;
i=10;
j=20;
printf(I and J before swapping : %d %d\n,i,j);
swap(&I,&j); /* pass the addresses I and j */
printf(I and j after swapping : %d %d\n,i,j);
return 0;
}
void swap(int *x,int *y)
{
int temp;
34
C Programming SSIT
temp=*x; /* save the value at address x */
*x=*y; /* put y in to x */
*y=temp; /* put x into y */
}

The output of the program seen here

i and j before swapping : 10 20


j and j after swapping : 20 10

Command Line Arguments


C provides a fairly simple mechanism for retrieving command line arguments entered by the user.

C:/>copy temp.txt temp1.txt

is called command line. Through command line we are giving instruction to operating
system to run a program. Here copy is the command (name of the program), temp.txt
temp1.txt are the command line arguments. Operating system is making call to the main
function of copy program by passing two arguments.

1. No of command line arguments plus one as first argument


2. char pointer array as a second argument. Which consist of starting addresses of
command and command line arguments?

To receive first argument define parameter of int type because first argument is integer
type, in above example first argument is 3.Define un sized char pointer array to receive second
argument. So main function definition should look like this:

int main(int argc,char* argv[])


{
/* statements*/
}

Where argc is argument count, argv is argument values. If argc receives 0 means no
command line arguments are specified by the user. argv[0] points the command, argv[1]
first command line argument, so on.

Recursive Functions

Recursion is a programming technique that allows the programmer to express operations in terms
of themselves. A useful way to think of recursive functions is to imagine them as a process being
performed where one of the instructions is to "repeat the process". This makes it sound very similar
to a loop because it repeats the same code, and in some ways it is similar to looping.

On the other hand, recursion makes it easier to express ideas in which the result of the recursive
call is necessary to complete the task. Of course, it must be possible for the "process" to sometimes
be completed without the recursive call.
35
C Programming SSIT
One simple example is the idea of building a wall that is ten feet high; if I want to build a ten foot
high wall, then I will first build a 9 foot high wall, and then add an extra foot of bricks.

syntax:

void recurs()
{
recurs(); /* Function calls itself */
}

int main()
{
recurs(); /* Sets off the recursion */
return 0;
}

Arrays and Strings

An Array is a group of similar type of variables. We can construct array of any type like int,
float, char, double. Moreover we can construct one dimensional array as well as multidimensional
array.

One Dimensional Arrays

It is an array which wills stores in the memory horizontally.

Array declaration:

To construct a one dimensional array system requires the following 3 specifications, they include.

1. Array name (group name)

2. Number of variables you want to have in that group.

3. Type of variables you want to have in that group.

Syntax

Type ArrayVariableName[size];

36
C Programming SSIT
int nos[5];

if above statement is executed for all 5 variables memory locations will be allocated in a continues
manner.

The amount of storage required to hold an array is directly related to its type and size, for a single
dimensional array the total size in bytes will be computed as

total bytes=sizeof(base type)* size of an array.

Total number of bytes allotted for this array are:

sizeof(int) * 5 => 2 * 5 = 10;

Accessing array elements:

Variables in an array are called elements. Each element is identifying with unique index
value. Indexing is zero based. First element index is 0, second element index is 1,so on. To name
the element of the array syntax is

Arrayname[index]

Name of the first element is nos[0],name of the second is nos[0],so on.

While constructing the array, if we know what values elements are to represent, use the following
syntax.

type arrayvariable[size] ={list of values};

int nos[]={10,20,30,40,50} ;

Passing One Dimensional Array to Functions

In C , you can not pass an entire array as an argument to function, You can however pass a
pointer to an array by specifying arrays name with out an index. For example the following program
fragment passes the address of nos to display().

int main(void)
{
int nos[]={10,20,30,40,50};
display(nos);
return 0;
}

If a function receives a pointer to a one dimensional array, you can declare its formal
parameter in one of three ways: as a pointer, as a sized array or as un sized array. For example, to
receive nos, functions called display() it can be declared as

Example:

void display(int *p) /* Pointer */

37
C Programming SSIT
{
int i;
for(i=0;i<5;i++)
{
printf(%d ,*(p+i));
}
}

Or

void display(int p[5]) /* Sized array */


{
int i;
for(i=0;i<5;i++)
{
printf(%d ,p[i]);
}
}

Or
void display(int p[]) /* Unsized array */
{
int i;
for(i=0;i<5;i++)
{
printf(%d ,p[i]);
}
}

All three declaration methods produce similar results because each tells the compiler that an
integer pointer is going to be received

Strings

Some thing which is placed in between double quotation marks is called string literal .In C a
string is treated as one dimensional char array terminated with null character. This means that after
the last truly usable char there is a null, hex 00, which is represented in C by '\0'. The subscripts
used for the array start with zero (0). The following line declares a char array called str. C provides
fifteen consecutive bytes of memory. N.B. Only the first fourteen bytes are usable for character
storage, because one must be used for the string-terminating null.

char str[15];

The following is a representation of what would be in RAM, if the string "Hello, world!" is
stored in this array.

Characters: H e l l o , w o r l d !
Hex values: 48 65 6C 6C 6F 2C 20 77 6F 71 6C 64 21 00
Subscripts: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

38
C Programming SSIT
The array name always contains the first element address. Thus, both of the following will
save the address of the 0th character in the pointer variable ptr.

ptr = str;
ptr = &str[0];

String Functions

The string functions operate on null-terminated arrays of characters and require the
header<string.h>

1. strlen()

Syntax:

#include <string.h>
size_t strlen( char *str );

The strlen() function returns the length of str (determined by the number of characters
before null termination).

The following code will result in len having the value 13.

int len = strlen("Hello, world!");

2. strcpy()

Syntax:

#include <string.h>
char *strcpy( char *to, const char *from );

The strcpy() function copies characters in the string from to the string to, including the null
termination. The return value is to.

Given the following declarations, several things are possible.

char S[25];
char D[25];

Putting text into a string:

strcpy(S, "This is String 1.");

Copying a whole string from S to D:


39
C Programming SSIT
strcpy(D, S);

Copying the tail end of string S to D:

strcpy(D, &S[8]);

Note. If you fail to ensure that the source string is null-terminated, very strange and sometimes
very ugly things may result.

3. strncpy()

Syntax:

#include <string.h>
char *strncpy( char *to, const char *from, size_t count );

The strncpy() function copies at most count characters of from to the string to. If from has
less than count characters, the remainder is padded with '\0' characters. The return value is the
resulting string.

4. strcat()

Syntax:

#include <string.h>
char *strcat( char *str1, const char *str2 );

The strcat() function concatenates str2 onto the end of str1, and returns str1. For example:

printf( "Enter your name: " );


scanf( "%s", name );
title = strcat( name, " the Great" );
printf( "Hello, %s\n", title );

5. strncat()
Syntax:

#include <string.h>
char *strncat( char *str1, const char *str2, size_t count );

The function strncat() concatenates at most count characters of str2 onto str1, adding a null
termination. The resulting string is returned.

Given the following declarations, several things are possible, but only one is commonly
used.

char S[25] = "world!";


char D[25] = "Hello, ";

Concatenating five characters from the beginning of S onto the end of D and placing a null
at the end:
40
C Programming SSIT
strncat(D, S, 5);
strncat(D, S, strlen(S) -1);

Both would result in D containing "Hello, world".

Note: If you fail to ensure that the source string is null-terminated, very strange and
sometimes very ugly things may result.

6. strcmp()
Syntax:

#include <string.h>
int strcmp( const char *str1, const char *str2 );

The function strcmp() compares str1 and str2, then returns:

Return value Explanation


less than 0 str1 is less than str2
equal to 0 str1 is equal to str2
greater than0 str1 is greater than str2

For example:

printf( "Enter your name: " );


scanf( "%s", name );
if( strcmp( name, "Mary" ) == 0 )
printf( "Hello, Dr. Mary!\n" );

7. strncmp()
Syntax:

#include <string.h>
int strncmp( const char *str1, const char *str2, size_t count );

The strncmp() function compares at most count characters of str1 and str2. The return
value is as follows:

Return value Explanation

less than 0 str1 is less than str2

equal to 0 str1 is equal to str2

greater than 0 str1 is greater than str2

If there are less than count characters in either string, then the comparison will stop after
the first null termination is encountered.

41
C Programming SSIT
Two-Dimesional Array

C supports multi dimensional arrays . The simplest form of multidimensional array is the two
dimensional array. A two dimensional array is essentially , an array of one dimensional arrays.

To declare two dimensional array syntax is

type arrayvariablename[size][size];

Example:

int twod[4][3];

To access the element of two dimensional array

arrayname[rowindex][columnindex];

To assign 1 in first element

twod[0][0]=1;

In case of two dimensional array , the following formula yields the number of bytes of memory
needed to hold it.

Bytes=sizeof(firstindex) * sizeof(secondindex) * sizeof (base type)

Pointers

A pointer is a variable that holds memory address. This address is the location of another variable
in memory.

Correct understanding and use of pointers is crucial to successful c programming, there are several
reasons for this:

1. Pointers can improve the efficiency of certain routines.

2. Pointers provide the means by which function can modify their calling arguments.

3. Pointers support dynamic allocation and dynamic data structures such as binary trees and linked
lists

Pointer variables

42
C Programming SSIT
A pointer is a variable that holds a memory address. A variable is going to be a pointer, it must be
declared as such

The general form for declaring a pointer is

type * variablename;

Example: int * p;

Where type is the base type of the pointer.

The Pointer Operators

There are two pointer operators: * and &.

1. & (address of):

The & is a unary operator that returns the memory address of its operand.

Example:

int count,*m;

m=&count;

The first statement will create one integer variable with name count and an integer pointer with
name m.

The second statement places address of count variable into the pointer variable m.

You can think of & has returning the address of. Therefore the preceding statement can be
verbalized as m receives the address of count".

To understand the above assignment better, assume that the variable count uses memory location
2000 to store its value, also assume that count has value of 100, then after preceding assignment
m will have the value 2000.

2. * at address:

The second pointer operator is the compliment of & ,This is also a unary operator that returns the
value located at that address.

That follows

Example:

q=*m;

Places the value of count into q . Thus q will have the value 100, 100 is actually stored in
the memory address 2000, which is address that was stored in m.so you can think of * as at

43
C Programming SSIT
address. In this case the preceding statement can be verbalized as q receives the value at
address m".

Pointer Arithmetic

There are only two arithmetic operations that can use on pointers, they include..

1. Addition

2. Subtraction

To understand what occurs in pointer arithmetic,

Let p1 be an integer pointer with the address 2000. Also assume ints are 2 bytes long. After the
expression

P1++;

P1 contains 2002, not 2001. The reason for this is that each time p1 is incremented it will point to
the next integer. The same is true for decrements.

Each time a pointer is incremented , it points to the memory location of the next element of its base
type. Each time it is decremented it points to the memory location of the previous element.

You are not limited to the increment and decrement operators.

For Example you may add or subtract integers to or pointers. The expression

p1=p1+12;

Makes p1 point to the 12th element of p1 type beyond the one it currently points to.

Beside addition and subtraction of a pointer and an integer, only one other arithmetic
operation is allowed: You can subtract one pointer to another in order to find the number of objects
base type that separates the two. All other arithmetic operations are prohibited. Specifically you
cant multiply or divide pointer, you cant add two pointers, you cant apply the bitwise operators to
them, you cant add or subtract float or double from pointer.

i.e.

Subtracting one pointer from other, in order to find number of objects of base type that
separate the two pointers.

Note: all other arithmetic operations are prohibited.

Arrays with Pointers

we are already familiar with arrays(collection of similar data elements reffered through common
name).

44
C Programming SSIT
Processing array with pointers is much more effective and it is very simple, bcz generally all data
elements of an array are stored in continuous memory locations, so if you know address of starting
element of an array, it is very easy to move till the end.

Finding address of the first element of an array is just simple, that as

To know the address of any variable we will simply prefix & to that variable

Here in our arrays each element can name as

Array_name[index];

First element index is 0, so the frist element is array_name[0];

so the address of first element is & array_name[0];

let us consider

int a[10],*p;( 'a' be the array and 'p' is the pointer).

p=&a[0];

we can write p=a;

Because array_name itself contains address of first element.

Once u know address of first element its very easy to move forward, thru pointer addition.

At the same time we can move from last element to first also, thru pointer subtraction from last
element address.

Example:

int a[5]={20,30,40,10,50}, *p;


p=a; /* suppose address is 2000*/

The base address value is obtained by mentioning its name first value can be accessed by
using *p .similarly we can access second element *(p + i).

Cs Dynamic Memory Allocation Functions

Cs Memory Map

A complied C program creates and uses four logically distinct regions of memory. The first
region is the memory that actually holds the programs executable code. The next region of the
memory where global variables are stored. The remaining two regions are stack and the heap. The
stack is used for a great many things while program executes. It holds the return addresses of

45
C Programming SSIT
functions call, arguments to functions and local variables. It will also save current state of the CPU.
The heap is a region of free memory that your program can use via Cs dynamic memory allocation
functions.

Standard C defines four dynamic allocation function that all compiler will supply:

calloc(),malloc(),free(),realloc()

1. calloc()

Syntax:

#include <stdlib.h>
void *calloc( size_t num, size_t size );

The calloc() function returns a pointer to space for an array of num objects, each of size size.
calloc() returns NULL if there is an error.

2. malloc ()

Syntax:

#include<stdlib.h>
void *malloc( size_t size );

The function malloc() returns a pointer to a chunk of memory of size size, or NULL if there is an
error. The memory pointed to will be on the heap, not the stack, so make sure to free it when you
are done with it.

3. realloc ()

Syntax:

#include <stdlib.h>
void *realloc( void *ptr, size_t size );

The realloc() function changes the size of the object pointed to by ptr to the given size. size can by
any size, larger or smaller than the original. The return value is a pointer to the new space, or NULL
if there is an error.

4. free ()

Syntax:

#include <stdlib.h>
void free( void *ptr);

46
C Programming SSIT
The free() function deallocates the space pointed to by ptr, freeing it up for future use. ptr must
have been used in a previous call to malloc(), calloc(), or realloc().

Structures

C language gives you five ways to create a custom data type:

Structures

Union

Typedef

Bit-field

47
C Programming SSIT
Enumeration

Structures

A structure is a collection of variables referenced under one name, providing a


convenient means of keeping related information together. A structure declaration forms a
template that can be used to create structured objects. The variables that make up the
structure are called members. They are also commonly refer to as elements or to as fields.

Need of structure

How will you store the address of a person which consists of name, street, city, state, pin
with the following types
char name[20]
char street[20]
char city[20]
char state[3]
unsigned long int pin

The above stated address will be created in 5 locations which may not be side-by-side
to store all the variables of a particular data in consecutive locations of memory there is a need for
new data type.

i.e., STRUCTURE

Structure Features

Structure allows us to keep related variables under one name


This type object allows us to keep related information together

The General form a structure declaration is

struct tag{
type member-name;
type member-name;
type member-name;
.
.
} structure-variables;

Where either tag or structure-variables may be omitted, but not both.

Structure Examples:

Student Address Details

struct Addr
{
char name[20];
char street[20;

48
C Programming SSIT
char city[20];
char state[3];
unsigned long int pin;
};

Department Details

struct dept
{
int deptno;
char name[20];
char location[20];
};

Book details

struct book
{
char bname[20];
float cost;
int copies;
};

Circle structure

struct circle
{
int x;
int y;
int radius;
};

Box Details

struct Box
{
double width;
double height;
double depth;
};

Constructing the structure objects

We have created

49
C Programming SSIT
A simple variable
A pointer variable
A simple array variable
An array of pointers

Using the format.

Simple type variablename;


Pointer type *variablename;
Array type variable[size];
PointerArray type *variable[size]

Example:

int no;
int *p;
char name[20];
int *p[10];

In the same steps we can create a structure variable too


struct <structure name> <variable>;

To declare variable of type addr, write

struct addr addr_info;

When above statement is executed for all members memory locations are allocated as per
their specifications in a continuous manner.

Example:

struct dept comp;


struct circle c;
struct box b;

Accessing structure members

Individual members of a structure are accessed through the use of the . (dot) Operator.

For Example, the following statement assigns the pin code 500036 to the pin field of the structure
variable addr_info.

addr_info.pin=500036;

The general form for accessing the member of the structure is objectname.membername

Examples:

50
C Programming SSIT
addr_info.name
addr_info.street
addr_info.city
addr_info.state
addr_info.pin
comp.deptno
comp.name
comp.loc
b.width
b.height
b.depth

Structure Memory Location

Consider Student address structure


struct addr
{
char name[20];
char street[20];
char city[20];
char state[3];
unsigned long int pin;
};
The total memory allocated for this structure is
20+20+20+3+4 = 67 bytes

Structure initialization

Structure can be initialized during the declaration of the structure

struct box
{
double width;
double height;
double depth;
}b={25,40,55};

struct addr
{
char name[20];
char street[20};
char city[20];
char state[3];
unsigned long int pin;
}addr_info={sai, patamata, vja, ap ,34567} ;

51
C Programming SSIT
Write a program to accept and display the address details

#include<stdio.h>
#include<conio.h>
int main(void)
struct addr
{
char name[20];
char street[20];
char city[25];
char state[3];
unsigned long pin ;
};
struct addr addr_info;

int main(void)
{
clrscr();
printf(Enter Name);
gets(addr_info.name);
printf(Enter Street);
gets(addr_info.street);
printf(Enter City);
gets(addr_info.city);
printf(Enter State);
gets(addr_info.state);
printf(Enter Pin);
scanf(%d,addr_info.pin);
clrscr();
printf(Name:%s\n,addr_info.name);
printf(street:%s\n,addr_info.street);
printf(city:%s\n,addr_info.city);
printf(state:%s\n,addr_info.state);
printf(pin:%d\n,addr_info.pin);
}

Array of structures

As we know array is collection of similar data types like int, float, char etc. In the same
way we can also define array of structures. In that array every element is of structure type.
Array of structures can be declared as follows.

struct addr
{
char name[20];
char street[20];
char city[25];
char state[3];
unsigned long pin ;
}; struct addr addr_info[5];

Structure within structure (Nested Structure)

52
C Programming SSIT
We can take any data type for declaring structure members like int, float, char etc.we can also
take objects of one structure as members of another structure.

The general form is

struct date
{
int dd;
int mm;
int yy;
};

struct person
{
char name[25];
struct date dob;
}emp;

Structures and functions

Like variables of standard type structure variables can also be passed to the function by
value or address .

Syntax:

return type function name (structure variable)

Example:

void show ( struct record m)

Pointer to a STRUCTURE

Pointer is a variable that holds the address of another variable. The variable may be of any
type int, float, char etc. in the same way we can define a pointer to a structure. Structure pointers
are declared by placing * in front of structure variables name.

Example:

struct addr
{
char name[20];
char street[20];
char city[25];
char state[3];
unsigned long pin ;
53
C Programming SSIT
};
struct addr *p;

p is pointer to structure.

To access data members the syntax is

To access the members of the structure using a pointer to that structure you must use the -
> operator.

Example:

p->name;
p->street;
p->city;
p->state;
p->pin;

For Example, to assign 500036 to pin

p->pin=500036;

54
C Programming SSIT

Enumerations

Enumeration is a set of named integer constants. Enumerations are defined much like
structures. The keyword enum the start of the enumeration type. The general form for
enumerations is

Syntax

enum tag
{
//Enumeration list
} var_list;

The following four fragments define an enumeration called coin:

enum coin
{
penny, nickel, dime, quarter, half_dollar, dollar
};

The enumeration tagname can be used to declare variables of its type the following declares
money to be a variable of type coin:

enum coin money;

Given these declarations,the following typs of statements are perfectly valid:

money=dime;

if(money==quarter)

printf(Money is a quarter.\n);

The key point to understand about is the enumeration is that each of the symbols stands for an
integer value. Each symbol is given a value one greater than the symbol that preceeds it.The value
of the first enumeration symbol is zero. Therefore,

printf(%d %d ,penny,dime);

displays 0 2 on the screen.

55
C Programming SSIT

Introduction to Preprocessor

Preprocessing

Occurs before a program is compiled

Inclusion of other files

Definition of symbolic constants and macros

Format of preprocessor directives

Lines begin with #

Only whitespace characters before directives on a line

The #include Preprocessor Directive

#include

Copy of a specified file included in place of the directive

#include <filename>
Searches standard library for file
Use for standard library files

#include "filename"

Searches current directory, then standard library


Use for user-defined files

Used for:
Programs with multiple source files to be compiled together

The #define Preprocessor Directive

Symbolic Constants:

#define Preprocessor directive used to create symbolic constants and macros Symbolic
constants

When program compiled, all occurrences of symbolic constant replaced with replacement text
56
C Programming SSIT
Format #define identifier replacement-text

Example:

#define PI 3.14159 Everything to right of identifier replaces text

#define PI = 3.14159

Replaces PI with " = 3.14159 " Cannot redefine symbolic constants once they have been
created

Macros

Operation defined in #define A macro without arguments is treated like a symbolic


constant A macro with arguments has its arguments substituted for replacement text, when the
macro is expanded Performs a text substitution no data type checking.

The macro #define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) )

The macro call area = CIRCLE_AREA( 4 );

Will become area = (3.14159 * (4) * (4));

The macro call

area = CIRCLE_AREA( c + 2 );

Will become area = 3.14159 * (c + 2) * (c +2);

Multiple arguments

#define RECTANGLE_AREA(x, y) ((x)*(y))

The macro call rectArea=RECTANGLE_AREA((a+4),(b+7));

will become rectArea = ( ( a + 4 ) * ( b + 7 ) );

57

Você também pode gostar