0% found this document useful (0 votes)
9 views80 pages

C Programming NW

The document provides an overview of C programming, including its history, features, and structure. It covers essential topics such as tokens, data types, and the advantages and limitations of C. Additionally, it includes examples of basic C programs and explains the purpose of various components within the language.

Uploaded by

irshadshekah4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views80 pages

C Programming NW

The document provides an overview of C programming, including its history, features, and structure. It covers essential topics such as tokens, data types, and the advantages and limitations of C. Additionally, it includes examples of basic C programs and explains the purpose of various components within the language.

Uploaded by

irshadshekah4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Raj Computer Academy Vasai West – Manikpur

9321192465
Raj Computer Academy Vasai West – Manikpur – C Programming

1 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

1. Introduction to C Programming

⮚ Facts of c Programming:
In 1988, the American National Standards Institute (ANSI) had formalized the C
language.

C was invented to write UNIX operating system.

C is a successor of 'Basic Combined Programming Language' (BCPL) called B


language.

Linux OS, PHP, and MySQL are written in C.

C has been written in assembly language.

⮚ Uses :
In the beginning, C was used for developing system applications, e.g. :

Database Systems

Language Interpreters

Compilers and Assemblers

Operating Systems

Network Drivers

Word Processors

⮚ Why C is Popular?
One of the early programming languages.

Still, the best programming language to learn quickly.

C language is reliable, simple, and easy to use.

C language is a structured language.

Modern programming concepts are based on C.

It can be compiled on a variety of computer platforms.

Universities preferred to add C programming in their courseware.

2 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

⮚ Feature of C :
C is a robust language with a rich set of built-in functions and operators.

Programs written in C are efficient and fast.

C is highly portable; programs once written in C can be run on other machines with
minor or no modification.

C is a collection of C library functions; we can also create our function and add it to
the C library.

C is easily extensible.

⮚ Advantage
C is the building block for many other programming languages.

Programs written in C are highly portable.

Several standard functions are there (like in-built) that can be used to develop
programs.

C programs are collections of C library functions, and it's also easy to add functions to
the C library.

The modular structure makes code debugging, maintenance, and testing easier.

C does not provide Object Oriented Programming (OOP) concepts.

There are no concepts of Namespace in C.

C does not provide binding or wrapping up of data in a single unit.

C does not provide Constructor and Destructor.

3 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

2. Structure of C

⮚ Documentations (Documentation Section)


⮚ Pre-processor Statements (Link Section)
⮚ Global Declarations (Definition Section)
⮚ The main() function
⮚ Local Declarations
⮚ Program Statements & Expressions
⮚ User Defined Functions

First Program
Writes the words "Hello, World!" on the screen */

#include<stdio.h>

int main()

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

return 0;

Or in different way

Writes the words "Hello, World!" on the screen */

#include<stdio.h>

#include<conio.h>

void main()

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

return 0;

}
Explanation
/* Comments */ : This is a comment block, which is ignored by the compiler. Comment can
be used anywhere in the program to add info about the program or code block, which will be

4 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

helpful for developers to understand the existing code in the future easily.

#include<stdio.h> stdio is standard for input/output, this allows us to use some commands
which includes a file called stdio.h.
or

This is a preprocessor command. That notifies the compiler to include the header file stdio.h
in the program before compiling the source-code.

main() The main() is the main function where program execution begins. Every C program
must contain only one main function.
Or This is the main function, which is the default entry point for every C program and the
void in front of it indicates that it does not return a value.

Braces Two curly brackets "{...}" are used to group all statements.

or

Curly braces which shows how much the main() function has its scope.

printf() It is a function in C, which prints text on the screen.

or

This is another pre-defined function of C which is used to be displayed text string in the
screen.

return 0 At the end of the main function returns value 0.

Execution part
The declaration part is used to declare all variables that will be used within the program.
There needs to be at least one statement in the executable part, and these two parts are
declared within the opening and closing curly braces of the main(). The execution of the
program begins at the opening brace '{' and ends with the closing brace '}'. Also, it has to be
noted that all the statements of these two parts need to be terminated with a semi-colon.

The sub-program section deals with all user-defined functions that are called from the main().
These user-defined functions are declared and usually defined after the main() function.

5 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

The limitations of C programming languages are as follows:


Difficult to debug.

C allows a lot of freedom in writing code, and that is why you can put an empty line or white
space anywhere in the program. And because there is no fixed place to start or end the line, so
it isn't easy to read and understand the program.

C compilers can only identify errors and are incapable of handling exceptions (run-time
errors).

C provides no data protection.

It also doesn't feature the reusability of source code extensively.

6 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

3. Tokens
C Supports Six Types of Tokens:

1. Identifiers
2. Keywords
3. Constants
4. Strings
5. Operators
6. Special Symbols

⮚ Identifiers

Example

int amount;

double totalbalance;

1. An identifier can only have alphanumeric characters (a-z , A-Z , 0-9) (i.e. letters &
digits) and underscore( _ ) symbol.
2. Identifier names must be unique
3. The first character must be an alphabet or underscore.
4. You cannot use a keyword as identifiers.
5. Only the first thirty-one (31) characters are significant.
6. It must not contain white spaces.
7. Identifiers are case-sensitive.

A list of 32 reserved keywords in c language is given below:

Keywords

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue signed void goto

default sizeof volatile for

do if static while

7 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

#include<stdio.h>

int main()

float a, b;

printf("Showing how keywords are used.");

return 0;

In the above program, float and return are keywords. The float is used to declare variables,
and return is used to return an integer type value in this program.

Constants
⮚ C Constants is the most fundamental and essential part of the C programming
language. Constants in C are the fixed values that are used in a program, and its value
remains the same during the entire execution of the program.
⮚ Constants are also called literals.
⮚ Constants can be any of the data types.
⮚ It is considered best practice to define constants using only upper-case names.

8 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

4. data-type

A data-type in C programming is a set of values and is determined to act on those values. C


provides various types of data-types which allow the programmer to select the appropriate
type for the variable to set its value.
The data-type in a programming language is the collection of data with values having fixed
meaning as well as characteristics. Some of them are an integer, floating point, character, etc.
Usually, programming languages specify the range values for given data-type.

C Data Types are used to:

1. Identify the type of a variable when it is declared.


2. Identify the type of the return value of a function.
3. Identify the type of a parameter expected by a function.

ANSI C provides three types of data types:

1. Primary(Built-in) Data Types:


void, int, char, double and float.
2. Derived Data Types:
Array, References, and Pointers.
3. User Defined Data Types:
Structure, Union, and Enumeration.

Just like the name suggests, here, data types refer to the type of data that we are using in a C
program. Whenever we utilise a data type in a C program, we define the variables or
functions used in it. We do so because we must specify the type of data that is in use, so that
the compiler knows exactly what type of data it must expect from the given program.

9 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Purpose of Data Types in C

Data types used in C language refer to an extensive system that we use to declare various
types of functions or variables in a program. Here, on the basis of the type of variable present
in a program, we determine the space that it occupies in storage, along with the way in which
the stored bit pattern will be interpreted.
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
Example of Data Types in C

Let us take a look at an example to understand data types better.


For instance, we may want to utilise some numbers such as 5, 8, 600, or maybe a decimal
point number such as 43.59, 127.368, 271.49, or maybe a text such as “cappuccino”. Then,
the compiler used in C language would handle all of these very differently. Thus, here, we
use different data types for defining what data types we want in the program.
Types of Data Types in C

Here are the five major categories into which data types are divided in C language:

