Top Banner
COURSE MATERIAL FOR C PROGRAMMING LANGUAGE PREPARED BY Mr. A.Manimuthu
91

Course Material for C Programming Language

Mar 28, 2023

Download

Documents

Khang Minh
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Course Material for C Programming Language

COURSE MATERIAL FOR C PROGRAMMING

LANGUAGE

PREPARED BY

Mr. A.Manimuthu

Page 2: Course Material for C Programming Language

Course Material for C Programming Language

Page 1

About the Course Material

C is a general-purpose, procedural, imperative computer programming language developed

in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX

operating system.

C is the most widely used computer language and it is highly efficient. That’s the main

reason why it’s very popular despite being more than 40 years old. Standard C programs are

portable. As mentioned, it’s a good language to start learning programming. If you know C

programming, you will not just understand how your program works, but will also be able to

create a mental picture on how a computer works. This whole material covers the C

programming language features with simple explanation and with the variety of exercises for

the students to develop problem solving skills.

Audience

This course material is prepared for I Semester students of BCA and B.sc Computer Science

Students to learn the programming language by themselves. This material will give the

students enough explanation and exercises where you can take yourself to higher level of

expertise.

Page 3: Course Material for C Programming Language

Course Material for C Programming Language

Page 2

Prerequisites

Before proceeding with this tutorial, you should have a basic understanding of Computer

Programming terminologies. A basic understanding of any of the programming languages

will help you in understanding the C programming concepts and move fast on the learning

track.

What is C Program?

Page 4: Course Material for C Programming Language

Course Material for C Programming Language

Page 3

Features of C Programming Language

Page 5: Course Material for C Programming Language

Course Material for C Programming Language

Page 4

C Program Structure

A C Program basically consists of the following parts:

1. Preprocessor commands.

2. Functions

3. Variables

4. Statements & Expressions

5. Comments

Let us look at a simple code that would print the words "Hello World":

#include <stdio.h>

int main()

{

/* my first program in C */

printf("Hello, World! \n");

return 0;

}

Page 6: Course Material for C Programming Language

Course Material for C Programming Language

Page 5

Applications of C

1. Operating Systems

2. Language Compilers

3. Language Interpreters

4. Assemblers

5. Text Editors

6. Print Spoolers

7. Networks Drivers

8. Databases

Compiler

The compilers are used to translate high-level language program to machine language.

Machine cannot understand C language. We need some translators to convert c language to

machine language.

Each high-level language needs a compiler to translate instructions written in the high-level

programming language into a machine language that a computer can understand and execute.

The entire program will be read by the compiler first and generates the object code.

In Don Bosco college computer lab, you would you GCC COMPILER to compile your c

program in LINUX Plat form

C Program Compiler Machine Code

Page 7: Course Material for C Programming Language

Course Material for C Programming Language

Page 6

Header files in C

