0% found this document useful (0 votes)
2 views82 pages

C Programming Complete Notes

Uploaded by

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

C Programming Complete Notes

Uploaded by

Namwel Miinda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

INTRODUCTION

Think about some of the different ways that people use computers.

In school, students use computers for tasks such as

● writing papers,
● searching for articles,
● sending email, and
● participating in online classes.

At work, people use computers to


● analyse data,
● make presentations,
● conduct business transactions,
● communicate with customers and co-workers,
● control machines in manufacturing facilities,
● and do many other things.

At home, people use computers for tasks such as

● paying bills,
● shopping online,
● communicating with friends and family,
● and playing computer games.
● And don’t forget that cell phones, iPods®, Blackberries®, car navigation systems, and
many other devices are computers too.

The uses of computers are almost limitless in our everyday lives. Computers can do such a
wide variety of things because they can be programmed.

This means that computers are not designed to do just one job, but to do any job that their
programs tell them to do. A program is a set of instructions that a computer follows to
perform a task.

For example, Figure 1-1 shows screens from two commonly used programs, Microsoft Word
and Adobe Photoshop. Microsoft Word is a word processing program that allows you to
create, edit, and print documents with your computer. Adobe Photoshop is an image editing
program that allows you to work with graphic images, such as photos taken with your digital
camera.
● Programs are commonly referred to as software. Software is essential to a computer
because it controls everything the computer does.

All of the software that we use to make our computers useful is created by individuals
working as programmers or software developers. A programmer, or software developer, is a
person with the training and skills necessary to design, create, and test computer programs.
Computer programming is an exciting and rewarding career.

Today, you will find programmers’ work used in business, medicine, government, law
enforcement, agriculture, academics, entertainment, and many other fields

What is programming?

● Programming is writing computer code to create a program, to solve a problem.


● To tell a computer to do something, a program must be written to tell it exactly what
to do and how to do it.

What is a programming language?

A programming language is an artificial language that a computer understands. The


language is made up of series of statements that fit together to form instructions. These
instructions tell a computer what to do.

There are many different programming languages, some more complicated and complex
than others. Among the most popular languages are:

● Python
● Java
● C++
● BASIC
● Scratch
● C
Different languages work in different ways. For example, in Python all instructions are
written in lowercase, but in BASIC they tend to be written in uppercase. -SYNTAX OR
GRAMMATICAL RULES

Programming is writing computer code to create a program, in order to solve a problem.


Programs consist of a series of instructions to tell a computer exactly what to do and how to
do it.

What is a program?

Programs are made up of statements that the programming language knows and
understands.

Just as words are put together to form a sentence, a program puts one or more statements
together to form an instruction. Each statement tells the computer to perform a specific
task, and the instructions tell a computer what to do.

Statements

Different programming languages use different statements. A few of these are listed in this
table:

Statement Purpose

Printf Output a message on the screen

Scanf Get data from the user

if…else A decision

While A loop controlled by a decision

For A loop controlled by a counter

WHAT IS C:

C is a mid-level structured oriented programming language, used in general-purpose


programming, developed by Dennis Ritchie at AT&T Bell Labs, the USA, between 1969 and
1973. to develop the UNIX operating system. C is the most widely used computer language.
It keeps fluctuating at number one scale of popularity along with Java programming
language, which is also equally popular and most widely used among modern software
programmers
Some Facts about C Language

● 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 of c language

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

C HAS BECOME POPULAR BECAUSE OF THE FOLLOWING REASONS

● 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

FEATURES OF C LANGUAGE

● 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.

ADVANTAGES OF C

● 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.

DISADVATAGES OF C

● 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

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.

● It does not provide strict data type checking (for example, an integer value can be passed for
floating datatype).

HISTORY OF THEC LANGUAGE

It is good to learn about the history of C programming. C was developed and written
by Dennis M. Ritchie in the year 1972, and hence he is known as the founder of C. C
programming language was developed to overcome the difficulties found in older
programming languages such as BCPL, BASIC, B, etc.
History of Programming Languages and C
Here are the lists of programming languages that were developed with or before C:
Programming Language Development Year

Regional Assembly Language 1951

Autocode 1952

IPL (forerunner to LISP) 1954

FLOW-MATIC (led by COBOL) 1955

FORTRAN (First compiler) 1957

COMTRAN (precursor to COBOL) 1957

LISP 1958

ALGOL 58 1958

FACT (forerunner to COBOL) 1959

COBOL 1959

RPG 1959

APL 1962

Simula 1962

SNOBOL 1962

CPL (forerunner to C) 1963

Speakeasy (computational environment) 1964

BASIC 1964

PL/I 1964

JOSS 1966

BCPL (forerunner to C) 1967

How a Program Works


When a CPU executes the instructions in a program, it is engaged in a process that is known
as the fetch-decode-execute cycle. This cycle, which consists of three steps, is repeated for
each instruction in the program. The steps are:

1. Fetch A program is a long sequence of machine language instructions. The first step of the
cycle is to fetch, or read, the next instruction from memory into the CPU.

2. Decode A machine language instruction is a binary number that represents a command


that tells the CPU to perform an operation. In this step the CPU decodes the instruction that
was just fetched from memory, to determine which operation it should perform.

3. Execute The last step in the cycle is to execute, or perform, the operation

GENERATION OF PROGRAMMING LANGUAGES

From Machine Language to Assembly Language

2ND GENERATION PROGRAMING LANGUAGE: Assembly language programs cannot be


executed by the CPU, however. The CPU only understands machine language, so a special
program known as an assembler is used to translate an assembly language program to a
machine language program. This process is shown in Figure 1-18. The machine language
program that is created by the assembler can then be executed by the CPU

3RD GENERATION PROGRAMMING LANGUAGE: High-Level Languages Although assembly


language makes it unnecessary to write binary machine language instructions, it is not
without difficulties. Assembly language is primarily a direct substitute for machine language,
and like machine language, it requires that you know a lot about the CPU.

Assembly language also requires that you write a large number of instructions for even the
simplest program. Because assembly language is so close in nature to machine language, it
is referred to as a low-level language.