Data Type Example of Data Type

Basic Data Type Floating-point, integer, double, character.

Derived Data Type Union, structure, array, etc.

Enumeration Enums

Void Data Type Empty Value

Bool Type True or False

The basic data types are also known as the primary data types in C programming.

10 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Primary Data Types in C

Here are the five primitive or primary data types that one can find in C programming
language:
1. Integer – We use these for storing various whole numbers, such as 5, 8, 67, 2390, etc.
2. Character – It refers to all ASCII character sets as well as the single alphabets, such as
‘x’, ‘Y’, etc.
3. Double – These include all large types of numeric values that do not come under either
floating-point data type or integer data type.
4. Floating-point – These refer to all the real number values or decimal points, such as 40.1,
820.673, 5.9, etc.
5. Void – This term refers to no values at all. We mostly use this data type when defining the
functions in a program.
Various keywords are used in a program for specifying the data types mentioned above. Here
are the keywords that we use:

Keyword Used Data Type

int Integer

float Floating-point

void Void

char Character

double Double

The size of every data type gets defined in bytes/ bits. Also, these data types are capable of
holding a very wide range of values.
Different Data Type Values

The size of any given data type in a program depends a lot on the type of processor, as well
as the compiler. In simpler words, the size of the data type depends entirely on the computer
on which we run C language along with the version of the C program compiler that we
installed in the computer.

11 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

The int data type can be 4 bytes/ 2 bytes.

Remembering the size of the int data type is very easy. The given size is generally equal to
the length of the word of the program’s execution environment. In other words, int will be 2
bytes or 16 bits in the case of an environment that is 16-bit. However, int will be 4 bytes or
32 bits in case of an environment that is 32-bit.
The char data type is 1 byte.

The size of the char data type is basically 8 bits or 1 byte. No variation would occur with
different compilers and interpreters. It means that the type of compiler or processor used will
have no effect on its size whatsoever.
The double data type is 8 bytes.

The size of the double data type is basically 64 bits or 8 bytes. It is capable of storing values
that are comparatively double the size of the bytes that the float data type can store. This is
the reason why it is known as the double.
When looking at the 64 bits in total, the program has 1 bit for the sake of sign representation,
the exponent uses 11 bits, and it uses the remaining 52 bits for the mantissa.
This data type is capable of holding about 15-17 digits, both after and before the decimal of
the data type.
The float data type is 4 bytes.

The size of the float data type is basically 32 bits or 4 bytes. The float data type is single-
precision in nature, and we use it for holding the decimal values. It helps in the storage of
various large values, but the float is comparatively faster than double. It is because double
works with comparatively much larger data values. Thus, it is slower comparatively.
The void data type is 0 bytes.

Since the void data type has no meaning, it has no size at all.
There is a range of values that come under all of these data types. But before we look into
that, let us take a look at the modifiers that are used in the data types.
Data Type Modifiers in C Programming Language

There are basically four types of modifiers for all data types used in C language. We use
these along with all the basic data types for categorising them further.
For instance, if we say that there is a chocolate bar on the table, the person we are speaking to
will know that a chocolate bar is present on the table. But if we get more specific and say that
there is a dark chocolate bar on the table or a milk chocolate bar on the table, it will become
much more clear and specific, to the person who is listening.
In a very similar manner, the modifiers in C language help in making the primary or primitive
data types much more specific.
Here are a few modifiers:

12 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

● short
● long
● unsigned
● signed
Just like the names suggest here, we use the unsigned and signed modifiers for presenting the
unsigned (only +) and signed (- and +) values in any given data type. Also, the short and long
modifiers cause an effect on the value range of any given data type.
For instance, the long int, short int, unsigned int, signed int, etc., are all very valid data types
in the C programming language.
Now, if we combine all the modifiers mentioned above with the five primitive or primary
data types, then it will result in the formation of the following data types:

Range of Values of C Data Type

The range of all the C language data types are present in the table given below:

Data Type Format Minimal Range Typical Bit


Specifier Size

unsigned char %c 0 to 255 8

char %c -127 to 127 8

signed char %c -127 to 127 8

int %d, %i -32,767 to 32,767 16 or 32

unsigned int %u 0 to 65,535 16 or 32

signed int %d, %i Same as int Same as int


16 or 32

short int %hd -32,767 to 32,767 16

unsigned short %hu 0 to 65,535 16


int

signed short int %hd Same as short int 16

long int %ld, %li -2,147,483,647 to 2,147,483,647 32

long long int %lld, %lli -(263 – 1) to 263 – 1 (It will be added by the 64
C99 standard)

signed long int %ld, %li Same as long int 32

13 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

unsigned long %lu 0 to 4,294,967,295 32


int

unsigned long %llu 264 – 1 (It will be added by the C99 64


long int standard)

%f 1E-37 to 1E+37 along with six digits of the 32


float precisions here

double %lf 1E-37 to 1E+37 along with six digits of the 64


precisions here

long double %Lf 1E-37 to 1E+37 along with six digits of the 80
precisions here

As you can witness in the table given above, the varied ranges and combinations of the
modifiers and data types result in a range of the changing values.
One must utilise the format specifier when they want to print any value of the variable in a
program. They must do it in the printf() statement.
When the value of the Data Type happens to be out of Range

Whenever we try to assign any value to a given data type in a program that is more than the
allowed value range, then the compiler in C language will generate an error.
Let us look at an example to understand this better.
#include <stdio.h>
int main() {
// the maximum value allowed in the signed short int is 32767
signed short int x = 34767;
return 0;
}
The generated output for this program would be:
warning: very large integer value implicitly truncated to signed type [-Woverflow]
signed short int x = 34767;
^
Whenever we use a type modifier even without using any data type, the program sets the int
data type as a form of default data type. Here, signed would refer to a signed int, unsigned
would refer to unsigned int, short would refer to short int, and also, long would refer to long
int.

14 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Meaning of Unsigned as well as Signed

It is basically a bit tricky to understand. But in easier words, the signed modifier would refer
to both the negative and positive values, while the unsigned modifier refers to all of the
positive values.
Whenever a compiler happens to get any numeric value, then it converts that very value of
the program into a binary number. This means it will be a combination of various 1s as well
as 0s. For instance, the binary of 1 is 0001 or 01, the binary value of the number 2 will be
0010, for the number 32767 will be 01111111 11111111, and many more.
When we talk about the signed integers, we use the very first digit starting from the left (in
binary values) or the highest bit of order as the sign flag. The number will be negative
whenever the sign flag is 1. It will, conversely, be positive whenever the sign flag is 0.
And because we use one bit to show if the given number is negative or positive, one less bit
will be representing the number in the program itself. Thus, the range here is very less.
For instance, in the case of a signed int, the binary digit 11111111 11111111 would mean the
number -32,767. Here, the first bit would serve as a sign flag that marks it as a negative
number. The rest of the bits would represent the actual number that is 32767. The very same
binary digit 11111111 11111111 would mean 65,535 in the case of an unsigned int.
Derived Data Types in C

While there are five data types that are primary, various derived data types are also present in
C language that help in storing complex types of data.
Thus, the derived data types are basically primary data types, but these are a bit more grouped
together or twisted, such as a structure, array, pointers, union, etc.
Use of C Data Types

The use of C data type is to define the type of data that we use in a program. Let us take a
look at each of these in detail.
The char Data Type

This data type basically refers to all the character values that get enclosed in single quotes.
Also, this data type ranges from -127 to 127.
As we can see, we can use any of the smaller integer values in a char data type.
For instance,
char status = ‘X’
The float Data Type