Every C program should begin with including a Header file with preprocessor command (#).

A header file is a file with extension .h which contains C function declarations and macro

definitions to be shared between several source files.

There are two types of header files:

1. the files that the programmer writes Ex. #include "file"

2. the files that comes with your compiler Ex. #include <stdio.h>

WITHOUT THESE HEADER FILES YOU CANNOT RUN THE C PROGRAM

SUCCESSFULLY.

Exercises:

1. Find out the list of headers files available in C.

2. What is the most commonly used header file in C.?

3. Try to write each header file with its explanation and functions in your C note book.

Semicolons

In a C program, the semicolon is a statement terminator. That is, each individual statement

inside main function must be ended with a semicolon. In case of missing, the compiler will

throw you an error saying “semicolon missing”

Examples:

int i;

char c;

return;

Page 8: Course Material for C Programming Language

Course Material for C Programming Language

Page 7

How to Compile and Execute C Program

Follow the following steps to Compile and Execute a C program

1. Type vi filename.c in the command prompt

2. New file has been opened

3. Press i alphabet from the keyboard.

4. Type the program

5. Once you finish typing it, press shift: and type wq or wq! to save and come out of the

file.

6. Now to compile your c program type cc filename.c or gcc filename.c

7. The compiler will show you the errors if any, otherwise the prompt will be shown to

run your c program

There are two types messages are shown when you compile the program

1. Errors (You cannot run the program until you resolve the errors)

2. Warnings (These are the suggestions given by the compiler. You can run

the program even if you have warnings. If you want you can correct

otherwise you just ignore.)

8. Type ./a.out to run your program

9. You will get the result of your program.

C is very simple if we understand and go with it. It is enough you know the basic rules of

writing a program with the basic knowledge of c. It will be more interesting for you to write

more complicated programs in C.

Now we shall explore the data part of C.

Page 9: Course Material for C Programming Language

Course Material for C Programming Language

Page 8

Keywords

C language has a list of reserved words which are called “Keywords”. These keywords

cannot be used as variable or constants or any other identifier names. There are 32 keywords

are there in C Language which is listed below:

Exercises:

1. Go to library. Take any book on C. Write down any program in your C notebook and

circle all the keywords in the program. Do this at least for 10 programs so that you

would recall the keywords.

2. Try remembering all these keywords.

Page 10: Course Material for C Programming Language

Course Material for C Programming Language

Page 9

Data Types

All C compilers support a variety of data types. This enables the programmer to select the

appropriate data type as per the need of the application.

• Generally, data is represented using numbers or characters.

• The numbers may be integers or real.

• The basic data types are char, int, float and double.

• The unsigned (+ve) and signed (-ve) qualifiers can be applied to char, int and long.

• The unsigned data types are always zero or positive.

• They signed data types are may be positive or negative.

C Data Types

ConstantBasic ConstantDerived ser-defined

• Pointers • Functions • Arrays

• Structure • Union • Enumeration • typedef

Integral Floating point

Void

int char float double

Page 11: Course Material for C Programming Language

Course Material for C Programming Language

Page 10

Data types with its range:

Exercises:

1. Write any 50 data with its type ex. Ac Number – Double, RollNo - String

2. Write a c program to declare 20 numeric variables using the numeric data types and

display the value to the user.

3. Write a c program to declare 5 character variables using character data type and

display the same to the user.

Page 12: Course Material for C Programming Language

Course Material for C Programming Language

Page 11

Variables

In programming, a variable is a container (storage area) to hold data. It is

to indicate the storage area, each variable should be given a unique name

(identifier). Variable names are just the symbolic representation of a

memory location.

How to Declare a Variable?

data_type variable_name; (OR)

data_type variable_name = constantvalue;

Each variable has data type, value, name of a storage location / memory location, size.

Example:

float num;

int number = 10;

char c;

Page 13: Course Material for C Programming Language

Course Material for C Programming Language

Page 12

The value of a variable can be changed, hence the name 'variable'. In C programming, you

have to declare a variable before you can use it.

Rules for naming a variable in C

1. A variable name can have letters (both uppercase and lowercase letters), digits and

underscore only.

2. The first letter of a variable should be either a letter or an underscore. However, it is

discouraged to start variable name with an underscore. It is because variable name

that starts with an underscore can conflict with system name and may cause error.

3. There is no rule on how long a variable can be. However, only the first 31 characters

of a variable are checked by the compiler. So, the first 31 letters of two variables in a

program should be different.

4. C is a strongly typed language. What this means it that, the type of a variable cannot

be changed.

Exercises:

1. Declare 20 integer variables

2. Declare 20 float variables

3. Declare 20 double variables

4. Declare 20 character variables

Page 14: Course Material for C Programming Language

Course Material for C Programming Language

Page 13

Constants

Constants refer to fixed values that the program may not alter during its execution. These

fixed values are also called literals.

Ex.

Pi = 3.14 or 22/7

e = 2.71

i = √–1

Ω = 0.5671

How to Declare a Constant?

const data_type variable_name; (OR)

const data_type variable_name = constantvalue;

you have to use const keyword in order to declare a constant. It is same as variable but the

value cannot be changed throughout the program once you set.

Example:

const float pi = 3.14;

const int number = 10;

const char c = ‘a’;

Page 15: Course Material for C Programming Language

Course Material for C Programming Language

Page 14

Types of Constants

Integer Constants

• Integer Constants: These are a sequence of numbers from 0 to 9 without decimal

points or fractional part or any other symbols.

• It requires minimum of 2 bytes and maximum 4 bytes.

• Integer constant could be either positive or negative or may be zero.

• The number without a sign is assumed as positive.

• Example: -10, 20, +30, -15.

Real Constants

• Real Constants: Real constants are often known as floating-point constants.

• Integer constants are not fit to represent many quantities. Many parameters or

quantities are defined not only in integers but also in real numbers.

• For example, length, height, prize and distance are measures in real numbers. Ex. 2.5,

5.521, 3.14

C Constants

Numeric Character

IntegerU Real Character String

Page 16: Course Material for C Programming Language

Course Material for C Programming Language

Page 15

Character Constants

• Single Character Constants: A character constant is a single character.

• It can also be represented with single digit or a single symbol or white space enclosed

within a pair of single quote marks. Ex. ‘a’, ‘8’, ‘&’.

• Length of a character, at the most, is one character.

• Character constants have integer values known as ASCII values. For example, ASCII

value for ‘A’ is 65.

Give example M-male, F-Female

String Constants

• String constants are a sequence of characters enclosed within double quote marks.

• The string may be a combination of all kinds of symbols and numbers.

• All string always has null character at the end.

• Examples are “Hello”, “India”, “444”, “a”.

Exercises:

1. Write 10 constants with value for each type above.

2. Write a c program to print pi value using constants.

3. Write a c program to illustrate the use of character constants.

4. Write a c program to illustrate the use of integer constants.

Page 17: Course Material for C Programming Language

Course Material for C Programming Language

Page 16

Page 18: Course Material for C Programming Language

Course Material for C Programming Language

Page 17

Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical

functions.

A = 10

OPERAND

OPERATOR

VALUE

A + B

OPERANDS

OPERATOR

C language is rich in built-in operators and provides the following types of operators:

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Bitwise Operators

5. Assignment Operators

Page 19: Course Material for C Programming Language

Course Material for C Programming Language

Page 18

Arithmetic Operators

The following table shows all the arithmetic operators supported by the C language. Assume

variable A holds 10 and variable B holds 20, then:

Operator Description Example

Operator Description Example

+ Adds two operands A + B = 30

- Subtracts second operand from the first. A - B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B / A = 2

% Modulus Operator and remainder of after an integer division. B % A = 0

++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- = 9

Exercises:

1. Write a c program to perform arithmetic operations

2. Write a c program to get two number as input and display its quotient and remainder

using arithmetic operators.

3. Write a c program to get 5 integer values and display its total and average.

4. Write a c program to get year as input and display the no of months, no of days, no of

weeks.

5. Write a c program to get your birth year and display your age using arithmetic

operators.

6. Write a c program to get hours as input and display no of minutes and seconds in that

hour using arithmetic operators.

7. Write a c program to convert a rupee to dollar.

Page 20: Course Material for C Programming Language

Course Material for C Programming Language

Page 19

8. Write a c program to convert Celsius to frenheit.

9. Write a c program to evaluate (a+b)2

10. Write a c program to calculate the area and perimeter of a circle.

11. Write a c program to calculate the area and perimeter of a square.

12. Write a c program to find the area and perimeter of a rectangle.

13. Write a c program to evaluate (a-b)2

14. Write a c program to evaluate (a + b + c)2 = a2 + b2 + c2 + 2ab + 2ac + 2bc

15. Write a c program to evaluate (a + b)4 = a4 + 4a3b + 6a2b2 + 4ab3 + b4

16. Write a c program to calculate the volume of a cylinder

17. Write a c program to calculate the volume of a sphere.

18. Write a c program to swap two variables without using temp variable

19. Write a c program to swap three variables without using temp variable.

20. Write a c program to solve quadratic equation using math library function.

Relational Operators

The following table shows all the relational operators supported by C. Assume variable A

holds 10 and variable B holds 20, then:

Operator Description Example

== Checks if the values of two operands are equal

or not. If yes, then the condition becomes

true.

(A == B) is not true.

!= Checks if the values of two operands are equal or not. If

the values are not equal, then the condition becomes

true.

(A != B) is true.

> Checks if the value of left operand is greater than the (A > B) is not true.

Page 21: Course Material for C Programming Language

Course Material for C Programming Language

Page 20

value of right operand. If yes, then the condition

becomes true.

< Checks if the value of left operand is less than the value

of right operand. If yes, then the condition becomes true.

(A < B) is true.

>= Checks if the value of left operand is greater than or

equal to the value of right operand. If yes, then the

condition becomes true.

(A >= B) is not

true.

<= Checks if the value of left operand is less than or equal

to the value of right operand. If yes, then the condition

becomes true.

(A <= B) is true.

Exercises:

1. Write a c program to check whether you are eligible to vote or not.

2. Write a c program to check whether a given number is positive or negative.

3. Write a c program to check whether a given year is leap year or not.

4. Write a c program to check whether a given mark is centum or not.

5. Write a c program to check whether a given number is odd or even.

6. Write a c program to check whether a given character is vowel or consonant.

7. Write a c program to find the biggest number among two numbers.

8. Write a c program to find the smallest number among two numbers.

Logical Operators

Following table shows all the logical operators supported by C language. Assume variable A

holds 1 and variable B holds 0, then:

Page 22: Course Material for C Programming Language

Course Material for C Programming Language

Page 21

Operator Description Example

&& Called Logical AND operator. If both the

operands are non-zero, then the condition

becomes true.

(A && B) is

false.

|| Called Logical OR Operator. If any of the two

operands is non-zero, then the condition becomes true.

(A || B) is true

! Called Logical NOT Operator. It is used to

reverse the logical state of its operand. If a

condition is true, then Logical NOT operator will

make it false.

!(A && B) is

true.

Exercises:

1. Write a c program to illustrate the use of logical operator using the following

expressions:

a. (7 && 3)

b. (4 && 0) || (!2)

c. (a || b) && (a+b)

Page 23: Course Material for C Programming Language

Course Material for C Programming Language

Page 22

Bitwise Operators

The following table lists the bitwise operators supported by C. Assume variable ‘A’ holds 60

and variable ‘B’ holds 13, then:

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists

in both operands.

(A & B) = 12, i.e.,

0000 1100

| Binary OR Operator copies a bit if it exists in either

operand.

(A | B) = 61, i.e.,

0011 1101

^ Binary XOR Operator copies the bit if it is set in one

operand but not both.

(A ^ B) = 49, i.e.,

0011 0001

~ Binary Ones Complement Operator is unary and has the

effect of 'flipping' bits.

(~A ) = -61, i.e.,

1100 0011 in 2's

complement form.

>> Binary Left Shift Operator. The left operands value is

moved left by the number of bits specified by the right

operand.

y = n*2𝑠

A << 2 = 240,

i.e., 1111 0000

<< Binary Right Shift Operator. The left operands value is

moved right by the number of bits specified by the right

operand.

y=n/2𝑠W

A >> 2 = 15, i.e.,

0000 1111

Page 24: Course Material for C Programming Language

Course Material for C Programming Language

Page 23

Assignment Operators

The following tables lists the assignment operators supported by the C language:

Operator Description Example

= Simple assignment operator. Assigns values from right side

operands to left side operan

C = A + B will assign

the value of A + B to C

+= Add AND assignment operator. It adds the right operand to the

left operand and assigns the result to the left operand.

C += A is equivalent

to C = C + A

-= Subtract AND assignment operator. It subtracts the right

operand from the left operand and assigns the result to the left

operand.

C -= A is equivalent

to C = C - A

*= Multiply AND assignment operator. It multiplies the right

operand with the left operand and assigns the result to the left

operand.

C *= A is equivalent

to C = C * A

/= Divide AND assignment operator. It divides the left operand

with the right operand and assigns the result to the left

operand.

C /= A is equivalent

to C = C / A

%= Modulus AND assignment operator. It takes modulus using two

operands and assigns the result to the left operand.

C %= A is equivalent

to C = C % A

<<= Left shift AND assignment operator. C <<= 2 is same as C

= C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C

= C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C

Page 25: Course Material for C Programming Language

Course Material for C Programming Language

Page 24

Operator Precedence in C

Operator precedence determines the grouping of terms in an expression and decides how an

expression is evaluated. Certain operators have higher precedence than others; for example,

the multiplication operator has a higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher

precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative * / % Left to right

Additive +- Left to fight

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Page 26: Course Material for C Programming Language

Course Material for C Programming Language

Page 25

Expressions

An expression is a combination of constants, variables, and operators that are used to denote

computations. In other terms it is the combination of operator and operands.

Example:

(2 + 3) * 10 is an expression that adds 2 and 3 first, and then multiplies the result of the

addition by 10.

Statements

In the C language, a statement is a complete instruction, ending with a semicolon. In

many cases, you can turn an expression into a statement by simply adding a semicolon at the

end of the expression.

i = 1; is a statement. You may have already figured out that the statement consists of an

expression of i = 1 and a semicolon(;).

Here are some other examples of statements:

1. i = (2 + 3) * 10;

2. i = 2 + 3 * 10;

3. printf(“%d”,i);

4. scanf(“%d”,&i);

Page 27: Course Material for C Programming Language

Course Material for C Programming Language

Page 26

Input Output in C

When we say Input, it means to feed some data into a program. An input can be given in the form of

a file or from the command line. C programming provides a set of built-in functions to read the given

input and feed it to the program as per requirement.

When we say Output, it means to display some data on screen, printer, or in any file. C programming

provides a set of built-in functions to output the data on the computer screen as well as to save it in

text or binary files.

Types of Streams in C

• Standard input stream is called “stdin” and is normally connected to the keyboard.

• Standard output stream is called “stdout” and is normally connected to the display

screen.

• Standard error stream is called “stderr” and is normally connected to the screen.

The getchar() and putchar() Functions

The int getchar(void) function reads the next available character from the screen and returns

it as an integer. This function reads only single character at a time. You can use this method

in the loop in case you want to read more than one character from the screen.

The int putchar(int c) function puts the passed character on the screen and returns the same

character. This function puts only single character at a time. You can use this method in the

loop in case you want to display more than one character on the screen.

Page 28: Course Material for C Programming Language

Course Material for C Programming Language

Page 27

Check the following example:

#include <stdio.h>

int main( )

{

int c;

printf( "Enter a value :");

c = getchar( );

printf( "\nYou entered: ");

putchar( c );

return 0;

}

When the above code is compiled and executed, it waits for you to input some text. When

you enter a text and press enter, then the program proceeds and reads only a single character

and displays it as follows:

$./a.out

Enter a value : this is test

You entered: t

The gets() and puts() Functions

The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until

either a terminating newline or EOF (End of File).

The int puts(const char *s) function writes the string ‘s’ and ‘a’ trailing newline to stdout.

Page 29: Course Material for C Programming Language

Course Material for C Programming Language

Page 28

#include <stdio.h>

int main( )

{

char str[100];

printf( "Enter a value :");

gets( str );

printf( "\nYou entered: ");

puts( str );

return 0;

}

When the above code is compiled and executed, it waits for you to input some text. When

you enter a text and press enter, then the program proceeds and reads the complete line till

end, and displays it as follows:

$./a.out

Enter a value : this is test

You entered: This is test

The scanf() and printf() Functions

The int scanf(const char *format, ...) function reads the input from the standard input

stream stdin and scans that input according to the format provided.

The int printf(const char *format, ...) function writes the output to the standard output

stream stdout and produces the output according to the format provided.

Page 30: Course Material for C Programming Language

Course Material for C Programming Language

Page 29

The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to

print or read strings, integer, character, or float, respectively. There are many other formatting

options available which can be used based on requirements.

Let us now proceed with a simple example to understand the concepts better:

#include <stdio.h>

int main( )

{

char str[100];

int i;

printf( "Enter a value :");

scanf("%s %d", str, &i);

printf( "\nYou entered: %s %d ", str, i);

return 0;

}

When the above code is compiled and executed, it waits for you to input some text. When

you enter a text and press enter, then program proceeds and reads the input and displays it as

follows:

$./a.out

Enter a value: seven 7

You entered: seven 7

Page 31: Course Material for C Programming Language

Course Material for C Programming Language

Page 30

Here, it should be noted that scanf() expects input in the same format as you provided %s and

%d, which means you have to provide valid inputs like "string integer". If you provide "string

string" or "integer integer", then it will be assumed as wrong input. Secondly, while reading a

string, scanf() stops reading as soon as it encounters a space, so "this is test" are three strings

for scanf().

Exercises:

1. Write a c program to swap two variables.

2. Write a c program to swap three variables.

3. Write a c program to get two integer variables and display the same to the user using

scanf and printf statements.

4. Write a c program to get +2 marks for a student and display the same to the user with

the help of scanf and printf statements.

5. Write a c program to get char as input and display its ASCII value.

6. Write a c program to get p,n,r and calculate the simple interest.

7. Write a c program to get year as input and display the no of days in a year.

8. Write a c program to get minutes as input and display the value as hours and days.

Page 32: Course Material for C Programming Language

Course Material for C Programming Language

Page 31

Control Statements

Decision-making structures require that the programmer specifies one or more conditions to

be evaluated or tested by the program, along with a statement or statements to be executed if

the condition is determined to be true, and optionally, other statements to be executed if the

condition is determined to be false.

C programming language assumes any non-zero and non-null values as true, and if it is

either zero or null, then it is assumed as false value.

Page 33: Course Material for C Programming Language

Course Material for C Programming Language

Page 32

C programming language provides the following types of decision-making statements.

1. if statement

2. if...else statement

3. if…..else ladder

4. nested if statements

5. Switch statement

6. Nested switch statements

if Statement

An if statement consists of a Boolean expression followed by one or more statements.

Syntax

The syntax of an ‘if’ statement in C programming language is:

if(boolean_expression)

{

/* statement(s) will execute if the boolean expression is true */

}

If the Boolean expression evaluates to true, then the block of code inside the ‘if’ statement

will be executed. If the Boolean expression evaluates to false, then the first set of code after

the end of the ‘if’ statement (after the closing curly brace) will be executed.

C programming language assumes any non-zero and non-null values as true and if it is

either zero or null, then it is assumed as false value.

Page 34: Course Material for C Programming Language

Course Material for C Programming Language

Page 33

Flow Diagram

Example

#include <stdio.h>

int main ()

{

/* local variable definition */

int a = 10;

/* check the boolean condition using if statement */

if( a < 20 )

{

/* if condition is true then print the following */

printf("a is less than 20\n" );

}

printf("value of a is : %d\n", a);

return 0;

Page 35: Course Material for C Programming Language

Course Material for C Programming Language

Page 34

}

When the above code is compiled and executed, it produces the following result:

a is less than 20;

value of a is : 10

if…else Statement

An if statement can be followed by an optional else statement, which executes when the

Boolean expression is false.

Syntax

The syntax of an if...else statement in C programming language is:

if(boolean_expression)

{

/* statement(s) will execute if the boolean expression is true */

}

else

{

/* statement(s) will execute if the boolean expression is false */

}

If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the

else block will be executed.

C programming language assumes any non-zero and non-null values as true, and if it is

either zero or null, then it is assumed as false value.

Page 36: Course Material for C Programming Language

Course Material for C Programming Language

Page 35

Flow Diagram

Example

#include <stdio.h>

int main ()

{

/* local variable definition */

int a = 100;

/* check the boolean condition */

if( a < 20 )

{

/* if condition is true then print the following */

printf("a is less than 20\n" );

}

else

Page 37: Course Material for C Programming Language

Course Material for C Programming Language

Page 36

{

/* if condition is false then print the following */

printf("a is not less than 20\n" );

}

printf("value of a is : %d\n", a);

return 0;

}

When the above code is compiled and executed, it produces the following result:

a is not less than 20;

value of a is : 100

if...else if...else Statement / if…else ladder

An if statement can be followed by an optional else if...else statement, which is very useful to

test various conditions using single if...else if statement. When using if…else if…else

statements, there are few points to keep in mind:

1. An if can have zero or one else's and it must come after any else if's.

2. An if can have zero to many else if's and they must come before the else.

3. Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax

The syntax of an if...else if...else statement in C programming language is:

if(boolean_expression 1)

{

/* Executes when the boolean expression 1 is true */

}

Page 38: Course Material for C Programming Language

Course Material for C Programming Language

Page 37

else if( boolean_expression 2)

{

/* Executes when the boolean expression 2 is true */

}

else if( boolean_expression 3)

{

/* Executes when the boolean expression 3 is true */

}

else

{

/* executes when the none of the above condition is true */

}

Example

#include <stdio.h>

int main ()

{

/* local variable definition */

int a = 100;

/* check the boolean condition */

if( a == 10 )

{

/* if condition is true then print the following */

printf("Value of a is 10\n" );

}

Page 39: Course Material for C Programming Language

Course Material for C Programming Language

Page 38

else if( a == 20 )

{

/* if else if condition is true */

printf("Value of a is 20\n" );

}

else if( a == 30 )

{

/* if else if condition is true */

printf("Value of a is 30\n" );

}

else

{

/* if none of the conditions is true */

printf("None of the values is matching\n" );

}

printf("Exact value of a is: %d\n", a );

return 0;

}

When the above code is compiled and executed, it produces the following result:

None of the values is matching

Exact value of a is: 100

Page 40: Course Material for C Programming Language

Course Material for C Programming Language

Page 39

Nested if Statements

It is always legal in C programming to nest if-else statements, which means you can use one

if or else if statement inside another if or else if statement(s).

Syntax

The syntax for a nested if statement is as follows:

if( boolean_expression 1)

{

/* Executes when the boolean expression 1 is true */

if(boolean_expression 2)

{

/* Executes when the boolean expression 2 is true */

}

}

You can nest else if...else in the similar way as you have nested if statements.

Example

#include <stdio.h>

int main ()

{

/* local variable definition */

int a = 100;

int b = 200;

/* check the boolean condition */

if( a == 100 )

{

/* if condition is true then check the following */

Page 41: Course Material for C Programming Language

Course Material for C Programming Language

Page 40

if( b == 200 )

{

/* if condition is true then print the

following */

printf("Value of a is 100 and b is 200\n" );

}

}

printf("Exact value of a is : %d\n", a );

printf("Exact value of b is : %d\n", b );

return 0;

}

When the above code is compiled and executed, it produces the following result:

Value of a is 100 and b is 200

Exact value of a is : 100

Exact value of b is : 200

Page 42: Course Material for C Programming Language

Course Material for C Programming Language

Page 41

Switch Statement

A switch statement allows a variable to be tested for equality against a list of values. Each

value is called a case, and the variable being switched on is checked for each switch case.

Syntax

The syntax for a switch statement in C programming language is as follows:

switch(expression)

{

case constant-expression :

statement(s);

break; /* optional */

case constant-expression :

statement(s);

break; /* optional */

/* you can have any number of case statements */

default : /* Optional */

statement(s);

}

The following rules apply to a switch statement:

1. The expression used in a switch statement must have an integral or enumerated type,

or be of a class type in which the class has a single conversion function to an integral

or enumerated type.

2. You can have any number of case statements within a switch. Each case is followed

by the value to be compared to and a colon.

3. The constant-expression for a case must be the same data type as the variable in the

switch, and it must be a constant or a literal.

Page 43: Course Material for C Programming Language

Course Material for C Programming Language

Page 42

4. When the variable being switched on is equal to a case, the statements following that

case will execute until a break statement is reached.

5. When a break statement is reached, the switch terminates, and the flow of control

jumps to the next line following the switch statement.

6. Not every case needs to contain a break. If no break appears, the flow of control will

fall through to subsequent cases until a break is reached.

7. A switch statement can have an optional default case, which must appear at the end

of the switch. The default case can be used for performing a task when none of the

cases is true. No break is needed in the default case.

Flow Diagram

Page 44: Course Material for C Programming Language

Course Material for C Programming Language

Page 43

Example

#include <stdio.h>

int main ()

{

/* local variable definition */

char grade = 'B';

switch(grade)

{

case 'A' :

printf("Excellent!\n" );

break;

case 'B' :

case 'C' :

printf("Well done\n" );

break;

case 'D' :

printf("You passed\n" );

break;

case 'F' :

printf("Better try again\n" );

break;

default :

printf("Invalid grade\n" );

}

printf("Your grade is %c\n", grade );

return 0;

Page 45: Course Material for C Programming Language

Course Material for C Programming Language

Page 44

}

When the above code is compiled and executed, it produces the following result:

Well done

Your grade is B

Nested switch Statements

It is possible to have a switch as a part of the statement sequence of an outer switch. Even if

the case constants of the inner and outer switch contain common values, no conflicts will

arise.

Syntax

The syntax for a nested switch statement is as follows:

switch(ch1)

{

case 'A':

printf("This A is part of outer switch" );

switch(ch2)

{

case 'A':

printf("This A is part of inner switch" );

break;

case 'B': /* case code */

}

break;

case 'B': /* case code */

}

Page 46: Course Material for C Programming Language

Course Material for C Programming Language

Page 45

Example

#include <stdio.h>

int main ()

{

/* local variable definition */

int a = 100;

int b = 200;

switch(a) {

case 100:

printf("This is part of outer switch\n", a );

switch(b) {

case 200:

printf("This is part of inner switch\n", a );

}

}

printf("Exact value of a is : %d\n", a );

printf("Exact value of b is : %d\n", b );

return 0;

}

When the above code is compiled and executed, it produces the following result:

This is part of outer switch

This is part of inner switch

Exact value of a is : 100

Exact value of b is : 200

Page 47: Course Material for C Programming Language

Course Material for C Programming Language

Page 46

The ? : Operator:

We have covered conditional operator ? : in the previous chapter which can be used to

replace if...else statements. It has the following general form:

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

The value of a ? expression is determined like this:

1. Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the

entire ? expression.

2. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the

expression.

Exercises

1. Write a c program to get a number from 1 to 12 and display month name to the user.

2. Write a c program to get 5 subject marks and find average. If the average is <40 - d

grade >=40 and a <=50 c grade a>50 and <70 b grade a >=70 then a grade.

3. Write a c program to get a number from 1 to 10 and display it in words like 1 - one 2

– two

4. Write a c program to get number from 1 - 7 and display its week day 1 - Sunday 2 –

Monday

5. Write a c program to get month number from 1 to 12 and display the no of days in

that month

6. Write a c program to find the bigger & small number among 2 numbers

7. Write a c program to display the name of a month when the no of month is given. Ex.

1 – January, 2 – February etc., use switch case / if else ladder

8. Write a c program to get student's gender and age as input. Check if gender is male

and age is >30 display "Driver is insured" otherwise "Driver is not insured"

Page 48: Course Material for C Programming Language

Course Material for C Programming Language

Page 47

9. if gender is female and age is > 25 display "female driver is insured" otherwise

"female driver is not insured"

10. Write a c program to get the age of Ram, Shyam, and ajay ages and display the

youngest among three

11. Write a c program to check whether a triangle is valid or not. When the 3 angles of

the triangle are entered through the keyboard. A triangle is valied if sum of all the

three angles are equal to 180

12. Write a c program to get the salary as input

a. Check if the salary is >=25000 and <=40000 then display "Manager"

b. If the salary is >15000 and al<25000 then display "Accountant"

c. if the salary is >=5000 and <=15000 then display "Trainees"

d. if the slary is 5000 and below "No employee working in the company on this

salary"

13. Write a c program to calculate the electricity Bill with the following details

No of Units Consumed rate

a. 200-500 3.50

b. 100-200 2.50

c. < 100 "No Bill"

14. Write a c program to get average as input and calculate the following:

Average Results

a. >34 && < 50 3rd Division

b. >49 && <60 Second Division

c. >=60 && < 75 First Division

d. >=75 && <=100 Distinction

e. less than 35 Fail

Page 49: Course Material for C Programming Language

Course Material for C Programming Language

Page 48

15. Enter a month and year and display the total no of days in that month using switch

case

16. Write a program to check whether the blood donor is eligible or not for donating

blood

a. Age should be greater than 18 years but not more than 55 years

b. Weight should be more than 45 kg

17. Write a c program to get a bus number and display its driver name using switch case

statement.

18. Write a c program to get 5 marks of a 10th student and display whether he has passed

or failed.

19. Write a c program to get 12th marks of a student and display whether he is eligible to

get engineering or not.

20. Write a c program to get a number and check whether it is divisible by 10 or not.

Page 50: Course Material for C Programming Language

Course Material for C Programming Language

Page 49

Control Statements – Looping

You may encounter situations when a block of code needs to be executed several number of

times. In general, statements are executed sequentially: The first statement in a function is

executed first, followed by the second, and so on. Programming languages provide various

control structures that allow for more complicated execution paths. A loop statement allows

us to execute a statement or group of statements multiple times.

Given below is the general form of a loop statement in most of the programming languages:

1. while loop

2. for loop 11. LOOPS

3. do...while loop

4. nested loops

While Loop

A while loop in C programming repeatedly executes a target statement as long as a given

condition is true.

Syntax

The syntax of a while loop in C programming language is:

while(condition)

{

statement(s);

}

Here, statement(s) may be a single statement or a block of statements. The condition may be

any expression, and true is any nonzero value. The loop iterates while the condition is true.

When the condition becomes false, the program control passes to the line immediately

following the loop.

Page 51: Course Material for C Programming Language

Course Material for C Programming Language

Page 50

Flow Diagram

Here, the key point to note is that a while loop might not execute at all. When the condition is

tested and the result is false, the loop body will be skipped and the first statement after the

while loop will be executed.

Page 52: Course Material for C Programming Language

Course Material for C Programming Language

Page 51

Example

#include <stdio.h>

int main ()

{

/* local variable definition */

int a = 10;

/* while loop execution */

while( a < 20 )

{

printf("value of a: %d\n", a);

a++;

}

return 0;

}

When the above code is compiled and executed, it produces the following result:

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19

Page 53: Course Material for C Programming Language

Course Material for C Programming Language

Page 52

for Loop

A for loop is a repetition control structure that allows you to efficiently write a loop that

needs to execute a specific number of times.

Syntax

The syntax of a for loop in C programming language is:

for ( init; condition; increment )

{

statement(s);

}

Here is the flow of control in a ‘for’ loop:

1. The init step is executed first, and only once. This step allows you to declare and

initialize any loop control variables. You are not required to put a statement here, as

long as a semicolon appears.

2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is

false, the body of the loop does not execute and the flow of control jumps to the next

statement just after the ‘for’ loop.

3. After the body of the ‘for’ loop executes, the flow of control jumps back up to the

increment statement. This statement allows you to update any loop control variables.

This statement can be left blank, as long as a semicolon appears after the condition.

4. The condition is now evaluated again. If it is true, the loop executes and the process

repeats itself (body of loop, then increment step, and then again condition). After the

condition becomes false, the ‘for’ loop terminates.

Page 54: Course Material for C Programming Language

Course Material for C Programming Language

Page 53

Flow Diagram

Example

#include <stdio.h>

int main ()

{

/* for loop execution */

for( int a = 10; a < 20; a = a + 1 )

{

printf("value of a: %d\n", a);

}

return 0;

Page 55: Course Material for C Programming Language

Course Material for C Programming Language

Page 54

}

When the above code is compiled and executed, it produces the following result:

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19

Page 56: Course Material for C Programming Language

Course Material for C Programming Language

Page 55

do…while Loop

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while

loop in C programming checks its condition at the bottom of the loop. A do...while loop is

similar to a while loop, except the fact that it is guaranteed to execute at least one time.

Syntax

The syntax of a do...while loop in C programming language is:

do

{

statement(s);

}while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in

the loop executes once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the

loop executes again. This process repeats until the given condition becomes false.

Flow Diagram

Page 57: Course Material for C Programming Language

Course Material for C Programming Language

Page 56

Example

#include <stdio.h>

int main ()

{

/* local variable definition */

int a = 10;

/* do loop execution */

do

{

printf("value of a: %d\n", a);

a = a + 1;

}while( a < 20 );

return 0;

}

When the above code is compiled and executed, it produces the following result:

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19

Page 58: Course Material for C Programming Language

Course Material for C Programming Language

Page 57

Nested Loops

C programming allows to use one loop inside another loop. The following section shows a

few examples to illustrate the concept.

Syntax

The syntax for a nested for loop statement in C is as follows:

for ( init; condition; increment )

{

for ( init; condition; increment )

{

statement(s);

}

statement(s);

}

The syntax for a nested while loop statement in C programming language is as follows:

while(condition)

{

while(condition)

{

statement(s);

}

statement(s);

}

The syntax for a nested do...while loop statement in C programming language

is as follows:

Page 59: Course Material for C Programming Language

Course Material for C Programming Language

Page 58

do

{

statement(s);

do

{

statement(s);

}while( condition );

}while( condition );

A final note on loop nesting is that you can put any type of loop inside any other type of loop.

For example, a ‘for’ loop can be inside a ‘while’ loop or vice versa.

Example

The following program uses a nested for loop to find the prime numbers from 2

to 100:

#include <stdio.h>

int main ()

{

/* local variable definition */

int i, j;

for(i=2; i<100; i++) {

for(j=2; j <= (i/j); j++)

if(!(i%j)) break; // if factor found, not prime

if(j > (i/j)) printf("%d is prime\n", i);

}

return 0;

}

Page 60: Course Material for C Programming Language

Course Material for C Programming Language

Page 59

When the above code is compiled and executed, it produces the following result:

2 is prime

3 is prime

5 is prime

7 is prime

11 is prime

13 is prime

17 is prime

19 is prime

23 is prime

29 is prime

31 is prime

37 is prime

41 is prime

43 is prime

47 is prime

53 is prime

59 is prime

61 is prime

67 is prime

71 is prime

73 is prime

79 is prime

83 is prime

89 is prime

Page 61: Course Material for C Programming Language

Course Material for C Programming Language

Page 60

97 is prime

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves

a scope, all automatic objects that were created in that scope are destroyed.

C supports the following control statements.

1. break statement

2. continue statement

3. goto statement

break Statement

The break statement in C programming has the following two usages:

1. When a break statement is encountered inside a loop, the loop is immediately

terminated and the program control resumes at the next statement following the loop.

2. It can be used to terminate a case in the switch statement (covered in the next

chapter).

3. If you are using nested loops, the break statement will stop the execution of the

innermost loop and start executing the next line of code after the block.

Syntax

The syntax for a break statement in C is as follows:

break;

Page 62: Course Material for C Programming Language

Course Material for C Programming Language

Page 61

Flow Diagram

Example

#include <stdio.h>

int main ()

{

/* local variable definition */

int a = 10;

/* while loop execution */

while( a < 20 )

{

printf("value of a: %d\n", a);

a++;

if( a > 15)

{

/* terminate the loop using break statement */

break;

Page 63: Course Material for C Programming Language

Course Material for C Programming Language

Page 62

}

}

return 0;

}

When the above code is compiled and executed, it produces the following result:

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

continue Statement

The continue statement in C programming works somewhat like the break statement.

Instead of forcing termination, it forces the next iteration of the loop to take place, skipping

any code in between.

For the for loop, continue statement causes the conditional test and increment portions of the

loop to execute. For the while and do...while loops, continue statement causes the program

control to pass to the conditional tests.

Syntax

The syntax for a continue statement in C is as follows:

continue;

Page 64: Course Material for C Programming Language

Course Material for C Programming Language

Page 63

Flow Diagram

Example

#include <stdio.h>

int main ()

{

/* local variable definition */

int a = 10;

/* do loop execution */

do

{

if( a == 15)

{

/* skip the iteration */

a = a + 1;

continue;

}

Page 65: Course Material for C Programming Language

Course Material for C Programming Language

Page 64

printf("value of a: %d\n", a);

a++;

}while( a < 20 );

return 0;

}

When the above code is compiled and executed, it produces the following result:

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 16

value of a: 17

value of a: 18

value of a: 19

Page 66: Course Material for C Programming Language

Course Material for C Programming Language

Page 65

goto Statement

A goto statement in C programming provides an unconditional jump from the ‘goto’ to a

labeled statement in the same function.

NOTE: Use of goto statement is highly discouraged in any programming language because it

makes difficult to trace the control flow of a program, making the program hard to understand

and hard to modify. Any program that uses a goto can be rewritten to avoid them.

Syntax

The syntax for a goto statement in C is as follows:

goto label;

..

.

label: statement;

Here label can be any plain text except C keyword and it can be set anywhere in the C

program above or below to goto statement.

Page 67: Course Material for C Programming Language

Course Material for C Programming Language

Page 66

Flow Diagram

Example

#include <stdio.h>

int main ()

{

/* local variable definition */

int a = 10;

/* do loop execution */

LOOP:do

{

if( a == 15)

{

/* skip the iteration */

a = a + 1;

goto LOOP;

}

printf("value of a: %d\n", a);

Page 68: Course Material for C Programming Language

Course Material for C Programming Language

Page 67

a++;

}while( a < 20 );

return 0;

}

When the above code is compiled and executed, it produces the following result:

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 16

value of a: 17

value of a: 18

value of a: 19

The Infinite Loop

A loop becomes an infinite loop if a condition never becomes false. The for loop is

traditionally used for this purpose. Since none of the three expressions that form the ‘for’

loop are required, you can make an endless loop by leaving the conditional expression empty.

Example

#include <stdio.h>

int main ()

{

for( ; ; )

{

printf("This loop will run forever.\n");

Page 69: Course Material for C Programming Language

Course Material for C Programming Language

Page 68

}

return 0;

}

When the conditional expression is absent, it is assumed to be true. You may have an

initialization and increment expression, but C programmers more commonly use the for (;;)

construct to signify an infinite loop.

NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.

Exercises

1. Write a c program to get a character and display that character for 10 times.

2. Write a c program to get a number as input and display that number for 10 times.

3. Write a c program to print from 1 to 100 using while loop

4. Write a c program to display numbers from 1 to n.

5. Write a c program to display multiplication table.

6. Write a c program to display addition table.

7. Write a c program to display even numbers from 1 to 100.

8. Write a c program to display odd numbers from 1 to 100.

9. Write a c program to count no of prime number from 1 to 100

10. Write a c program to reverse a string.

11. Write a c program to reverse a given number.

12. Write a c program to find GCD.

13. Write a c program to count no of vowels, consonants, spaces or digits and special

symbol in a line of text.

14. Write a c program to perform Cos Series.

15. Write a c program to perform Sin Series.

16. Write a c program to find sum of odd numbers from 1 to n integers.

Page 70: Course Material for C Programming Language

Course Material for C Programming Language

Page 69

17. Write a c program to find sum of even numbers from 1 to n integers.

18. Write a c program to display the following series 1+1/12+1/22+……+1/n2.

19. Write a c program to display the following series 12+22+32+42+……n2

20. Write a c program to find the factorial of a given number.

21. Calculate nPr.

22. Calculate nCr.

23. Write a c program to evaluate the series 1+1/3+1/5+…. upto 15 terms.

24. Write a c program to generate Fibonacci series.

25. Write a c program to reverse a string and check for palindrome.

26. Write a c program to display prime number from 1 to n integers.

27. Write a c program to display the no of leap years from given two years.

28. Write a c program to print the following for n times

*

**

***

****

29. Write a c program to print the following for n times

*

* *

* * *

* * * *

30. Write a c program to print the following for n times

**

****

******

Page 71: Course Material for C Programming Language

Course Material for C Programming Language

Page 70

********

31. Write a c program to print the following for n times

1

12

123

1234

12345

32. Write a c program to print the following for n times.

1

22

333

4444

55555

33. Write a c program to print the following for n times.

1

11

111

1111

Page 72: Course Material for C Programming Language

Course Material for C Programming Language

Page 71

Functions

A function is a group of statements that together perform a task. Every C program has at least

one function, which is main(), and all the most trivial programs can define additional

functions.

You can divide up your code into separate functions. How you divide up your code among

different functions is up to you, but logically the division is such that each function performs

a specific task.

A function declaration tells the compiler about a function's name, return type, and

parameters. A function definition provides the actual body of the function. The C standard

library provides numerous built-in functions that your program can call.

For example, strcat() to concatenate two strings, memcpy() to copy one memory location to

another location, and many more functions.

A function can also be referred as a method or a sub-routine or a procedure, etc.

Defining a Function

The general form of a function definition in C programming language is as follows:

return_type function_name( parameter list )

{

body of the function

}

A function definition in C programming consists of a function header and a function body.

Here are all the parts of a function:

1. Return Type: A function may return a value. The return_type is the data type of the

value the function returns. Some functions perform the desired operations without

returning a value. In this case, the return_type is the keyword void.

Page 73: Course Material for C Programming Language

Course Material for C Programming Language

Page 72

2. Function Name: This is the actual name of the function. The function name and the

parameter list together constitute the function signature.

3. Parameters: A parameter is like a placeholder. When a function is invoked, you pass

a value to the parameter. This value is referred to as actual parameter or argument.

The parameter list refers to the type, order, and number of the parameters of a

function. Parameters are optional; that is, a function may contain no parameters.

4. Function Body: The function body contains a collection of statements that define

what the function does.

Example

Given below is the source code for a function called max(). This function takes two

parameters num1 and num2 and returns the maximum value between the two:

/* function returning the max between two numbers */

int max(int num1, int num2)

{

/* local variable declaration */

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

Page 74: Course Material for C Programming Language

Course Material for C Programming Language

Page 73

Function Declarations

A function declaration tells the compiler about a function name and how to call the function.

The actual body of the function can be defined separately.

A function declaration has the following parts:

return_type function_name( parameter list );

For the above defined function max(),the function declaration is as follows:

int max(int num1, int num2);

Parameter names are not important in function declaration, only their type is required, so the

following is also a valid declaration:

int max(int, int);

Function declaration is required when you define a function in one source file and you call

that function in another file. In such case, you should declare the function at the top of the file

calling the function.

Calling a Function

While creating a C function, you give a definition of what the function has to do. To use a

function, you will have to call that function to perform the defined task. When a program

calls a function, the program control is transferred to the called function. A called function

performs a defined task and when its return statement is executed or when its function-ending

closing brace is reached, it returns the program control back to the main program.

Page 75: Course Material for C Programming Language

Course Material for C Programming Language

Page 74

To call a function, you simply need to pass the required parameters along with the function

name, and if the function returns a value, then you can store the returned value. For example:

#include <stdio.h>

/* function declaration */

int max(int num1, int num2);

int main ()

{

/* local variable definition */

int a = 100;

int b = 200;

int ret;

/* calling a function to get max value */

ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;

}

/* function returning the max between two numbers */

int max(int num1, int num2)

{

/* local variable declaration */

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

Page 76: Course Material for C Programming Language

Course Material for C Programming Language

Page 75

}

We have kept max()along with main() and compiled the source code. While running the final

executable, it would produce the following result:

Max value is : 200

Function Arguments

If a function is to use arguments, it must declare variables that accept the values of the

arguments. These variables are called the formal parameters of the function. Formal

parameters behave like other local variables inside the function and are created upon entry

into the function and destroyed upon exit. While calling a function, there are two ways in

which arguments can be passed to a function:

Call Type Description

1. Call by value - This method copies the actual value of an argument into the formal

parameter of the function. In this case, changes made to the parameter inside the

function have no effect on the argument.

2. Call by reference - This method copies the address of an argument into the formal

parameter. Inside the function, the address is used to access the actual argument used

in the call. This means that changes made to the parameter affect the argument.

Call by Value

The call by value method of passing arguments to a function copies the actual value of an

argument into the formal parameter of the function. In this case, changes made to the

parameter inside the function have no effect on the argument.

Page 77: Course Material for C Programming Language

Course Material for C Programming Language

Page 76

By default, C programming uses call by value to pass arguments. In general, it means the

code within a function cannot alter the arguments used to call the function. Consider the

function swap() definition as follows.

/* function definition to swap the values */

void swap(int x, int y)

{

int temp;

temp = x; /* save the value of x */

x = y; /* put y into x */

y = temp; /* put temp into y */

return;

}

Now, let us call the function swap() by passing actual values as in the following example:

#include <stdio.h>

/* function declaration */

void swap(int x, int y);

int main ()

{

/* local variable definition */

int a = 100;

int b = 200;

printf("Before swap, value of a : %d\n", a );

printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values */

swap(a, b);

printf("After swap, value of a : %d\n", a );

Page 78: Course Material for C Programming Language

Course Material for C Programming Language

Page 77

printf("After swap, value of b : %d\n", b );

return 0;

}

Let us put the above code in a single C file, compile and execute it, it will produce the

following result:

Before swap, value of a :100

Before swap, value of b :200

After swap, value of a :100

After swap, value of b :200

It shows that there are no changes in the values, though they had been changed inside the

function.

Call by Reference

The call by reference method of passing arguments to a function copies the address of an

argument into the formal parameter. Inside the function, the address is used to access the

actual argument used in the call. It means the changes made to the parameter affect the

passed argument.

To pass a value by reference, argument pointers are passed to the functions just like any other

value. So accordingly, you need to declare the function parameters as pointer types as in the

following function swap(), which exchanges the values of the two integer variables pointed

to, by their arguments.

/* function definition to swap the values */

Page 79: Course Material for C Programming Language

Course Material for C Programming Language

Page 78

void swap(int *x, int *y)

{

int temp;

temp = *x; /* save the value at address x */

*x = *y; /* put y into x */

*y = temp; /* put temp into y */

return;

}

Let us now call the function swap() by passing values by reference as in the following

example:

#include <stdio.h>

/* function declaration */

void swap(int *x, int *y);

int main ()

{

/* local variable definition */

int a = 100;

int b = 200;

printf("Before swap, value of a : %d\n", a );

printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values.

* &a indicates pointer to a i.e. address of variable a

and

* &b indicates pointer to b i.e. address of variable b.

*/

swap(&a, &b);

Page 80: Course Material for C Programming Language

Course Material for C Programming Language

Page 79

printf("After swap, value of a : %d\n", a );

printf("After swap, value of b : %d\n", b );

return 0;

}

Let us put the above code in a single C file, compile and execute it, to produce the following

result:

Before swap, value of a :100

Before swap, value of b :200

Exercises:

1. Write c program to swap four variables using functions

2. Write a recursive routine to find the factorial value of an integer. Use it to evaluate

nCr.

3. Write a c program to generate calculator using functions for all mathematical

operations.

4. Write a c program to find biggest and smallest number among 3 numbers. Use

separate functions to find biggest and smallest numbers.

5. Write a c program to find the area and perimeter of square, circle, rectangle, triangle

using separate functions for each operations.

Page 81: Course Material for C Programming Language

Course Material for C Programming Language

Page 80

Arrays

An array is a collection of homogeneous elements stored sequentially under the same variable

name. Homogeneous means same type of elements. Let’s say, the type of array is int, then all

the elements of array should be an integer, not any other types of data.

Rules for defining an Array

1. The array index starts from 0.

2. A specific element is an array is accessed by an index.

3. The lowest address correspondence to the first element and the highest address to the

last element.

Types of arrays

An array has two types.

1. Single dimensional array

2. Multi-dimensional array

Single Dimensional Array (One)

Single dimensional array is nothing but it has one dimension. It is like a linear or vector.

Declaring Arrays

Syntax

datatype arrayname[size];

Example

int marks[5];

Here,

int is the data type,

marks is the array name,

5 is the size of the array.

Page 82: Course Material for C Programming Language

Course Material for C Programming Language

Page 81

Initializing Arrays

It's possible to initialize an array during declaration. For example,

int marks[5] = {19, 10, 8, 17, 9};

Another method to initialize array during declaration:

int marks[] = {19, 10, 8, 17, 9};

Here,

marks[0] is equal to 19

marks[1] is equal to 10

marks[2] is equal to 8

marks[3] is equal to 17

marks[4] is equal to 9

Example

#include<stdio.h>

int main()

{

int i;

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

arr[0] = 10;

arr[1] = 20;

arr[2] = 30;

arr[3] = 40;

arr[4] = 50;

for (i=0;i<5;i++)

{

printf("value of arr[%d] is %d \n", i, arr[i]);

}

}

Output

value of arr[0] is 10

value of arr[1] is 20

value of arr[2] is 30

value of arr[3] is 40

value of arr[4] is 50

Page 83: Course Material for C Programming Language

Course Material for C Programming Language

Page 82

Multi-Dimensional Array (Two or more)

The simplest form of multidimensional array is the two-dimensional array. It has two or more

dimensions. Two dimensional array is nothing but it has two dimensions. It is like a table,

which contains rows and columns.

Declaring Arrays

Syntax

datatype arrayname[row-size][cols-size];

Example

int a[3][4];

Here,

int is the data type,

a is the array name,

3 is the row size of the array,

4 is the column size of the array.

Initializing Arrays

It's possible to initialize an array during declaration. For example,

int a[2][2] = {19, 10, 8, 17}; (or)

int a[2][2] = {{19,10},{8,17}};

Another method to initialize array during declaration:

int a[][] = {19, 10, 8, 17}; (or)

int a[][] = {{19,10},{8,17}};

Here,

a[0][0] is equal to 19

a[0][1] is equal to 10

a[1][0] is equal to 8

a[1][1] is equal to 17

Page 84: Course Material for C Programming Language

Course Material for C Programming Language

Page 83

Example

#include<stdio.h>

int main()

{

int i,j;

int arr[2][2] = {10,20,30,40};

/* Above array can be initialized as below also

arr[0][0] = 10; // Initializing array

arr[0][1] = 20;

arr[1][0] = 30;

arr[1][1] = 40; */

for (i=0;i<2;i++)

{

for (j=0;j<2;j++)

{

printf("value of arr[%d] [%d] : %d\n",i,j,arr[i][j]);

}

}

}

Output

value of arr[0] [0] is 10

value of arr[0] [1] is 20

value of arr[1] [0] is 30

value of arr[1] [1] is 40

Page 85: Course Material for C Programming Language

Course Material for C Programming Language

Page 84

File Handling

A file represents a sequence of bytes on the disk where a group of related data is

stored.

File is created for permanent storage of data.

Why files are needed?

When a program is terminated, the entire data is lost. Storing in a file will preserve

your data even if the program terminates.

If you have to enter a large number of data, it will take a lot of time to enter them all.

However, if you have a file containing all the data, you can easily access the contents

of the file using few commands in C.

You can easily move your data from one computer to another without any changes.

Types of Files

1. Text Files

2. Binary Files

Text Files

Text files are the normal .txt files that you can easily create using Notepad or any

simple text editors.

When you open those files, you'll see all the contents within the file as plain text. You

can easily edit or delete the contents.

They take minimum effort to maintain, are easily readable, and provide least security

and takes bigger storage space.

Page 86: Course Material for C Programming Language

Course Material for C Programming Language

Page 85

Binary Files

Binary files are mostly the .bin files in your computer.

Instead of storing data in plain text, they store it in the binary form (0's and 1's).

They can hold higher amount of data, are not readable easily and provides a better

security than text files.

File Operations

1. Creating a file or Opening an existing file

2. Closing a file

3. Writing into a file.

4. Reading from a file

1. Creating a new file or Opening an existing file

The fopen() function is used to create a new file or to open an existing file.

General Syntax

*fp = FILE *fopen(const char *filename, const char *mode);

Here filename is the name of the file to be opened and mode specifies the purpose of

opening the file. Mode can be of following types, *fp is the FILE pointer (FILE *fp), which

will hold the reference to the opened (or created) file.

Mode Description

r opens a text file in reading mode

w Opens or create a text file in writing mode.

a opens a text file in append mode

r+ opens a text file in both reading and writing

mode

w+ opens a text file in both reading and writing

mode

a+ opens a text file in both reading and writing

mode

rb opens a binary file in reading mode

wb opens or create a binary file in writing

mode

ab opens a binary file in append mode

Page 87: Course Material for C Programming Language

Course Material for C Programming Language

Page 86

rb+ opens a binary file in both reading and

writing mode

wb+ opens a binary file in both reading and

writing mode

ab+ opens a binary file in both reading and

writing mode

2. Closing a file

The fclose() function is used to close an already opened file.

General Syntax

int fclose( FILE *fp );

Here fclose() function closes the file and returns zero on success, or EOF if there is an

error in closing the file. This EOF is a constant defined in the header file stdio.h.

3. Writing into a file

int fputc( int c, FILE *fp );

The function fputc() writes the character value of the argument c to the output stream

referenced by fp. It returns the written character written on success otherwise EOF if there is

an error. You can use the following functions to write a null-terminated string to a stream.

int fputs( const char *s, FILE *fp );

The function fputs() writes the string s to the output stream referenced by fp. It returns a non-

negative value on success, otherwise EOF is returned in case of any error. You can use

int fprintf(FILE *fp,const char *format, ...) function as well to write

a string into a file.

Make sure you have /tmp directory available. If it is not, then before proceeding, you must

create this directory on your machine.

Example

#include <stdio.h>

main()

{

Page 88: Course Material for C Programming Language

Course Material for C Programming Language

Page 87

FILE *fp;

fp = fopen("/tmp/test.txt", "w+");

fprintf(fp, "This is testing for fprintf...\n");

fputs("This is testing for fputs...\n", fp);

fclose(fp);

}

When the above code is compiled and executed, it creates a new file test.txt in /tmp directory

and writes two lines using two different functions.

4. Reading from a file

int fgetc( FILE * fp );

The fgetc() function reads a character from the input file referenced by fp. The return value is

the character read, or in case of any error, it returns EOF. The following function allows to

read a string from a stream.

char *fgets( char *buf, int n, FILE *fp );

The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It

copies the read string into the buffer buf, appending a null character to terminate the string. If

this function encounters a newline character '\n' or the end of the file EOF before they have

read the maximum number of characters, then it returns only the characters read up to that

point including the new line character. You can also use

int fscanf(FILE *fp, const char *format, ...) function to read strings

from a file, but it stops reading after encountering the first space character.

Example

#include <stdio.h>

main() {

FILE *fp;

char buff[255];

fp = fopen("/tmp/test.txt", "r");

fscanf(fp, "%s", buff);

printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);

Page 89: Course Material for C Programming Language

Course Material for C Programming Language

Page 88

printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);

printf("3: %s\n", buff );

fclose(fp);

}