In the 1950s, a new generation of programming languages known as high-level languages


began to appear. A high-level language allows you to create powerful and complex
programs without knowing how the CPU works, and without writing large numbers of low-
level instructions. I

n addition, most high-level languages use words that are easy to understand. For example, if
a programmer were using COBOL (which was one of the early high-level languages created
in the 1950s), he or she would write the following instruction to display the message Hello
world on the computer screen:

DISPLAY "Hello world"

Python is a modern, high-level programming language that we will use in this book. In
Python you would display the message Hello world with the following instruction:

print 'Hello world'

Doing the same thing in assembly language would require several instructions, and an
intimate knowledge of how the CPU interacts with the computer’s output device. As you can
see from this example, high-level languages allow programmers to concentrate on the tasks
they want to perform with their programs rather than the details of how the CPU will
execute those programs.

Since the 1950s, thousands of high-level languages have been created. Table 1-1 lists several
of the more well-known languages
Compilers and Interpreters

Because the CPU understands only machine language instructions, programs that are
written in a high-level language must be translated into machine language. Depending on
the language that a program has been written in, the programmer will use either a compiler
or an interpreter to make the translation.

A compiler is a program that translates a high-level language program into a separate


machine language program. The machine language program can then be executed any time
it is needed. This is shown in Figure 1-19. As shown in the figure, compiling and executing
are two different processes

The Python language uses an interpreter, which is a program that both translates and
executes the instructions in a high-level language program. As the interpreter reads each
individual instruction in the program, it converts it to machine language instructions and
then immediately executes them. This process repeats for every instruction in the program.
This process is illustrated in Figure 1-20. Because interpreters combine translation and
execution, they typically do not create separate machine language programs.
The statements that a programmer writes in a high-level language are called source code, or
simply code.

Typically, the programmer types a program’s code into a text editor and then saves the code
in a file on the computer’s disk.

Next, the programmer uses a compiler to translate the code into a machine language
program, or an interpreter to translate and execute the code.

If the code contains a syntax error, however, it cannot be translated. A syntax error is a
mistake such as a misspelled key word, a missing punctuation character, or the incorrect use
of an operator.

When this happens the compiler or interpreter displays an error message indicating that the
program contains a syntax error.

The programmer corrects the error and then attempts once again to translate the program.

Categories of Programming Languages

Technical aspects of languages will consider linguistic structure, expressive features,


possibility of efficient implementation, direct support for certain programming models, and
similar concerns. Sone examples:

● Machine languages, that are interpreted directly in hardware

● Assembly languages, that are thin wrappers over a corresponding machine language

● High-level languages, that are anything machine-independent


● System languages, that are designed for writing low-level tasks, like memory and
process management

● Scripting languages, that are generally extremely high-level and powerful

● Domain-specific languages, that are used in highly special-purpose areas only

● Visual languages, that are non-text based

Program Development Life Cycle


When we want to develop a program using any programming language, we follow a
sequence of steps. These steps are called phases in program development. The program
development life cycle is a set of steps or phases that are used to develop a program in any
programming language.
Generally, the program development life cycle contains 6 phases, they are as follows….

● Problem Definition
● Problem Analysis
● Algorithm Development
● Coding & Documentation
● Testing & Debugging
● Maintenance
1. Problem Definition
In this phase, we define the problem statement and we decide the boundaries of the
problem. In this phase we need to understand the problem statement, what is our
requirement, what should be the output of the problem solution. These are defined in this
first phase of the program development life cycle.

2. Problem Analysis
In phase 2, we determine the requirements like variables, functions, etc. to solve the
problem. That means we gather the required resources to solve the problem defined in the
problem definition phase. We also determine the bounds of the solution.

3. Algorithm Development
During this phase, we develop a step by step procedure to solve the problem using the
specification given in the previous phase. This phase is very important for program
development. That means we write the solution in step by step statements.

4. Coding & Documentation


This phase uses a programming language to write or implement the actual programming
instructions for the steps defined in the previous phase. In this phase, we construct the
actual program. That means we write the program to solve the given problem using
programming languages like C, C++, Java, etc.,

5. Testing & Debugging


During this phase, we check whether the code written in the previous step is solving the
specified problem or not. That means we test the program whether it is solving the problem
for various input data values or not. We also test whether it is providing the desired output
or not.

6. Maintenance
During this phase, the program is actively used by the users. If any enhancements found in
this phase, all the phases are to be repeated to make the enhancements. That means in this
phase, the solution (program) is used by the end-user. If the user encounters any problem
or wants any enhancement, then we need to repeat all the phases from the starting, so that
the encountered problem is solved or enhancement is added.

C - Program Structure

Before we study the basic building blocks of the C programming language, let us look at a
bare minimum C program structure so that we can take it as a reference in the upcoming
chapters.

Hello World Example

A C program basically consists of the following parts −

● Pre-processor Commands
● Functions
● Variables
● Statements & Expressions
● Comments
Let us look at a simple code that would print the words "Hello World" −
Live Demo
#include <stdio.h>

int main() {
/* my first program in C */
printf("Hello, World! \n");

return 0;
}
Let us take a look at the various parts of the above program −
● The first line of the program #include <stdio.h> is a pre-processor command, which
tells a C compiler to include stdio.h file before going to actual compilation.
● The next line int main() is the main function where the program execution begins.
● The next line /*...*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So, such lines are called comments in the
program.
● The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.
● The next line return 0; terminates the main() function and returns the value 0.

C - Basic Syntax
You have seen the basic structure of a C program, so it will be easy to understand
other basic building blocks of the C programming language.

Tokens in C
A C program consists of various tokens and a token is either a keyword, an
identifier, a constant, a string literal, or a symbol. For example, the following C
statement consists of five tokens −
printf ("Hello, World! \n");
The individual tokens are −
printf
(
"Hello, World! \n"
)
;

Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual
statement must be ended with a semicolon. It indicates the end of one logical
entity.
Given below are two different statements −
printf ("Hello, World! \n");
return 0;

Comments
Comments are like helping text in your C program and they are ignored by the
compiler. They start with /* and terminate with the characters */ as shown below −
/* my first program in C */
//this is a comment
You cannot have comments within comments and they do not occur within a string
or character literals.