We use the float data type for storing all the real numbers. These may have both, the
exponential part as well as the decimal part (or the fraction part). It is basically a single-
precision type of number.

15 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

For instance,
float y = 127.675;
// by using the suffix f or F
float x = 1000.5454F;
Just like the data type int, we can also use the float data type along with various modifiers.
The double Data Type

We store such numbers in a double data type that the float data type can’t store in a program
(bigger than the maximum capacity of the float data type). The double data type is basically a
double-precision type of number. It is capable of holding about 15 to 17 values, both after
and before a decimal point.
For instance,
double y = 424455236424564.24663224663322;

A person will utilise the double data type in a program only when it is needed to store any
such large numbers. Otherwise, we don’t use it as it will make the program very slow.

The int Data Type

We use the int data type for storing the whole numbers that might be values that have no
exponential part or decimal part in the number.
We can store the octal (or base 8), hexadecimal (or base 16), and decimal (or base 10) in the
data types.
For instance,
// a simple int data value
int z = 310;
// a negative data value
z = -4260;
// an unsigned int data value that has a suffix of u or U
int z = 90U;
// a long int data value that has a suffix of l or L
long int long Val = 87500L;
When we use the int data type in a program, then we must use the suffix “u” or “U” so that
the compiler can interpret the available value of the unsigned data type. On the other hand,
we use the suffix “l” or “L” when using a long int value in a program.

16 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Every C compiler supports five primary data types:

void As the name suggests, it holds no value and is generally used for
specifying the type of function or what it returns. If the function has a
void type, it means that the function will not return any value.

int Used to denote an integer type.

char Used to denote a character type.

float, double Used to denote a floating point type.

int *, float *, char Used to denote a pointer type.


*

Three more data types have been added in C99:

_Bool
_Complex
_Imaginary

Declaration of Primary Data Types with Variable Names


After taking suitable variable names, they need to be assigned with a data type. This is how
the data types are used along with variables:

Example:
int age;
char letter;
float height, width;

17 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Derived Data Types


C supports three derived data types:

Data Types Description

Arrays Arrays are sequences of data items having homogeneous values.


They have adjacent memory locations to store values.

References Function pointers allow referencing functions with a particular


signature.

Pointers These are powerful C features which are used to access the memory
and deal with their addresses.

User Defined Data Types


C allows the feature called type definition which allows programmers to define their
identifier that would represent an existing data type.

18 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

There are three such types:

Data Types Description

Structure It is a package of variables of different types under a single


name. This is done to handle data efficiently. "struct"
keyword is used to define a structure.

Union These allow storing various data types in the same memory
location. Programmers can define a union with different
members, but only a single member can contain a value at a
given time. It is used for

Enum Enumeration is a special data type that consists of integral


constants, and each of them is assigned with a specific name.
"enum" keyword is used to define the enumerated data type.

19 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Data Types and Variable Declarations in C


The storage representation and machine instructions differ from machine to machine. sizeof
operator can use to get the exact size of a type or a variable on a particular platform.
Example:

#include <stdio.h>
#include <limits.h>
int main()

int a = 4000; // positive integer data type

float b = 5.2324; // float data type

char c = 'Z'; // char data type

long d = 41657; // long positive integer data type

long e = -21556; // long -ve integer data type

int f = -185; // -ve integer data type

short g = 130; // short +ve integer data type

short h = -130; // short -ve integer data type

double i = 4.1234567890; // double float data type

float j = -3.55; // float data type

printf("Storage size for int is: %d \n", sizeof(int));

printf("Storage size for char is: %d \n", sizeof(char));

return 0;

20 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

4. Expressions
An expression is a formula in which operands are linked to each other by the use of operators
to compute a value. An operand can be a function reference, a variable, an array element or a
constant.
Let's see an example:
1. a-b;
In the above expression, minus character (-) is an operator, and a, and b are the two operands.
There are four types of expressions exist in C:
Competitive questions on Structures in HindiKeep Watching
o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions

Each type of expression takes certain types of operands and uses a specific set of operators.
Evaluation of a particular expression produces a specific value.

For example:
1. x = 9/2 + a-b;
The entire above line is a statement, not an expression. The portion after the equal is an
expression.

Arithmetic Expressions
An arithmetic expression is an expression that consists of operands and arithmetic operators.
An arithmetic expression computes a value of type int, float or double.
When an expression contains only integral operands, then it is known as pure integer expression
when it contains only real operands, it is known as pure real expression, and when it contains
both integral and real operands, it is known as mixed mode expression.
Evaluation of Arithmetic Expressions
The expressions are evaluated by performing one operation at a time. The precedence and
associativity of operators decide the order of the evaluation of individual operations.
When individual operations are performed, the following cases can be happened:
21 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

o When both the operands are of type integer, then arithmetic will be performed, and the
result of the operation would be an integer value. For example, 3/2 will yield 1 not 1.5
as the fractional part is ignored.
o When both the operands are of type float, then arithmetic will be performed, and the
result of the operation would be a real value. For example, 2.0/2.0 will yield 1.0, not 1.
o If one operand is of type integer and another operand is of type real, then the mixed
arithmetic will be performed. In this case, the first operand is converted into a real
operand, and then arithmetic is performed to produce the real value. For example, 6/2.0
will yield 3.0 as the first value of 6 is converted into 6.0 and then arithmetic is
performed to produce 3.0.

Let's understand through an example.


6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)

Evaluation of expression Description of each operation

6*2/( 2+1 * 2/3 +6) +8 * (8/4) An expression is given.

6*2/(2+2/3 + 6) + 8 * (8/4) 2 is multiplied by 1, giving value 2.

6*2/(2+0+6) + 8 * (8/4) 2 is divided by 3, giving value 0.

6*2/ 8+ 8 * (8/4) 2 is added to 6, giving value 8.

6*2/8 + 8 * 2 8 is divided by 4, giving value 2.

12/8 +8 * 2 6 is multiplied by 2, giving value 12.

1+8*2 12 is divided by 8, giving value 1.

1 + 16 8 is multiplied by 2, giving value 16.

17 1 is added to 16, giving value 17.

Relational Expressions
o A relational expression is an expression used to compare two operands.
o It is a condition which is used to decide whether the action should be taken or not.
o In relational expressions, a numeric value cannot be compared with the string value.
o The result of the relational expression can be either zero or non-zero value. Here, the
zero value is equivalent to a false and non-zero value is equivalent to true.

22 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Relational Description
Expression

x%2 = = 0 This condition is used to check whether the x is an even number or not. The
relational expression results in value 1 if x is an even number otherwise
results in value 0.

a!=b It is used to check whether a is not equal to b. This relational expression


results in 1 if a is not equal to b otherwise 0.

a+b = = x+y It is used to check whether the expression "a+b" is equal to the expression
"x+y".

a>=9 It is used to check whether the value of a is greater than or equal to 9.

Let's see a simple example:


#include <stdio.h>
int main()
{

int x=4;
if(x%2==0)
{
printf("The number x is even");
}
else
printf("The number x is not even");
return 0;
}

Output

Logical Expressions
o A logical expression is an expression that computes either a zero or non-zero value.
o It is a complex test condition to take a decision.

23 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Let's see some example of the logical expressions.

Logical Description
Expressions

( x > 4 ) && ( x < 6 ) It is a test condition to check whether the x is greater than 4 and x is less
than 6. The result of the condition is true only when both the conditions
are true.