When the above code is compiled and executed, it reads the file created in the previous

section and produces the following result.

1 : This

2: is testing for fprintf...

3: This is testing for fputs...

Pointer

Pointers in C language is a variable that stores/points the address of another variable. A

Pointer in C is used to allocate memory dynamically i.e. at run time. The pointer variable

might be belonging to any of the data type such as int, float, char, double, short etc.

Syntax

data_type *var_name;

Example

int *p; char *p;

Where, * is used to denote that “p” is pointer variable and not a normal variable.

Key points to remember about pointers in C

Normal variable stores the value whereas pointer variable stores the address of the

variable.

The content of the C pointer always be a whole number i.e. address.

Always C pointer is initialized to null, i.e. int *p = null.

The value of null pointer is 0.

& symbol is used to get the address of the variable.

* symbol is used to get the value of the variable that the pointer is pointing to.

Page 90: Course Material for C Programming Language

Course Material for C Programming Language

Page 89

If a pointer in C is assigned to NULL, it means it is pointing to nothing.

Two pointers can be subtracted to know how many elements are available between

these two pointers.

But, Pointer addition, multiplication, division are not allowed.

The size of any pointer is 2 byte (for 16 bit compiler).

Example

/* Source code to demonstrate, handling of pointers in C program */

#include <stdio.h>