Identifiers
A C identifier is a name used to identify a variable, function, or any other user-
defined item. An identifier starts with a letter A to Z, a to z, or an underscore '_'
followed by zero or more letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is
a case-sensitive programming language. Thus, Manpower and manpower are two
different identifiers in C. Here are some examples of acceptable identifiers −
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal

Keywords
The following list shows the reserved words in C. These reserved words may not be
used as constants or variables or any other identifier names.

Auto Else Long switch

Break Enum register typedef

Case Extern return union

Char Float short unsigned

Const for signed void

continue goto Sizeof volatile

default if Static while


do int Struct _Packed

double

Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank
line, and a C compiler totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters and
comments. Whitespace separates one part of a statement from another and
enables the compiler to identify where one element in a statement, such as int, ends
and the next element begins. Therefore, in the following statement −
//this a variable age
int age;
there must be at least one whitespace character (usually a space) between int and
age for the compiler to be able to distinguish them. On the other hand, in the
following statement −
fruit = apples + oranges; // get the total fruit
no whitespace characters are necessary between fruit and =, or between = and
apples, although you are free to include some if you wish to increase readability.

C - Data Types

Data types in c refer to an extensive system used for declaring variables or


functions of different types. The type of a variable determines how much space
it occupies in storage and how the bit pattern stored is interpreted.
The types in C can be classified as follows −

[Link]. Types & Description

1
Basic Types
They are arithmetic types and are further classified into: (a) integer types and
(b) floating-point types, char .

2
Enumerated types
They are again arithmetic types and they are used to define variables that
can only assign certain discrete integer values throughout the program.

3
The type void
The type specifier void indicates that no value is available.

4
Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union
types and (e) Function types.

The array types and structure types are referred collectively as the aggregate types.
The type of a function specifies the type of the function's return value. We will see
the basic types in the following section, where as other types will be covered in the
upcoming chapters.

Integer Types
The following table provides the details of standard integer types with their storage
sizes and value ranges −

Type Storage size Value range

char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

-32,768 to 32,767 or -2,147,483,648 to


int 2 or 4 bytes
2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 8 bytes or (4bytes for 32 bit OS) -9223372036854775808 to


9223372036854775807

unsigned long 8 bytes 0 to 18446744073709551615


C - Variables
A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and
layout of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C is case-sensitive. Based on the basic types explained
in the previous chapter, there will be the following basic variable types −

[Link]. Type & Description

1
Char
Typically a single octet(one byte). It is an integer type.

2
Int
The most natural size of integer for the machine.

3
Float
A single-precision floating point value.

4
Double
A double-precision floating point value.

5
Void
Represents the absence of type.

C programming language also allows to define various other types of variables,


which we will cover in subsequent chapters like Enumeration, Pointer, Array,
Structure, Union, etc. For this chapter, let us study only basic variable types.

Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type and contains a list of one or
more variables of that type as follows −
type variable list;
Here, type must be a valid C data type including char, int, float, double, bool, or any
user-defined object; and variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;

The line int i, j, k; declares and defines the variables i, j, and k; which instruct the
compiler to create variables named i, j and k of type int.

Variables can be initialized (assigned an initial value) in their declaration. The


initializer consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and
f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are
implicitly initialized with NULL (all bytes have the value 0); the initial value of all
other variables are undefined.

Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a
variable with the given type and name so that the compiler can proceed for further
compilation without requiring the complete detail about the variable. A variable
definition has its meaning at the time of compilation only, the compiler needs actual
variable definition at the time of linking the program.
A variable declaration is useful when you are using multiple files and you define
your variable in one of the files which will be available at the time of linking of the
program. You will use the keyword extern to declare a variable at any place.
Though you can declare a variable multiple time in your C program, it can be
defined only once in a file, a function, or a block of code.

Example
Try the following example, where variables have been declared at the top, but they
have been defined and initialized inside the main function −
Live Demo

#include <stdio.h>

// Variable declaration:
extern int a, b;
extern int c;
extern float f;