x > 10 || y <11 It is a test condition used to check whether x is greater than 10 or y is less
than 11. The result of the test condition is true if either of the conditions
holds true value.

! ( x > 10 ) && ( y = It is a test condition used to check whether x is not greater than 10 and y
=2) is equal to 2. The result of the condition is true if both the conditions are
true.

Let's see a simple program of "&&" operator.


#include <stdio.h>
int main()
{
int x = 4;
int y = 10;
if ( (x <10) && (y>5))
{
printf("Condition is true");
}
else
printf("Condition is false");
return 0;
}

Output

24 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Let's see a simple example of "| |" operator


#include <stdio.h>
int main()
{
int x = 4;
int y = 9;
if ( (x <6) || (y>10))
{
printf("Condition is true");
}
else
printf("Condition is false");
return 0;
}
Output

Conditional Expressions
o A conditional expression is an expression that returns 1 if the condition is true otherwise
0.
o A conditional operator is also known as a ternary operator.

The Syntax of Conditional operator


Suppose exp1, exp2 and exp3 are three expressions.
exp1 ? exp2 : exp3
The above expression is a conditional expression which is evaluated on the basis of the value
of the exp1 expression. If the condition of the expression exp1 holds true, then the final
conditional expression is represented by exp2 otherwise represented by exp3.

Let's understand through a simple example.


#include<stdio.h>
#include<string.h>
int main()
{
int age = 25;
char status;
status = (age>22) ? 'M': 'U';
if(status == 'M')
printf("Married");
else
printf("Unmarried");
return 0;
}
Output

25 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

5. C Format specifiers

Format specifiers can be defined as the operators which are used in association with printf()
function for printing the data that is referred by any object or any variable. When a value is
stored in a particular variable, then you cannot print the value stored in the variable
straightforwardly without using the format specifiers. You can retrieve the data that are stored
in the variables and can print them onto the console screen by implementing these format
specifiers in a printf() function.
Format specifiers start with a percentage % operator and followed by a special character for
identifying the type of data.
There are mostly six types of format specifiers that are available in C.

List of format specifiers in C

Format Specifier Description

%d Integer Format Specifier

%f Float Format Specifier

%c Character Format Specifier

%s String Format Specifier

%u Unsigned Integer Format Specifier

%ld Long Int Format Specifier

Integer Format Specifier %d

The %d format specifier is implemented for representing integer values. This is used with
printf() function for printing the integer value stored in the variable.

Syntax: printf("%d",<variable name>);

26 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Float Format Specifier %f

The %f format specifier is implemented for representing fractional values. This is


implemented within printf() function for printing the fractional or floating value stored in the
variable. Whenever you need to print any fractional or floating data, you have to use %f
format specifier.

Syntax: printf("%f", <variable name>);

Character Format Specifier %c

The %c format specifier is implemented for representing characters. This is used with printf()
function for printing the character stored in a variable. When you want to print a character
data, you should incorporate the %c format specifier.

Syntax: printf("%c",<variable name>);

String Format Specifier %s

The %s format specifier is implemented for representing strings. This is used in printf()
function for printing a string stored in the character array variable. When you have to print a
string, you should implement the %s format specifier.

Syntax: printf("%s",<variable name>);

Unsigned Integer Format Specifier %u

The %u format specifier is implemented for fetching values from the address of a variable
having unsigned decimal integer stored in the memory. This is used within printf() function
for printing the unsigned integer variable.

Syntax: printf("%u",<variable name>);

Long Int Format Specifier %ld

The %ld format specifier is implemented for representing long integer values. This is
implemented with printf() function for printing the long integer value stored in the variable.

Syntax: printf("%ld",<variable name>);

27 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

6. Conditional Statement

C conditional statements allow you to make a decision, based upon the result of a condition.
These statements are called Decision Making Statements or Conditional Statements.
So far, we have seen that all set of statements in a C program gets executed sequentially in
the order in which they are written and appear. This occurs when there is no jump-based
statements or repetitions of certain calculations. But some situations may arise where we may
have to change the order of execution of statements depending on some specific conditions.
This involves a kind of decision making from a set of calculations. It is to be noted that C
language assumes any non-zero or non-null value as true and if zero or null, treated as false.
This type of structure requires that the programmers indicate several conditions for evaluation
within a program. The statement(s) will get executed only if the condition becomes true and
optionally, alternative statement or set of statements will get executed if the condition
becomes false.

C languages have such decision-making capabilities within its program by the use of
following the decision making statements:

Conditional Statements in C

If statement
if statement
if-else statement
Nested if-else statement
else if-statement
goto statement
switch statement

Conditional Operator

28 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Example 1 :

#include<stdio.h>

void main()

int a = 15, b = 20;