int main(){

int* pc;

int c;

c=22;

printf("Address of c:%u\n",&c);

printf("Value of c:%d\n\n",c);

pc=&c;

printf("Address of pointer pc:%u\n",pc);

printf("Content of pointer pc:%d\n\n",*pc);

c=11;

printf("Address of pointer pc:%u\n",pc);

printf("Content of pointer pc:%d\n\n",*pc);

*pc=2;

printf("Address of c:%u\n",&c);

printf("Value of c:%d\n\n",c);

return 0;

}

Output

Address of c: 2686784

Value of c: 22

Address of pointer pc: 2686784

Content of pointer pc: 22

Address of pointer pc: 2686784

Content of pointer pc: 11

Address of c: 2686784

Value of c: 2

Page 91: Course Material for C Programming Language

Course Material for C Programming Language

Page 90

Explanation of program and figure

1. int* pc; creates a pointer pc and int c; creates a normal variable c.

Since pc and c are both not initialized, pointer pc points to either no address or a

random address. Likewise, variable c is assigned an address but contains a

random/garbage value.

2. c=22; assigns 22 to the variable c, i.e.,22 is stored in the memory location of variable

c.

Note that, when printing &c (address of c), we use %u rather than %d since address is

usually expressed as an unsigned integer (always positive).

3. pc=&c; assigns the address of variable to c to the pointer pc.

When printing, you see value of pc is the same as the address of c and the content of

pc (*pc) is 22 as well.

4. c=11; assigns 11 to variable c.

We assign a new value to c to see its effect on pointer pc.

5. Since, pointer pc points to the same address as c, value pointed by pointer pc is 11 as

well.

Printing the address and content of pc shows the updated content as 11.

6. *pc=2; changes the contents of the memory location pointed by pointer pc to 2.

Since the address of pointer pc is same as address of c, value of c also changes to 2.