int main () {

/* variable definition: */
int a, b;
int c;
float f;

/* actual initialization */
a = 10;
b = 20;

c = a + b;
printf ("value of c: %d \n", c);

f = 70.0/3.0;
printf ("value of f: %f \n", f);

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of c : 30
value of f: 23.333334

C - Constants and Literals

Constants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are enumeration constants
as well.
Constants are treated just like regular variables except that their values cannot be
modified after their definition.

Defining Constants
There are two simple ways in C to define constants −
● Using #define preprocessor.
● Using const keyword.
The #define Preprocessor
Given below is the form to use #define preprocessor to define a constant −
#define identifier value
The following example explains it in detail −
Live Demo

#include <stdio.h>

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

int main() {
int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
printf("%c", NEWLINE);

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50

The const Keyword


You can use const prefix to declare constants with a specific type as follows −
const type variable = value;
The following example explains it in detail −
Live Demo

#include <stdio.h>

int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
printf("%c", NEWLINE);

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
Note that it is a good programming practice to define constants in CAPITALS.
C - Storage Classes

A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program. They precede the type that they modify. We have four
different storage classes in a C program −

● auto
● register
● static
● extern

The auto Storage Class


The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can
only be used within functions, i.e., local variables.

The register Storage Class


The register storage class is used to define local variables that should be stored in
a register instead of RAM. This means that the variable has a maximum size equal
to the register size (usually one word) and can't have the unary '&' operator applied
to it (as it does not have a memory location).
{
register int miles;
}
The register should only be used for variables that require quick access such as
counters. It should also be noted that defining 'register' does not mean that the
variable will be stored in a register. It means that it MIGHT be stored in a register
depending on hardware and implementation restrictions.

The static Storage Class


The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each time it
comes into and goes out of scope. Therefore, making local variables static allows
them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it
causes that variable's scope to be restricted to the file in which it is declared.
In C programming, when static is used on a global variable, it causes only one copy
of that member to be shared by all the objects of its class.
Live Demo

#include <stdio.h>

/* function declaration */
void func(void);

static int count = 5; /* global variable */

main() {

while(count--) {
func();
}

return 0;
}

/* function definition */
void func( void ) {

static int i = 5; /* local static variable */


i++;

printf("i is %d and count is %d\n", i, count);


}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

The extern Storage Class


The extern storage class is used to give a reference of a global variable that is
visible to ALL the program files. When you use 'extern', the variable cannot be
initialized however, it points the variable name at a storage location that has been
previously defined.
When you have multiple files and you define a global variable or function, which will
also be used in other files, then extern will be used in another file to provide the
reference of defined variable or function. Just for understanding, extern is used to
declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files
sharing the same global variables or functions as explained below.
First File: main.c
#include <stdio.h>

int count;
extern void write extern ();

main () {
count = 5;
write extern ();
}
Second File: support.c
#include <stdio.h>

extern int count;

void write extern(void) {


printf ("count is %d\n", count);
}

Here, extern is being used to declare count in the second file, where as it has its
definition in the first file, main.c. Now, compile these two files as follows −
$gcc main.c support.c
It will produce the executable program [Link]. When this program is executed, it
produces the following result −
count is 5
C - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or
logical functions. C language is rich in built-in operators and provides the following
types of operators −

● Arithmetic Operators
● Relational Operators
● Logical Operators
● Assignment Operators
● Misc Operators
We will, in this chapter, look into the way each operator works.

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 −
Show Examples

Operato Description Example


r

+ 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

Relational Operators
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20 then −
Show Examples

Operato Description Example


r

== Checks if the values of two operands are equal or not. If yes, then the (A == B)
condition becomes true. is not
true.

!= Checks if the values of two operands are equal or not. If the values are not (A != B)
equal, then the condition becomes true. is true.

> Checks if the value of left operand is greater than the value of right (A > B)
operand. If yes, then the condition becomes true. is not
true.

< Checks if the value of left operand is less than the value of right operand. If (A < B)
yes, then the condition becomes true. is true.

>= Checks if the value of left operand is greater than or equal to the value of (A >= B)
right operand. If yes, then the condition becomes true. is not
true.

<= Checks if the value of left operand is less than or equal to the value of right (A <= B)
operand. If yes, then the condition becomes true. is true.

Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
Show Examples

Operato Description Example


r

&& Called Logical AND operator. If both the operands are non-zero, then the (A && B)
condition becomes true. is false.

|| Called Logical OR Operator. If any of the two operands is non-zero, then (A || B) is


the condition becomes true. true.

! Called Logical NOT Operator. It is used to reverse the logical state of its !(A &&
B) is
operand. If a condition is true, then Logical NOT operator will make it false. true.

Assignment Operators
The following table lists the assignment operators supported by the C language −
Show Examples

Operato Description Example


r

= Simple assignment operator. Assigns values from right side operands to C=A+B
left side operand will assign
the value
of A + B
to C

+= Add AND assignment operator. It adds the right operand to the left C += A is
operand and assign the result to the left operand. equivalent
to C = C +
A

-= Subtract AND assignment operator. It subtracts the right operand from the C -= A is
left operand and assigns the result to the left operand. equivalent
to C = C -
A

*= Multiply AND assignment operator. It multiplies the right operand with the C *= A is
left operand and assigns the result to the left operand. equivalent
to C = C *
A

/= Divide AND assignment operator. It divides the left operand with the right C /= A is
operand and assigns the result to the left operand. equivalent
to C = C /
A

%= Modulus AND assignment operator. It takes modulus using two operands C %= A is


and assigns the result to the left operand. 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=C&2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is


same as
C=C^2

|= Bitwise inclusive OR and assignment operator. C |= 2 is


same as
C=C|2

Misc Operators ↦ sizeof & ternary


Besides the operators discussed above, there are a few other important operators
including sizeof and? : supported by the C Language.
Show Examples

Operato Description Example


r

sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.

& Returns the address of a variable. &a; returns the actual address of the variable.

* Pointer to a variable. *a;

?: If Condition is true ? then value X : otherwise


Conditional Expression.
value Y

Operators 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.
Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.
Show Examples

Category Operator Associativity

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

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

Multiplicative */% Left to right

Additive +- Left to right

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

C - Input and Output


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.

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.
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 −
$./[Link]
Enter a value: seven 7
You entered: seven 7
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" or "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 ().

Question 1
Write a program that will prompt the user to input any two number. calculate the total and
average and display them out.
#include<stdio.h>
Int main()
{
Int num1, num2, total, avg;
printf(“Enter the first number”);
scanf(“%d”, num1);
printf(“Enter the second number”);
scanf (“%d”, num2);
total=num1+num2;
avg=total/2;
printf(“the total is %d”, total);
printf(“the average is %d”, avg);
return 0;
}
Question 2
Write a program that will prompt the user to input customer number, customer name, item
name, price, quantity, calculate total amount to be paid by the customer.
#include<stdio.h>
Int main()
{
Int customer_no, price, quantity,total_amount;
Char customer_name[20], item_name[20];
printf(“Enter customer name”);
scanf (“%s”, customer_name);
printf(“Enter customer number”);
scanf (“%d”, customer_no);
printf(“Enter item name”);
scanf (“%s”, item_name);
printf(“Enter quantity”);
scanf (“%d”, quantity);
printf(“Enter price”);
scanf (“%d”, price);
total_amount=price* quantity;
printf(“the total is %d”,total_amount);
return 0;
}

QUESTION 3
Write a program will prompt the user to input Employee number, Employee name, basic
salary, compute allowances as 30% of basic salary and deductions as 20% of basic salary.
Finally compute his gross pay and net pay and display the out.
C - Decision Making
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.
Show below is the general form of a typical decision-making structure found in most
of the programming languages −
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.
C programming language provides the following types of decision-making
statements.

[Link] Statement & Description


.

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


statements.

2 if...else statement

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


when the Boolean expression is false.

3 nested if statements

You can use one if or else if statement inside another if or else if statement(s).

4 switch statement

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


values.

5 nested switch statements

You can use one switch statement inside another switch statement(s).

Syntax of

if(condition)

Statements to be executed if the condition evaluates to true

Else

Statements to be executed if the condition evaluates to false

Question1

Write a program that will prompt the user to input his name, subject1, subject2 marks. The
program should calculate his total and average marks and find out whether he has passed or
not.

#include<stdio.h>
Int main()
{
Int num1, num2, total, avg;
Char student_name[20];
printf(“Enter Student name”);
scanf(“%s”, student_name);
printf(“Enter the first number”);
scanf(“%d”, num1);
printf(“Enter the second number”);
scanf (“%d”, num2);
total=num1+num2;
avg=total/2;
printf(“the total is %d”, total);
printf(“the average is %d”, avg);
if(avg>=50)
printf(“PASSED”);
else
printf(“FAILED”);
return 0;
}

Question 2.

Write a program that will prompt the user to input customer name, item name, price, quantity,
calculate the total amount, discount which is 30% if the total amount > 5000 else discount is 0
and display the final bill amount to be paid.

#include<stdio.h>
Int main()
{
Int customer_no, price, quantity,total_amount,discount,bill_amount;
Char customer_name[20], item_name[20];
printf(“Enter customer name”);
scanf (“%s”, customer_name);
printf(“Enter customer number”);
scanf (“%d”, customer_no);
printf(“Enter item name”);
scanf (“%s”, item_name);
printf(“Enter quantity”);
scanf (“%d”, quantity);
printf(“Enter price”);
scanf (“%d”, price);
total_amount=price* quantity;
printf(“the total is %d”,total_amount);
if (total_amount>5000)
discount=0.3*total_amount;
else
discount=0;
bill_amount=total_amount-discount
printf(“the final BILL AMOUNT is %d”,bill_amount);
return 0;
}
Syntax of Nested if else statement:

When an if else statement is present inside the body of another “if” or “else” then this is
called nested if else.
Syntax of Nested if else statement:

if(condition) {
//Nested if else inside the body of "if"
if(condition2) {
//Statements inside the body of nested "if"
}
else {
//Statements inside the body of nested "else"
}
}
else {
//Statements inside the body of "else"
}

Question 3

Do question one and extend it with grade computation based on the following table.

Average Grade

>=70 A

>=60 and <70 B

>=50 and <60 C

>=40 and <50 D

<40 E

Question 4

Do question 2 and extend it with the following discount calculations


Total Amount Discount

>=10000 30%

>=5000 and <10000 20%

<5000 10%

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 −
● Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value
of the entire? expression.
● If Exp1 is false, then Exp3 is evaluated and its value becomes the value of
the expression.
C - Loops
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 −

C programming language provides the following types of loops to handle looping


requirements.

[Link] Loop Type & Description


.

1 while loop

Repeats a statement or group of statements while a given condition is true. It


tests the condition before executing the loop body.

2 for loop

Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

3 do...while loop
It is more like a while statement, except that it tests the condition at the end of the
loop body.

4 nested loops

You can use one or more loops inside any other while, for, or do..while loop.

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.

[Link] Control Statement & Description


.

1 break statement

Terminates the loop or switch statement and transfers execution to the


statement immediately following the loop or switch.

2 continue statement

Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.

3 goto statement

Transfers control to the labeled statement.

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.
#include <stdio.h>

int main () {

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

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.
C - 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 −
● 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.
● Function Name − This is the actual name of the function. The function name
and the parameter list together constitute the function signature.
● 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.
● 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;
}

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.
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 −
Live Demo

#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;
}
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 −

[Link] 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.

By default, C 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.
C - Arrays
Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables. A specific
element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds
to the first element and the highest address to the last element.

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer
constant greater than zero and type can be any valid C data type. For example, to
declare a 10-element array called balance of type double, use this statement −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays
You can initialize an array in C either one by one or using a single statement as
follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
You will create exactly the same array as you did in the previous example.
Following is an example to assign a single element of the array −
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. All
arrays have 0 as the index of their first element which is also called the base index
and the last index of an array will be total size of the array minus 1. Shown below is
the pictorial representation of the array we discussed above −

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the
index of the element within square brackets after the name of the array. For
example −
double salary = balance[9];
The above statement will take the 10th element from the array and assign the value
to salary variable. The following example Shows how to use all the three above
mentioned concepts viz. declaration, assignment, and accessing arrays −
Live Demo

#include <stdio.h>

int main () {

int n[ 10 ]; /* n is an array of 10 integers */


int i,j;

/* initialize elements of array n to 0 */


for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100
*/
}

/* output each array element's value */


for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}