if (b > a) {

printf("b is greater");

29 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Example 2:

#include<stdio.h>

void main()

int number;

printf("Type a number:");

scanf("%d", &number);

if (number < 0) { // check whether the number is negative number.

number = -number; // If it is a negative then convert it into positive.

printf("The absolute value is %d\n", number);

30 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

If else statements in C : is also used to control the program flow based on some
condition, only the difference is: it's used to execute some statement code block if the
expression is evaluated to true, otherwise executes else statement code block.

#include<stdio.h>

void main()

int a, b;

printf("Please enter the value for a:");

scanf("%d", &a);

printf("\nPlease the value for b:");

scanf("%d", &b);

if (a > b) {

printf("\n a is greater");

} else {

printf("\n b is greater");

31 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Example 2

#include<stdio.h>

void main() {

int num;

printf("Enter the number:");

scanf("%d", &num);

/* check whether the number is negative number */

if (num < 0)

printf("The number is negative.");

else

printf("The number is positive.");

Nested if else statements


Nested if else statements play an important role in C programming, it means you can use
conditional statements inside another conditional statement.

#include<stdio.h>

void main()

int x=20,y=30;

if(x==20)

if(y==30)

printf("value of x is 20, and value of y is 30.");

32 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Execution of the above code produces the following result.

Output:

value of x is 20, and value of y is 30.

#include<stdio.h>

void main()

int a, b;

printf("Please enter the value for a:");

scanf("%d", &a);

printf("\nPlease enter the value for b:");

scanf("%d", &b);

if (a > b)

printf("\n a is greater than b");

else if (b > a)

printf("\n b is greater than a");

else

printf("\n Both are equal");

33 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

C supports a unique form of a statement that is the goto Statement which is used to branch
unconditionally within a program from one point to another. Although it is not a good habit
to use the goto statement in C, there may be some situations where the use of the goto
statement might be desirable.

The goto statement is used by programmers to change the sequence of execution of a C


program by shifting the control to a different part of the same program.

#include<stdio.h>

void main()

int age;

g: //label name

printf("you are Eligible\n");

s: //label name

printf("you are not Eligible");

printf("Enter you age:");

scanf("%d", &age);

if(age>=18)

goto g; //goto label g

else

goto s; //goto label s

} Correct the coding : )

34 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

7. C switch statement

is used when you have multiple possibilities for the if statement. Switch case will allow you
to choose from multiple options. When we compare it to a general electric switchboard, you
will have many switches in the switchboard but you will only select the required switch,
similarly, the switch case allows you to set the necessary statements for the user.

After the end of each block it is necessary to insert a break statement because if the
programmers do not use the break statement, all consecutive blocks of codes will get
executed from every case onwards after matching the case block.

#include<stdio.h>

void main()

int a;

printf("Please enter a no between 1 and 5: ");

scanf("%d",&a);

switch(a)

case 1:

printf("You chose One");

break;

case 2:

printf("You chose Two");

break;

35 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

case 3:

printf("You chose Three");

break;

case 4:

printf("You chose Four");

break;

case 5:

printf("You chose Five.");

break;

default :

printf("Invalid Choice. Enter a no between 1 and 5");

break;

36 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

8. Loop & Control Statements

A computer is the most suitable machine for performing repetitive tasks, and it can perform a
task thousands of times. Every programming language has the feature to instruct to do such
repetitive tasks with the help of certain statements. The process of repeatedly executing a
collection of statements is called looping. The statements get executed many numbers of
times based on the condition. But if the condition is given in such logic that the repetition
continues any number of times with no fixed condition to stop looping those statements, then
this type of looping is called infinite looping.

C supports the following types of loops:

while loops
do-while loops
for loops

C Loop Control Statements


Loop control statements are used to change the normal sequence of execution of the loop.

Statement Syntax Description

break statement break; It is used to terminate loop or switch


statements.

continue continue; It is used to suspend the current loop


statement iteration and transfer control to the
loop for the next iteration.

goto statement goto labelName; It transfers the current program


execution sequence to some other
labelName: statement; part of the program.

37 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

C while loops statement allows to repeatedly run the same block of code until a
condition is met.
while loop is a most basic loop in C programming. while loop has one control condition, and
executes as long the condition is true. The condition of the loop is tested before the body of
the loop is executed, hence it is called an entry-controlled loop.
The basic format of while loop statement is:

#include<stdio.h>

int main ()

/* local variable Initialization */ int n = 1,times=5;

/* while loops execution */ while( n <= times )

printf("C while loops: %d\n", n);

n++;

return 0;

38 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

C do while loops are very similar to the while loops, but it always executes the code
block at least once and furthermore as long as the condition remains true. This is an do while
loop.

#include<stdio.h>

int main ()
{
/* local variable Initialization */ int n = 1,times=5;

/* do loops execution */ do
{
printf("C do while loops: %d\n", n);
n = n + 1;
}while( n <= times );

return 0;
}

C for loops is very similar to a while loops in that it continues to process a block
of code until a statement becomes false, and everything is defined in a single line. The for

loop is also entry-controlled loop.


#include<stdio.h>

int main ()
{
/* local variable Initialization */ int n,times=5;;

/* for loops execution */ for( n = 1; n <= times; n = n + 1 )


{
printf("C for loops: %d\n", n);
}

return 0;
}

39 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

C Program to Demonstrate the Use of Library Functions


Example:
#include<stdio.h>
#include<ctype.h>
#include<math.h>
void main()
{
int i = -10, e = 2, d = 10; //Variables Defining and Assign values
float rad = 1.43;
double d1 = 3.0, d2 = 4.0;

printf("%d\n", abs(i));
printf("%f\n", sin(rad));
printf("%f\n", cos(rad));
printf("%f\n", exp(e));
printf("%d\n", log(d));
printf("%f\n", pow(d1, d2));
}

Program Output:

A scope is a region of the program, and the scope of variables refers to the area of the
program where the variables can be accessed after its declaration.
In C every variable defined in scope. You can define scope as the section or region of a
program where a variable has its existence; moreover, that variable cannot be used or
accessed beyond that region.

40 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

In C programming, variable declared within a function is different from a variable declared


outside of a function. The variable can be declared in three places. These are:

Position Type

Inside a function or a block. local variables

Out of all functions. Global variables

In the function parameters. Formal parameters

Local Variables

Variables that are declared within the function block and can be used only within the function
is called local variables.

Local Scope or Block Scope

A local scope or block is collective program statements put in and declared within a function
or block (a specific region enclosed with curly braces) and variables lying inside such blocks
are termed as local variables. All these locally scoped statements are written and enclosed
within left ({) and right braces (}) curly braces. There's a provision for nested blocks also in
C which means there can be a block or a function within another block or function. So it can
be said that variable(s) that are declared within a block can be accessed within that specific
block and all other inner blocks of that block, but those variables cannot be accessed outside
the block.
Example:
#include <stdio.h>

41 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

int main ()
{
//local variable definition and initialization
int x,y,z;

//actual initialization
x = 20;
y = 30;
z = x + y;

printf ("value of x = %d, y = %d and z = %d\n", x, y, z);

return 0;
}

Global Variables

Variables that are declared outside of a function block and can be accessed inside the
function is called global variables.

Global Scope

Global variables are defined outside a function or any specific block, in most of the case, on
the top of the C program. These variables hold their values all through the end of the program
and are accessible within any of the functions defined in your program.
Any function can access variables defined within the global scope, i.e., its availability stays
for the entire program after being declared.

42 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Example:
#include <stdio.h>

//global variable definition


int z;

int main ()
{
//local variable definition and initialization
int x,y;

//actual initialization
x = 20;
y = 30;
z = x + y;

printf ("value of x = %d, y = %d and z = %d\n", x, y, z);

return 0;
}

Global Variable Initialization

After defining a local variable, the system or the compiler won't be initializing any value to it.
You have to initialize it by yourself. It is considered good programming practice to initialize
variables before using. Whereas in contrast, global variables get initialized automatically by
the compiler as and when defined. Here's how based on datatype; global variables are
defined.

43 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

datatype Initial Default Value

Int 0

Char '\0'

Float 0

Double 0

Pointer NULL

44 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

9. C Arrays
Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.

To create an array, define the data type (like int) and specify the name of the array followed
by square brackets [].

To insert values to it, use a comma-separated list, inside curly braces:

int myNumbers[] = {25, 50, 75, 100};

We have now created a variable that holds an array of four integers.

Access the Elements of an Array


To access an array element, refer to its index number.

Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

This statement accesses the value of the first element [0] in myNumbers:

#include <stdio.h>

int main() {

int myNumbers[] = {25, 50, 75, 100};

printf("%d", myNumbers[0]);

return 0;

45 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Change an Array Element


To change the value of a specific element, refer to the index number:

Example
myNumbers[0] = 33;

#include <stdio.h>

int main() {

int myNumbers[] = {25, 50, 75, 100};

myNumbers[0] = 33;

printf("%d", myNumbers[0]);

return 0;

Loop Through an Array


You can loop through the array elements with the for loop.

The following example outputs all elements in the myNumbers array:

#include <stdio.h>

int main() {

int myNumbers[] = {25, 50, 75, 100};

int i;

for (i = 0; i < 4; i++) {

printf("%d\n", myNumbers[i]);

return 0;

46 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Set Array Size


Another common way to create arrays, is to specify the size of the array, and add elements later:

#include <stdio.h>

int main() {

// Declare an array of four integers:

int myNumbers[4];

// Add elements to it

myNumbers[0] = 25;

myNumbers[1] = 50;

myNumbers[2] = 75;

myNumbers[3] = 100;

printf("%d\n", myNumbers[0]);

return 0;

47 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

10. C Strings
Strings
Strings are used for storing text/characters.

For example, "Hello World" is a string of characters.

Unlike many other programming languages, C does not have a String type to easily create string
variables. However, you can use the char type and create an array of characters to make a string in
C:

char greetings[] = "Hello World!";

Note that you have to use double quotes.

To output the string, you can use the printf() function together with the format specifier %s to tell
C that we are now working with strings:

#include <stdio.h>

int main() {

char greetings[] = "Hello World!";

printf("%s", greetings);

return 0;

Access Strings
Since strings are actually arrays in C, you can access a string by referring to its index number
inside square brackets [].

This example prints the first character (0) in greetings:

#include <stdio.h>

int main() {
48 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

char greetings[] = "Hello World!";

printf("%c", greetings[0]);

return 0;

Modify Strings
To change the value of a specific character in a string, refer to the index number, and use single
quotes:

#include <stdio.h>

int main() {

char greetings[] = "Hello World!";

greetings[0] = 'J';

printf("%s", greetings);

return 0;

Another Way Of Creating Strings


In the examples above, we used a "string literal" to create a string variable. This is the easiest way
to create a string in C.

You should also note that you can to create a string with a set of characters. This example will
produce the same result as the one above:

#include <stdio.h>

int main() {

char greetings[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0'};

char greetings2[] = "Hello World!";

printf("%s\n", greetings);

printf("%s\n", greetings2);

49 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

return 0;

Why do we include the \0 character at the end? This is known as the "null termininating
character", and must be included when creating strings using this method. It tells C that this is the
end of the string.

Differences
The difference between the two ways of creating strings, is that the first method is easier to write,
and you do not have to include the \0 character, as C will do it for you.

You should note that the size of both arrays is the same: They both have 13 characters (space
also counts as a character by the way), including the \0 character:

#include <stdio.h>

int main() {

char greetings[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0'};

char greetings2[] = "Hello World!";

printf("%lu\n", sizeof(greetings));

printf("%lu\n", sizeof(greetings2));

return 0;

50 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

11. C Pointers
Creating Pointers
You learned from the previous chapter, that we can get the memory address of a variable with
the reference operator &:

Example
#include <stdio.h>

int main() {

int myAge = 43;

printf("%d\n", myAge);

printf("%p\n", &myAge);

return 0;

#include <stdio.h>

int main() {

int myAge = 43; // An int variable

int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the address of
myAge

// Output the value of myAge (43)

printf("%d\n", myAge);

// Output the memory address of myAge (0x7ffe5367e044)

printf("%p\n", &myAge);

// Output the memory address of myAge with the pointer (0x7ffe5367e044)

printf("%p\n", ptr);

return 0;

51 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

In the example above, &myAge is also known as a pointer.

A pointer is a variable that stores the memory address of another variable as its value.

A pointer variable points to a data type (like int) of the same type, and is created with
the * operator. The address of the variable you're working with is assigned to the pointer:

#include <stdio.h>

int main() {

int myAge = 43; // An int variable

int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the address of
myAge

// Output the value of myAge (43)

printf("%d\n", myAge);

// Output the memory address of myAge (0x7ffe5367e044)

printf("%p\n", &myAge);

// Output the memory address of myAge with the pointer (0x7ffe5367e044)

printf("%p\n", ptr);

return 0;

Example explained
Create a pointer variable with the name ptr, that points to an int variable (myAge). Note that the
type of the pointer has to match the type of the variable you're working with.

Use the & operator to store the memory address of the myAge variable, and assign it to the pointer.

Now, ptr holds the value of myAge's memory address.

52 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Dereference
In the example above, we used the pointer variable to get the memory address of a variable (used
together with the & reference operator).

However, you can also get the value of the variable the pointer points to, by using the * operator
(the dereference operator):

Example
#include <stdio.h>

int main() {

int myAge = 43; // Variable declaration

int* ptr = &myAge; // Pointer declaration

// Reference: Output the memory address of myAge with the pointer (0x7ffe5367e044)

printf("%p\n", ptr);

// Dereference: Output the value of myAge with the pointer (43)

printf("%d\n", *ptr);

return 0;

Note that the * sign can be confusing here, as it does two different things in our code:

• When used in declaration (int* ptr), it creates a pointer variable.


• When not used in declaration, it act as a dereference operator.

53 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

12. C Functions
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

Functions are used to perform certain actions, and they are important for reusing code: Define
the code once, and use it many times.

Predefined Functions
So it turns out you already know what a function is. You have been using it the whole time while
studying this tutorial!

For example, main() is a function, which is used to execute code, and printf() is a function; used to
output/print text to the screen:

int main() {
printf("Hello World!");
return 0;
}

Create a Function
To create (often referred to as declare) your own function, specify the name of the function,
followed by parentheses () and curly brackets {}:

Syntax
void myFunction() {
// code to be executed
}

Example Explained
• myFunction() is the name of the function
• void means that the function does not have a return value. You will learn more about
return values later in the next chapter
• Inside the function (the body), add code that defines what the function should do

Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be
executed when they are called.

54 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

To call a function, write the function's name followed by two parentheses () and a semicolon ;

In the following example, myFunction() is used to print a text (the action), when it is called:

Example
Inside main, call myFunction():

#include <stdio.h>

// Create a function

void myFunction() {

printf("I just got executed!");

int main() {

myFunction(); // call the function

return 0;

A function can be called multiple times:

void myFunction() {
printf("I just got executed!");
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
// I just got executed!
// I just got executed!
// I just got executed!

55 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

13. C Function Parameters


Parameters and Arguments
Information can be passed to functions as a parameter. Parameters act as variables inside the
function.

Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma:

Syntax
returnType functionName(parameter1, parameter2, parameter3) {
// code to be executed
}

The following function that takes a string of characters with name as parameter. When the
function is called, we pass along a name, which is used inside the function to print "Hello" and
the name of each person.

Example
void myFunction(char name[]) {
printf("Hello %s\n", name);
}

int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}

// Hello Liam
// Hello Jenny
// Hello Anja

56 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Multiple Parameters
Inside the function, you can add as many parameters as you want:

Example
void myFunction(char name[], int age) {
printf("Hello %s. You are %d years old.\n", name, age);
}

int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}

// Hello Liam. You are 3 years old.


// Hello Jenny. You are 14 years old.
// Hello Anja. You are 30 years old.

Return Values
The void keyword, used in the previous examples, indicates that the function should not return a
value. If you want the function to return a value, you can use a data type (such as int or float, etc.)
instead of void, and use the return keyword inside the function:

Example
int myFunction(int x) {
return 5 + x;
}

int main() {
printf("Result is: %d", myFunction(3));

return 0;
}

// Outputs 8 (5 + 3)

57 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

This example returns the sum of a function with two parameters:

Example
int myFunction(int x, int y) {
return x + y;
}

int main() {
printf("Result is: %d", myFunction(5, 3));

return 0;
}

// Outputs 8 (5 + 3)

C Function Declaration and Definition


Function Declaration and Definition
You just learned from the previous chapters that you can create and call a function it the
following way:

Example
// Create a function
void myFunction() {
printf("I just got executed!");
}

int main() {
myFunction(); // call the function
return 0;
}

A function consist of two parts:

• Declaration: the function's name, return type, and parameters (if any)
• Definition: the body of the function (code to be executed)

void myFunction() { // declaration


// the body of the function (definition)
}

For code optimization, it is recommended to separate the declaration and the definition of the
function.

58 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

You will often see C programs that have function declaration above main(), and function
definition below main(). This will make the code better organized and easier to read:

Example
// Function declaration
void myFunction();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction() {
printf("I just got executed!");
}

59 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

14. C Recursion
Recursion
Recursion is the technique of making a function call itself. This technique provides a way to
break complicated problems down into simple problems which are easier to solve. Recursion may
be a bit difficult to understand. The best way to figure out how it works is to experiment with it.

Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more complicated.
In the following example, recursion is used to add a range of numbers together by breaking it
down into the simple task of adding two numbers:

Example
int sum(int k);

int main() {
int result = sum(10);
printf("%d", result);
return 0;
}

int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers smaller
than k and returns the result. When k becomes 0, the function just returns 0. When running, the
program follows these steps:

10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0

Since the function does not call itself when k is 0, the program stops there and returns the result.

60 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

15. C Math Functions


Math Functions
There is also a list of math functions available, that allows you to perform mathematical tasks on
numbers.

To use them, you must include the math.h header file in your program:

#include <math.h>

Square Root
To find the square root of a number, use the sqrt() function:

Example
#include <stdio.h>

#include <math.h>

int main() {

printf("%f", sqrt(16));

return 0;

Round a Number
The ceil() function rounds a number upwards to its nearest integer, and the floor() method rounds a
number downwards to its nearest integer, and returns the result:

Example
printf("%f", ceil(1.4));
printf("%f", floor(1.4));

61 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Power
The pow() function returns the value of x to the power of y (xy):

Example
printf("%f", pow(4, 3));

Other Math Functions


A list of other popular math functions (from the <math.h> library) can be found in the table below:

Function Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x

asin(x) Returns the arcsine of x

atan(x) Returns the arctangent of x

cbrt(x) Returns the cube root of x

cos(x) Returns the cosine of x

exp(x) Returns the value of Ex

sin(x) Returns the sine of x (x is in radians)

tan(x) Returns the tangent of an angle

62 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

16. C Structures (structs)

C Structures (structs)
Structures (also called structs) are a way to group several related variables into one place. Each
variable in the structure is known as a member of the structure.

Unlike an array, a structure can contain many different data types (int, float, char, etc.).

Create a Structure
You can create a structure by using the struct keyword and declare each of its members inside
curly braces:

struct MyStructure { // Structure declaration


int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon

To access the structure, you must create a variable of it.

Use the struct keyword inside the main() method, followed by the name of the structure and then
the name of the structure variable:

Create a struct variable with the name "s1":

struct myStructure {
int myNum;
char myLetter;
};

int main() {
struct myStructure s1;
return 0;
}

Access Structure Members


To access members of a structure, use the dot syntax (.):

Example
// Create a structure called myStructure
struct myStructure {

63 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

int myNum;
char myLetter;
};

int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;

// Assign values to members of s1


s1.myNum = 13;
s1.myLetter = 'B';

// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);

return 0;
}

Now you can easily create multiple structure variables with different values, using just one
structure:

Example
// Create different struct variables
struct myStructure s1;
struct myStructure s2;

// Assign values to different struct variables


s1.myNum = 13;
s1.myLetter = 'B';

s2.myNum = 20;
s2.myLetter = 'C';

What About Strings in Structures?


Remember that strings in C are actually an array of characters, and unfortunately, you can't assign
a value to an array like this:

Example
struct myStructure {
int myNum;
char myLetter;
char myString[30]; // String
};

64 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

int main() {
struct myStructure s1;

// Trying to assign a value to the string


s1.myString = "Some text";

// Trying to print the value


printf("My string: %s", s1.myString);

return 0;
}

An error will occur:

prog.c:12:15: error: assignment to expression with array type

However, there is a solution for this! You can use the strcpy() function and assign the value
to s1.myString, like this:

Example
struct myStructure {
int myNum;
char myLetter;
char myString[30]; // String
};

int main() {
struct myStructure s1;

// Assign a value to the string using the strcpy function


strcpy(s1.myString, "Some text");

// Print the value


printf("My string: %s", s1.myString);

return 0;
}

Result:

My string: Some text

Simpler Syntax
You can also assign values to members of a structure variable at declaration time, in a single line.

Just insert the values in a comma-separated list inside curly braces {}. Note that you don't have to
use the strcpy() function for string values with this technique:

65 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Example
// Create a structure
struct myStructure {
int myNum;
char myLetter;
char myString[30];
};

int main() {
// Create a structure variable and assign values to it
struct myStructure s1 = {13, 'B', "Some text"};

// Print values
printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);

return 0;
}

Note: The order of the inserted values must match the order of the variable types declared in the
structure (13 for int, 'B' for char, etc).

Copy Structures
You can also assign one structure to another.

In the following example, the values of s1 are copied to s2:

Example
struct myStructure s1 = {13, 'B', "Some text"};
struct myStructure s2;

s2 = s1;

Modify Values
If you want to change/modify a value, you can use the dot syntax (.).

And to modify a string value, the strcpy() function is useful again:

Example
struct myStructure {
int myNum;
char myLetter;
char myString[30];

66 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

};

int main() {
// Create a structure variable and assign values to it
struct myStructure s1 = {13, 'B', "Some text"};

// Modify values
s1.myNum = 30;
s1.myLetter = 'C';
strcpy(s1.myString, "Something else");

// Print values
printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);

return 0;
}

Modifying values are especially useful when you copy structure values:

Example
// Create a structure variable and assign values to it
struct myStructure s1 = {13, 'B', "Some text"};

// Create another structure variable


struct myStructure s2;

// Copy s1 values to s2
s2 = s1;

// Change s2 values
s2.myNum = 30;
s2.myLetter = 'C';
strcpy(s2.myString, "Something else");

// Print values
printf("%d %c %s\n", s1.myNum, s1.myLetter, s1.myString);
printf("%d %c %s\n", s2.myNum, s2.myLetter, s2.myString);

Ok, so, how are structures useful?


Imagine you have to write a program to store different information about Cars, such as brand,
model, and year. What's great about structures is that you can create a single "Car template" and
use it for every cars you make. See below for a real life example.

67 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Real Life Example


Use a structure to store different information about Cars:

Example
struct Car {
char brand[50];
char model[50];
int year;
};

int main() {
struct Car car1 = {"BMW", "X5", 1999};
struct Car car2 = {"Ford", "Mustang", 1969};
struct Car car3 = {"Toyota", "Corolla", 2011};

printf("%s %s %d\n", car1.brand, car1.model, car1.year);


printf("%s %s %d\n", car2.brand, car2.model, car2.year);
printf("%s %s %d\n", car3.brand, car3.model, car3.year);

return 0;
}

68 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

17. C File handling


C files I/O functions handle data on a secondary storage device, such as a hard disk.
C can handle files as Stream-oriented data (Text) files, and System oriented data
(Binary) files.
Stream-oriented The data is stored in the same manner as it appears on the screen. The I/O
data files operations like buffering, data conversions, etc. take place automatically.
System-oriented System-oriented data files are more closely associated with the OS and data stored
data files in memory without converting into text format.

C File Operations
Five major operations can be performed on file are:

• Creation of a new file.


• Opening an existing file.
• Reading data from a file.
• Writing data in a file.
• Closing a file.

Steps for Processing a File

• Declare a file pointer variable.


• Open a file using fopen() function.
• Process the file using the suitable function.
• Close the file using fclose() function.
To handling files in C, file input/output functions available in the stdio library are:
Function Uses/Purpose
fopen Opens a file.
fclose Closes a file.
getc Reads a character from a file
putc Writes a character to a file
getw Read integer
putw Write an integer
fprintf Prints formatted output to a file
fscanf Reads formatted input from a file
fgets Read string of characters from a file
fputs Write string of characters to file
feof Detects end-of-file marker in a file

69 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

1.C fopen
C fopen is a C library function used to open an existing file or create a new file.

The basic format of fopen is:

Syntax:
FILE *fopen( const char * filePath, const char * mode );

Parameters

• filePath: The first argument is a pointer to a string containing the name of the file to
be opened.
• mode: The second argument is an access mode.

C fopen() access mode can be one of the following values:

Mode Description
r Opens an existing text file.
w Opens a text file for writing if the file doesn't exist then a new file is created.
a Opens a text file for appending(writing at the end of existing file) and create the file if it
does not exist.
r+ Opens a text file for reading and writing.
w+ Open for reading and writing and create the file if it does not exist. If the file exists then
make it blank.
a+ Open for reading and appending and create the file if it does not exist. The reading will start
from the beginning, but writing can only be appended.

Return Value
C fopen function returns NULL in case of a failure and returns a FILE stream pointer on
success.

Example:
#include<stdio.h>

int main()
{
FILE *fp;
fp = fopen("fileName.txt","w");
return 0;
}

• The above example will create a file called fileName.txt.


• The w means that the file is being opened for writing, and if the file does not exist
then the new file will be created.

70 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

2.fclose()
fclose() function is C library function and it's used to releases the memory stream, opened
by fopen() function.

The basic format of fclose is:

Syntax:
int fclose( FILE * stream );

Return Value
C fclose returns EOF in case of failure and returns 0 on success.

Example:
#include<stdio.h>

int main()
{
FILE *fp;
fp = fopen("fileName.txt","w");
fprintf(fp, "%s", "Sample Texts");
fclose(fp);
return 0;
}

• The above example will create a file called fileName.txt.


• The w means that the file is being opened for writing, and if the file does not exist
then the new file will be created.
• The fprintf function writes Sample Texts text to the file.
• The fclose function closes the file and releases the memory stream.

3.getc()
getc() function is the C library function, and it's used to read a character from a file that has
been opened in read mode by fopen() function.

Syntax:
int getc( FILE * stream );

Return Value

• getc() function returns the next requested object from the stream on success.
• Character values are returned as an unsigned char cast to an int or EOF on the end of
the file or error.
• The function feof() and ferror() to distinguish between end-of-file and error must be
used.

Example:
#include<stdio.h>

71 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

int main()
{
FILE *fp = fopen("fileName.txt", "r");
int ch = getc(fp);
while (ch != EOF)
{
//To display the contents of the file on the screen
putchar(ch);
ch = getc(fp);
}

if (feof(fp))
printf("\n Reached the end of file.");
else
printf("\n Something gone wrong.");
fclose(fp);

getchar();
return 0;
}

4.putc()
putc() function is C library function, and it's used to write a character to the file. This
function is used for writing a single character in a stream along with that it moves forward the
indicator's position.

Syntax:
int putc( int c, FILE * stream );
Example:
int main (void)
{
FILE * fileName;
char ch;
fileName = fopen("anything.txt","wt");
for (ch = 'D' ; ch <= 'S' ; ch++) {
putc (ch , fileName);
}
fclose (fileName);
return 0;
}

72 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

5.C fprintf
C fprintf function pass arguments according to the specified format to the file indicated by
the stream. This function is implemented in file related programs for writing formatted data
in any file.

Syntax:
int fprintf(FILE *stream, const char *format, ...)
Example:
int main (void)
{
FILE *fileName;
fileName = fopen("anything.txt","r");
fprintf(fileName, "%s %s %d", "Welcome", "to", 2018);
fclose(fileName);
return(0);
}

6.C fscanf
C fscanf function reads formatted input from a file. This function is implemented in file
related programs for reading formatted data from any file that is specified in the program.

Syntax:
int fscanf(FILE *stream, const char *format, ...)
Its return the number of variables that are assigned values, or EOF if no assignments could be
made.

Example:
int main()
{
char str1[10], str2[10];
int yr;
FILE* fileName;
fileName = fopen("anything.txt", "w+");
fputs("Welcome to", fileName);
rewind(fileName);
fscanf(fileName, "%s %s %d", str1, str2, &yr);
printf("----------------------------------------------- \n");
printf("1st word %s \t", str1);
printf("2nd word %s \t", str2);
printf("Year-Name %d \t", yr);
fclose(fileName);
return (0);
}

73 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

7.C fgets
C fgets function is implemented in file related programs for reading strings from any
particular file. It gets the strings 1 line each time.

Syntax:
char *fgets(char *str, int n, FILE *stream)
Example:
void main(void)
{
FILE* fileName;
char ch[100];
fileName = fopen("anything.txt", "r");
printf("%s", fgets(ch, 50, fileName));
fclose(fileName);
}

• On success, the function returns the same str parameter


• C fgets function returns a NULL pointer in case of a failure.
• C fputs function is implemented in file related programs for writing string to any
particular file.
• Syntax:
• int fputs(const char *str, FILE *stream)
• Example:
• #include<stdio.h>
• int main()
• {
• FILE *fp;
• fp = fopen("fileName.txt","w");

• fputs("This is a sample text file.", fp);
• fputs("This file contains some sample text data.", fp);

• fclose(fp);
• return 0;
• }
• In this function returns non-negative value, otherwise returns EOF on error.

74 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

8.EOF
EOF stands for End of File. The function getc() returns EOF, on success..

Here is an example of EOF in C language,

Let’s say we have “new.txt” file with the following content.

This is demo!

This is demo!

Now, let us see the example.

Example

#include <stdio.h>

int main() {

FILE *f = fopen("new.txt", "r");

int c = getc(f);

while (c != EOF) {

putchar(c);

c = getc(f);

fclose(f);

getchar();

return 0;

Output

This is demo!

75 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

This is demo!

In the above program, file is opened by using fopen(). When integer variable c is not equal to
EOF, it will read the file.

getc()

It reads a single character from the input and return an integer value. If it fails, it returns EOF.

Here is the syntax of getc() in C language,

int getc(FILE *stream);

Here is an example of getc() in C language,

Let’s say we have “new.txt” file with the following content −

This is demo!

This is demo!

Now, let us see the example.

Example

#include <stdio.h>

int main() {

FILE *f = fopen("new.txt", "r");

int c = getc(f);

while (c != EOF) {

putchar(c);

c = getc(f);

fclose(f);

76 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

getchar();

return 0;

Output

This is demo!

This is demo!

In the above program, file is opened by using fopen(). When integer variable c is not equal to
EOF, it will read the file. The function getc() is reading the characters from the file.

FILE *f = fopen("new.txt", "r");

int c = getc(f);

while (c != EOF) {

putchar(c);

c = getc(f);

feof()

The function feof() is used to check the end of file after EOF. It tests the end of file indicator.
It returns non-zero value if successful otherwise, zero.

Here is the syntax of feof() in C language,

int feof(FILE *stream)

Here is an example of feof() in C language,

Let’s say we have “new.txt” file with the following content −

This is demo!

This is demo!

77 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

Now, let us see the example.

Example

#include <stdio.h>

int main() {

FILE *f = fopen("new.txt", "r");

int c = getc(f);

while (c != EOF) {

putchar(c);

c = getc(f);

if (feof(f))

printf("\n Reached to the end of file.");

else

printf("\n Failure.");

fclose(f);

getchar();

return 0;

Output

This is demo!

This is demo!

Reached to the end of file.

78 | Page
Raj Computer Academy Vasai West – Manikpur – C Programming

In the above program, In the above program, file is opened by using fopen(). When integer
variable c is not equal to EOF, it will read the file. The function feof() is checking again that
pointer has reached to the end of file or not.

FILE *f = fopen("new.txt", "r");

int c = getc(f);

while (c != EOF) {

putchar(c);

c = getc(f);

if (feof(f))

printf("\n Reached to the end of file.");

else

printf("\n Failure.");

79 | Page

You might also like