return 0;
}
When the above code is compiled and executed, it produces the following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Arrays in Detail
Arrays are important to C and should need a lot more attention. The following
important concepts related to array should be clear to a C programmer −

[Link] Concept & Description


.

1 Multi-dimensional arrays

C supports multidimensional arrays. The simplest form of the multidimensional


array is the two-dimensional array.

2 Passing arrays to functions

You can pass to the function a pointer to an array by specifying the array's name
without an index.

3 Return array from a function

C allows a function to return an array.

4 Pointer to an array

You can generate a pointer to the first element of an array by simply specifying
the array name, without any index.
C - Pointers
Advertisements

Previous Page
Next Page
Pointers in C are easy and fun to learn. Some C programming tasks are performed
more easily with pointers, and other tasks, such as dynamic memory allocation,
cannot be performed without using pointers. So it becomes necessary to learn
pointers to become a perfect C programmer. Let's start learning them in simple and
easy steps.
As you know, every variable is a memory location and every memory location has
its address defined which can be accessed using ampersand (&) operator, which
denotes an address in memory. Consider the following example, which prints the
address of the variables defined −
Live Demo

#include <stdio.h>

int main () {

int var1;
char var2[10];

printf("Address of var1 variable: %x\n", &var1 );


printf("Address of var2 variable: %x\n", &var2 );

return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6

What are Pointers?


A pointer is a variable whose value is the address of another variable, i.e., direct
address of the memory location. Like any variable or constant, you must declare a
pointer before using it to store any variable address. The general form of a pointer
variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-
name is the name of the pointer variable. The asterisk * used to declare a pointer is
the same asterisk used for multiplication. However, in this statement the asterisk is
being used to designate a variable as a pointer. Take a look at some of the valid
pointer declarations −
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory
address. The only difference between pointers of different data types is the data
type of the variable or constant that the pointer points to.

How to Use Pointers?


There are a few important operations, which we will do with the help of pointers very
frequently. (a) We define a pointer variable, (b) assign the address of a variable to a
pointer and (c) finally access the value at the address available in the pointer
variable. This is done by using unary operator * that returns the value of the variable
located at the address specified by its operand. The following example makes use
of these operations −
Live Demo

#include <stdio.h>

int main () {

int var = 20; /* actual variable declaration */


int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */


printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */


printf("Value of *ip variable: %d\n", *ip );

return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20

NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you
do not have an exact address to be assigned. This is done at the time of variable
declaration. A pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard
libraries. Consider the following program −
Live Demo

#include <stdio.h>

int main () {

int *ptr = NULL;

printf("The value of ptr is : %x\n", ptr );

return 0;
}
When the above code is compiled and executed, it produces the following result −
The value of ptr is 0
In most of the operating systems, programs are not permitted to access memory at
address 0 because that memory is reserved by the operating system. However, the
memory address 0 has special significance; it signals that the pointer is not
intended to point to an accessible memory location. But by convention, if a pointer
contains the null (zero) value, it is assumed to point to nothing.
To check for a null pointer, you can use an 'if' statement as follows −
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */

Pointers in Detail
Pointers have many but easy concepts and they are very important to C
programming. The following important pointer concepts should be clear to any C
programmer −

[Link] Concept & Description


.

1 Pointer arithmetic

There are four arithmetic operators that can be used in pointers: ++, --, +, -
2 Array of pointers

You can define arrays to hold a number of pointers.

3 Pointer to pointer

C allows you to have pointer on a pointer and so on.

4 Passing pointers to functions in C

Passing an argument by reference or by address enable the passed argument to


be changed in the calling function by the called function.

5 Return pointer from functions in C

C allows a function to return a pointer to the local variable, static variable, and
dynamically allocated memory as well.
C - Strings
Advertisements

Previous Page
Next Page
Strings are actually one-dimensional array of characters terminated by
a null character '\0'. Thus a null-terminated string contains the characters that
comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word
"Hello". To hold the null character at the end of the array, the size of the character
array containing the string is one more than the number of characters in the word
"Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as
follows −
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C/C++ −

Actually, you do not place the null character at the end of a string constant. The C
compiler automatically places the '\0' at the end of the string when it initializes the
array. Let us try to print the above mentioned string −
Live Demo

#include <stdio.h>

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
C supports a wide range of functions that manipulate null-terminated strings −

[Link]. Function & Purpose

1
strcpy(s1, s2);
Copies string s2 into string s1.

2
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.

3
strlen(s1);
Returns the length of string s1.

4
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.

6
strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.

The following example uses some of the above-mentioned functions −


Live Demo

#include <stdio.h>
#include <string.h>

int main () {

char str1[12] = "Hello";


char str2[12] = "World";
char str3[12];
int len ;

/* copy str1 into str3 */


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */


strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */


len = strlen(str1);
printf("strlen(str1) : %d\n", len );

return 0;
}
When the above code is compiled and executed, it produces the following result −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
C - Structures
Advertisements

Previous Page
Next Page
Arrays allow to define type of variables that can hold several data items of the same
kind. Similarly structure is another user defined data type available in C that allows
to combine data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your
books in a library. You might want to track the following attributes about each book

● Title
● Author
● Subject
● Book ID

Defining a Structure
To define a structure, you must use the struct statement. The struct statement
defines a new data type, with more than one member. The format of the struct
statement is as follows −
struct [structure tag] {

member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the end of
the structure's definition, before the final semicolon, you can specify one or more
structure variables but it is optional. Here is the way you would declare the Book
structure −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;

Accessing Structure Members


To access any member of a structure, we use the member access operator (.).
The member access operator is coded as a period between the structure variable
name and the structure member that we wish to access. You would use the
keyword struct to define variables of structure type. The following example shows
how to use a structure in a program −
Live Demo

#include <stdio.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main( ) {

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
strcpy( [Link], "C Programming");
strcpy( [Link], "Nuha Ali");
strcpy( [Link], "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( [Link], "Telecom Billing");
strcpy( [Link], "Zara Ali");
strcpy( [Link], "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info */


printf( "Book 1 title : %s\n", [Link]);
printf( "Book 1 author : %s\n", [Link]);
printf( "Book 1 subject : %s\n", [Link]);
printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */


printf( "Book 2 title : %s\n", [Link]);
printf( "Book 2 author : %s\n", [Link]);
printf( "Book 2 subject : %s\n", [Link]);
printf( "Book 2 book_id : %d\n", Book2.book_id);

return 0;
}
When the above code is compiled and executed, it produces the following result −
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

Structures as Function Arguments


You can pass a structure as a function argument in the same way as you pass any
other variable or pointer.
Live Demo

#include <stdio.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

/* function declaration */
void printBook( struct Books book );

int main( ) {

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
strcpy( [Link], "C Programming");
strcpy( [Link], "Nuha Ali");
strcpy( [Link], "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( [Link], "Telecom Billing");
strcpy( [Link], "Zara Ali");
strcpy( [Link], "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info */


printBook( Book1 );
/* Print Book2 info */
printBook( Book2 );

return 0;
}

void printBook( struct Books book ) {

printf( "Book title : %s\n", [Link]);


printf( "Book author : %s\n", [Link]);
printf( "Book subject : %s\n", [Link]);
printf( "Book book_id : %d\n", book.book_id);
}
When the above code is compiled and executed, it produces the following result −
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

Pointers to Structures
You can define pointers to structures in the same way as you define pointer to any
other variable −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer
variable. To find the address of a structure variable, place the '&'; operator before
the structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must
use the → operator as follows −
struct_pointer->title;
Let us re-write the above example using structure pointer.
Live Demo

#include <stdio.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books *book );
int main( ) {

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
strcpy( [Link], "C Programming");
strcpy( [Link], "Nuha Ali");
strcpy( [Link], "C Programming Tutorial");
Book1.book_id = 6495407;

/* book 2 specification */
strcpy( [Link], "Telecom Billing");
strcpy( [Link], "Zara Ali");
strcpy( [Link], "Telecom Billing Tutorial");
Book2.book_id = 6495700;

/* print Book1 info by passing address of Book1 */


printBook( &Book1 );

/* print Book2 info by passing address of Book2 */


printBook( &Book2 );

return 0;
}

void printBook( struct Books *book ) {

printf( "Book title : %s\n", book->title);


printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
When the above code is compiled and executed, it produces the following result −
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

Bit Fields
Bit Fields allow the packing of data in a structure. This is especially useful when
memory or data storage is at a premium. Typical examples include −
● Packing several objects into a machine word. e.g. 1 bit flags can be
compacted.
● Reading external file formats -- non-standard file formats could be read in,
e.g., 9-bit integers.
C allows us to do this in a structure definition by putting :bit length after the variable.
For example −
struct packed_struct {
unsigned int f1:1;
unsigned int f2:1;
unsigned int f3:1;
unsigned int f4:1;
unsigned int type:4;
unsigned int my_int:9;
} pack;
Here, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4-bit type and
a 9-bit my_int.
C automatically packs the above bit fields as compactly as possible, provided that
the maximum length of the field is less than or equal to the integer word length of
the computer. If this is not the case, then some compilers may allow memory
overlap for the fields while others would store the next field in the next word.
C - Input and Output
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.

The Standard Files


C programming treats all the devices as files. So devices such as the display are
addressed in the same way as files and the following three files are automatically
opened when a program executes to provide access to the keyboard and screen.

Standard File File Pointer Device

Standard input stdin Keyboard

Standard output stdout Screen

Standard error stderr Your screen

The file pointers are the means to access the file for reading and writing purpose.
This section explains how to read values from the screen and how to print the result
on 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. 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 −
$./[Link]
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.
NOTE: Though it has been deprecated to use gets() function, Instead of using gets,
you want to use fgets().
#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 −
$./[Link]
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.
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 −
$./[Link]
Enter a value : seven 7
You entered: seven 7
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().

C - File I/O
Advertisements

Previous Page
Next Page
The last chapter explained the standard input and output devices handled by C
programming language. This chapter cover how C programmers can create, open,
close text or binary files for their data storage.
A file represents a sequence of bytes, regardless of it being a text file or a binary
file. C programming language provides access on high level functions as well as low
level (OS level) calls to handle file on your storage devices. This chapter will take
you through the important calls for file management.

Opening Files
You can use the fopen( ) function to create a new file or to open an existing file.
This call will initialize an object of the type FILE, which contains all the information
necessary to control the stream. The prototype of this function call is as follows −
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file, and
access mode can have one of the following values −

[Link] Mode & Description


.

1
r
Opens an existing text file for reading purpose.

2
w
Opens a text file for writing. If it does not exist, then a new file is created. Here
your program will start writing content from the beginning of the file.

3
a
Opens a text file for writing in appending mode. If it does not exist, then a new file
is created. Here your program will start appending content in the existing file
content.

4
r+
Opens a text file for both reading and writing.

5
w+
Opens a text file for both reading and writing. It first truncates the file to zero
length if it exists, otherwise creates a file if it does not exist.

6
a+
Opens a text file for both reading and writing. It creates the file if it does not exist.
The reading will start from the beginning but writing can only be appended.

If you are going to handle binary files, then you will use following access modes
instead of the above mentioned ones −
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

Closing a File
To close a file, use the fclose( ) function. The prototype of this function is −
int fclose( FILE *fp );
The fclose(-) function returns zero on success, or EOF if there is an error in closing
the file. This function actually flushes any data still pending in the buffer to the file,
closes the file, and releases any memory used for the file. The EOF is a constant
defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file,
character by character, or in the form of a fixed length string.

Writing a File
Following is the simplest function to write individual characters to a stream −
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. Try the following example.
Make sure you have /tmp directory available. If it is not, then before proceeding,
you must create this directory on your machine.
#include <stdio.h>

main() {
FILE *fp;

fp = fopen("/tmp/[Link]", "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 [Link] in
/tmp directory and writes two lines using two different functions. Let us read this file
in the next section.

Reading a File
Given below is the simplest function to read a single character 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.
#include <stdio.h>

main() {

FILE *fp;
char buff[255];

fp = fopen("/tmp/[Link]", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );

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


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...


Let's see a little more in detail about what happened here. First, fscanf() read
just This because after that, it encountered a space, second call is for fgets() which
reads the remaining line till it encountered end of line. Finally, the last
call fgets() reads the second line completely.

Binary I/O Functions


There are two functions, that can be used for binary input and output −
size_t fread(void *ptr, size_t size_of_elements, size_t
number_of_elements, FILE *a_file);

size_t fwrite(const void *ptr, size_t size_of_elements, size_t


number_of_elements, FILE *a_file);
Both of these functions should be used to read or write blocks of memories - usually
arrays or structures.

C - Preprocessors
Advertisements

Previous Page
Next Page
The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. In simple terms, a C Preprocessor is just a text substitution
tool and it instructs the compiler to do required pre-processing before the actual
compilation. We'll refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first
nonblank character, and for readability, a preprocessor directive should begin in the
first column. The following section lists down all the important preprocessor
directives −

[Link]. Directive & Description

1
#define
Substitutes a preprocessor macro.

2
#include
Inserts a particular header from another file.

3
#undef
Undefines a preprocessor macro.

4
#ifdef
Returns true if this macro is defined.

5
#ifndef
Returns true if this macro is not defined.

6
#if
Tests if a compile time condition is true.

7
#else
The alternative for #if.

8
#elif
#else and #if in one statement.

9
#endif
Ends preprocessor conditional.

10
#error
Prints error message on stderr.
11
#pragma
Issues special commands to the compiler, using a standardized method.

Preprocessors Examples
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20.
Use #define for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text
to the current source file. The next line tells CPP to get myheader.h from the local
directory and add the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42
It tells the CPP to undefine existing FILE_SIZE and define it as 42.
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.
#ifdef DEBUG
/* Your debugging statements here */
#endif
It tells the CPP to process the statements enclosed if DEBUG is defined. This is
useful if you pass the -DDEBUG flag to the gcc compiler at the time of compilation.
This will define DEBUG, so you can turn debugging on and off on the fly during
compilation.

Predefined Macros
ANSI C defines a number of macros. Although each one is available for use in
programming, the predefined macros should not be directly modified.

[Link]. Macro & Description

1
__DATE__
The current date as a character literal in "MMM DD YYYY" format.

2
__TIME__
The current time as a character literal in "HH:MM:SS" format.

3
__FILE__
This contains the current filename as a string literal.

4
__LINE__
This contains the current line number as a decimal constant.

5
__STDC__
Defined as 1 when the compiler complies with the ANSI standard.

Let's try the following example −


Live Demo

#include <stdio.h>

int main() {

printf("File :%s\n", __FILE__ );


printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("ANSI :%d\n", __STDC__ );

}
When the above code in a file test.c is compiled and executed, it produces the
following result −
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1

Preprocessor Operators
The C preprocessor offers the following operators to help create macros −
The Macro Continuation (\) Operator
A macro is normally confined to a single line. The macro continuation operator (\) is
used to continue a macro that is too long for a single line. For example −
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
The Stringize (#) Operator
The stringize or number-sign operator ( '#' ), when used within a macro definition,
converts a macro parameter into a string constant. This operator may be used only
in a macro having a specified argument or parameter list. For example −
Live Demo

#include <stdio.h>

#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")

int main(void) {
message_for(Carole, Debra);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Carole and Debra: We love you!
The Token Pasting (##) Operator
The token-pasting operator (##) within a macro definition combines two arguments.
It permits two separate tokens in the macro definition to be joined into a single
token. For example −
Live Demo

#include <stdio.h>

#define tokenpaster(n) printf ("token" #n " = %d", token##n)

int main(void) {
int token34 = 40;
tokenpaster(34);
return 0;
}
When the above code is compiled and executed, it produces the following result −
token34 = 40
It happened so because this example results in the following actual output from the
preprocessor −
printf ("token34 = %d", token34);
This example shows the concatenation of token##n into token34 and here we have
used both stringize and token-pasting.
The Defined() Operator
The preprocessor defined operator is used in constant expressions to determine if
an identifier is defined using #define. If the specified identifier is defined, the value is
true (non-zero). If the symbol is not defined, the value is false (zero). The defined
operator is specified as follows −
Live Demo
#include <stdio.h>

#if !defined (MESSAGE)


#define MESSAGE "You wish!"
#endif

int main(void) {
printf("Here is the message: %s\n", MESSAGE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Here is the message: You wish!

Parameterized Macros
One of the powerful functions of the CPP is the ability to simulate functions using
parameterized macros. For example, we might have some code to square a number
as follows −
int square(int x) {
return x * x;
}
We can rewrite above the code using a macro as follows −
#define square(x) ((x) * (x))
Macros with arguments must be defined using the #define directive before they can
be used. The argument list is enclosed in parentheses and must immediately follow
the macro name. Spaces are not allowed between the macro name and open
parenthesis. For example −
Live Demo

#include <stdio.h>

#define MAX(x,y) ((x) > (y) ? (x) : (y))

int main(void) {
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Max between 20 and 10 is 20
C - Header Files
Advertisements

Previous Page
Next Page
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: the files that the programmer writes and the files that comes with your
compiler.
You request to use a header file in your program by including it with the C
preprocessing directive #include, like you have seen inclusion of stdio.h header
file, which comes along with your compiler.
Including a header file is equal to copying the content of the header file but we do
not do it because it will be error-prone and it is not a good idea to copy the content
of a header file in the source files, especially if we have multiple source files in a
program.
A simple practice in C or C++ programs is that we keep all the constants, macros,
system wide global variables, and function prototypes in the header files and
include that header file wherever it is required.
Include Syntax
Both the user and the system header files are included using the preprocessing
directive #include. It has the following two forms −
#include <file>
This form is used for system header files. It searches for a file named 'file' in a
standard list of system directories. You can prepend directories to this list with the -I
option while compiling your source code.
#include "file"
This form is used for header files of your own program. It searches for a file named
'file' in the directory containing the current file. You can prepend directories to this
list with the -I option while compiling your source code.

Include Operation
The #include directive works by directing the C preprocessor to scan the specified
file as input before continuing with the rest of the current source file. The output
from the preprocessor contains the output already generated, followed by the output
resulting from the included file, followed by the output that comes from the text after
the #include directive. For example, if you have a header file header.h as follows −
char *test (void);
and a main program called program.c that uses the header file, like this −
int x;
#include "header.h"

int main (void) {


puts (test ());
}
the compiler will see the same token stream as it would if program.c read.
int x;
char *test (void);

int main (void) {


puts (test ());
}

Once-Only Headers
If a header file happens to be included twice, the compiler will process its contents
twice and it will result in an error. The standard way to prevent this is to enclose the
entire real contents of the file in a conditional, like this −
#ifndef HEADER_FILE
#define HEADER_FILE

the entire header file file


#endif
This construct is commonly known as a wrapper #ifndef. When the header is
included again, the conditional will be false, because HEADER_FILE is defined. The
preprocessor will skip over the entire contents of the file, and the compiler will not
see it twice.

Computed Includes
Sometimes it is necessary to select one of the several different header files to be
included into your program. For instance, they might specify configuration
parameters to be used on different sorts of operating systems. You could do this
with a series of conditionals as follows −
#if SYSTEM_1
# include "system_1.h"
#elif SYSTEM_2
# include "system_2.h"
#elif SYSTEM_3
...
#endif
But as it grows, it becomes tedious, instead the preprocessor offers the ability to
use a macro for the header name. This is called a computed include. Instead of
writing a header name as the direct argument of #include, you simply put a macro
name there −
#define SYSTEM_H "system_1.h"
...
#include SYSTEM_H
SYSTEM_H will be expanded, and the preprocessor will look for system_1.h as if
the #include had been written that way originally. SYSTEM_H could be defined by
your Makefile with a -D option.

You might also like