Introduction to structured programming using C language:
C concepts
C is a general purpose programming language, unlike other languages such as COBOL and
FORTRAN developed for some specific uses. C is designed to work with both software and
hardware. C has in fact been used to develop a variety of software such as:
✓ Operating systems: Unix and Windows.
✓ Application packages: WordPerfect and Dbase.
It was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs.
C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978, Brian Kernighan
and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX applications
programs have been written in C. The C has now become a widely used professional language for
various reasons.
Easy to learn
Structured language
It produces efficient programs.
It can handle low-level activities.
It can be compiled on a variety of computer platforms.
Facts about C
➢ C was invented to write an operating system called UNIX.
➢ C is a successor of B language, which was introduced around 1970.
➢ The language was formalized in 1988 by the American National Standard Institute. (ANSI).
➢ The UNIX OS was totally written in C by 1973.
➢ Today, C is the most widely used and popular System Programming Language.
➢ Most of the state-of-the-art softwares have been implemented using C.
➢ Today's most popular Linux OS and RBDMS MySQL have been written in C.
Why to use C?
C was initially used for system development work, in particular the programs that make up the
operating system. C was adopted as a system development language because it produces code that
runs nearly as fast as code written in assembly language. Some examples of the use of C might be:
Operating Systems Modern Programs
Databases Text Editors
Language Interpreters Language Compilers
Utilities
MERITS OF C LANGUAGE
• C Supports structured programming design features.
It allows programmers to break down their programs into functions. Further it supports the
use of comments, making programs readable and easily maintainable.
• Efficiency
✓ C is a concise language that allows you to say what you mean in a few words.
✓ The final code tends to be more compact and runs quickly.
• Portability
C programs written for one system can be run with little or no modification on other systems.
• Power and flexibility
✓ C has been used to write operating systems such as Unix, Windows.
✓ It has (and still is) been used to solve problems in areas such as physics and engineering.
• Programmer orientation
✓ C is oriented towards the programmer’s needs.
✓ It gives access to the hardware. It lets you manipulate individual bits of memory.
✓ It also has a rich selection of operators that allow you to expand programming capability.
C programming environment
Local Environment Setup
If you want to set up your environment for C programming language, you need the following two
software tools available on your computer, (a) Text Editor and (b) The C Compiler.
Text Editor
This will be used to type your program. Examples of few a editors include Windows Notepad, OS
Edit command, Brief, Epsilon, EMACS, and vim or vi.
The name and version of text editors can vary on different operating systems. For example, Notepad
will be used on Windows, and vim or vi can be used on windows as well as on Linux or UNIX.
The files you create with your editor are called the source files and they contain the program source
codes. The source files for C programs are typically named with the extension ".c".
Before starting your programming, make sure you have one text editor in place and you have enough
experience to write a computer program, save it in a file, compile it and finally execute it.
The C Compiler
The source code written in source file is the human readable source for your program. It needs to be
"compiled", into machine language so that your CPU can actually execute the program as per the
instructions given.
The compiler compiles the source codes into final executable programs. The most frequently used
and free available compiler is the GNU C/C++ compiler; otherwise you can have compilers either
from HP or Solaris if you have the respective operating systems.
C program format
A C program basically consists of the following parts −
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
⎯ Preprocessor Commands: These commands tells the compiler to do preprocessing before doing
actual compilation. Like #include <stdio.h> is a preprocessor command which tells a C compiler to
include stdio.h file before going to actual compilation.
⎯ Functions: are main building blocks of any C Program. Every C Program will have one or more
functions and there is one mandatory function which is called main() function. This function is
prefixed with keyword int which means this function returns an integer value when it exits. This
integer value is retured using return statement.
⎯ The C Programming language provides a set of built-in functions. In the above example printf() is
a C built-in function which is used to print anything on the screen. Check Builtin functionsection
for more detail.
⎯ You will learn how to write your own functions and use them in Using Function session.
⎯ Variables: are used to hold numbers, strings and complex data for manipulation. You will learn
in detail about variables in C Variable Types.
⎯ Statements & Expressions : Expressions combine variables and constants to create new values.
Statements are expressions, assignments, function calls, or control flow statements which make
up C programs.
⎯ Comments: are used to give additional useful information inside a C Program. All the comments
will be put inside /*...*/ as given in the example above. A comment can span through multiple
lines.
Note the followings
• C is a case sensitive programming language. It means in C printf and Printf will have different
meanings.
• C has a free-form line structure. End of each C statement must be marked with a semicolon.
• Multiple statements can be one the same line.
• White Spaces (ie tab space and space bar ) are ignored.
• Statements can continue over multiple lines.
#include <stdio.h>
int main() {
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
Explanation:
⎯ The first line of the program #include <stdio.h> is a preprocessor 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.
Variables in C
Variables are the storage areas in a code that the program can easily manipulate. Every variable in C
language has some specific type- that determines the layout and the size of the memory of the variable,
the range of values that the memory can hold, and the set of operations that one can perform on that
variable.
The name of a variable can be a composition of digits, letters, and also underscore characters. The
name of the character must begin with either an underscore or a letter. In the case of C, the lowercase
and uppercase letters are distinct. It is because C is case-sensitive in nature. Let us look at some more
ways in which we name a variable.
Rules for Naming a Variable in C
We give a variable a meaningful name when we create it. Here are the rules that we must follow when
naming it:
1. The name of the variable must not begin with a digit.
2. A variable name can consist of digits, alphabets, and even special symbols such as an underscore (
_ ).
3. A variable name must not have any keywords, for instance, float, int, etc.
4. There must be no spaces or blanks in the variable name.
5. The C language treats lowercase and uppercase very differently, as it is case sensitive. Usually, we
keep the name of the variable in the lower case.
Let us look at some of the examples,
int var1; // it is correct
int 1var; // it is incorrect – the name of the variable should not start using a number
int my_var1; // it is correct
int my$var // it is incorrect – no special characters should be in the name of the variable
char else; // there must be no keywords in the name of the variable
int my var; // it is incorrect – there must be no spaces in the name of the variable
int COUNT; // it is a new variable
int Count; // it is a new variable
int count; // it is a valid variable name
Data Type of the Variable
We must assign a data type to all the variables that are present in the C language. These define the
type of data that we can store in any variable. If we do not provide the variable with a data type, the
C compiler will ultimately generate a syntax error or a compile-time error.
The data Types present in the C language are float, int, double, char, long int, short int, etc., along
with other modifiers.
Types of Primary/ Primitive Data Types in C Language
The variables can be of the following basic types, based on the name and the type of the variable:
Type of Name Description Uses
Variable
char Character It is a type of integer. It is We use them in the form of single alphabets,
typically one byte (single such as X, r, B, f, k, etc., or for the ASCII
octet). character sets.
int Integer It is the most natural size of We use this for storing the whole numbers,
an integer used in the such as 4, 300, 8000, etc.
machine.
float Floating- It is a floating-point value We use these for indicating the real number
Point that is single precision. values or decimal points, such as 20.8, 18.56,
etc.
double Double It is a floating-point value These are very large-sized numeric values that
that is double precision. aren’t really allowed in any data type that is a
floating-point or an integer.
void Void It represents that there is an We use it to represent the absence of value.
absence of type. Thus, the use of this data type is to define
various functions.
Let us look at a few examples,
// int type variable in C
int marks = 45;
// char type variable in C
char status = ‘G’;
// double type variable in C
double long = 28.338612;
// float type variable in C
float percentage = 82.5;
If we try to assign a variable with an incorrect value of datatype, then the compiler will (most probably)
generate an error- the compile-time error. Or else, the compiler will convert this value automatically
into the intended datatype of the available variable.
Let us look at an example,
#include <stdio.h>
int main() {
// assignment of the incorrect value to the variable
int a = 20.397;
printf(“Value is %d”, a);
return 0;
}
The output generated here will be:
20
As you can already look at this output- the compiler of C will remove the part that is present after the
decimal. It is because the data types are capable of storing only the whole numbers.
We Cannot Change The Data Type
Once a user defines a given variable with any data type, then they will not be able to change the data
type of that given variable in any case.
Let us look at an example,
// the int variable in C
int marks = 20;
float marks; // it generates an error
Variable Definition in C
The variable definition in C language tells the compiler about how much storage it should be creating
for the given variable and where it should create the storage. Basically, the variable definition helps in
specifying the data type. It contains a list of one variable or multiple ones as follows:
type variable_list;
In the given syntax, type must be a valid data type of C that includes w_char, char, float, int, bool,
double, or any object that is user-defined. The variable_list, on the other hand, may contain one or
more names of identifiers that are separated by commas. Here we have shown some of the valid
declarations:
char c, ch;
int p, q, r;
double d;
float f, salary;
Here, the line int p, q, r; defines as well as declares the variables p, q, and r. It instructs the compiler
to create three variables- named p, q, and r- of the type int.
We can initialize the variables in their declaration (assigned an initial value). The initializer of a variable
may contain an equal sign- that gets followed by a constant expression. It goes like this:
type variable_name = value;
A few examples are −
extern int p = 3, q = 5; // for the declaration of p and q.
int p = 3, q = 5; // for the definition and initialization of p and q.
byte x = 22; // for the definition and initialization of x.
char a = ‘a’; // the variable x contains the value ‘a’.
In case of definition without the initializer: The variables with a static duration of storage are initialized
implicitly with NULL (here, all bytes have a 0 value), while the initial values of all the other variables
are not defined.
Declaration of Variable in C
Declaring a variable provides the compiler with an assurance that there is a variable that exists with
that very given name. This way, the compiler will get a signal to proceed with the further compilation
without needing the complete details regarding that variable.
The variable definition only has a meaning of its own during the time of compilation. The compiler
would require an actual variable definition during the time of program linking.
The declaration of variables is useful when we use multiple numbers of files and we define the variables
in one of the files that might be available during the time of program linking. We use
the extern keyword for declaring a variable at any given place. Though we can declare one variable
various times in a C program, we can only define it once in a function, a file, or any block of code.
Example
Let us look at the given example where we have declared the variable at the top and initialized and
defined them inside the main function:
#include <stdio.h>
// Declaration of Variable
extern int p, q;
extern int c;
extern float f;
int main () {
/* variable definition: */
int p, q;
int r;
float i;
/* actual initialization */
p = 10;
q = 20;
r = p + q;
printf(“the value of r : %d \n”, r);
i = 70.0/3.0;
printf(“the value of i : %f \n”, i);
return 0;
}
The compilation and execution of the code mentioned above will produce the result as follows:
the value of r : 30
the value of i : 23.333334
Classification of Variables in C
The variables can be of the following basic types, based on the name and the type of the variable:
• Global Variable: A variable that gets declared outside a block or a function is known as a
global variable. Any function in a program is capable of changing the value of a global
variable. It means that the global variable will be available to all the functions in the code.
Because the global variable in c is available to all the functions, we have to declare it at the
beginning of a block. Explore, Global Variable in C to know more.
Example,
int value=30; // a global variable
void function1(){
int a=20; // a local variable
}
• Local Variable: A local variable is a type of variable that we declare inside a block or a
function, unlike the global variable. Thus, we also have to declare a local variable in c at the
beginning of a given block.
Example,
void function1(){
int x=10; // a local variable
}
A user also has to initialize this local variable in a code before we use it in the program.
• Automatic Variable: Every variable that gets declared inside a block (in the C language) is
by default automatic in nature. One can declare any given automatic variable explicitly using
the keyword auto.
Example,
void main(){
int a=80; // a local variable (it is also automatic variable)
auto int b=50; // an automatic variable
}
• Static Variable: The static variable in c is a variable that a user declares using
the static keyword. This variable retains the given value between various function calls.
Example, void function1(){
int a=10; // A local variable
static int b=10; // A static variable
a=a+1;
b=b+1;
printf(“%d,%d”,a,b);
}
If we call this given function multiple times, then the local variable will print this very same
value for every function call. For example, 11, 11, 11, and so on after this. The static variable,
on the other hand, will print the value that is incremented in each and every function call. For
example, 11, 12, 13, and so on.
• External Variable: A user will be capable of sharing a variable in multiple numbers of
source files in C if they use an external variable. If we want to declare an external variable,
then we need to use the keyword extern.
Syntax, extern int a=10;// external variable (also a global variable)
Constants in C
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c
programming" etc.
2 ways to define constant in C
There are two ways to define constant in C programming
1. const keyword
2. #define preprocessor
1) C const keyword
The const keyword is used to define constant in C programming.
1. const float PI=3.14;
Now, the value of PI variable can't be changed.
1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. printf("The value of PI is: %f",PI);
5. return 0;
6. }
Output:
The value of PI is: 3.140000
If you try to change the the value of PI, it will render compile time error.
1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. PI=4.5;
5. printf("The value of PI is: %f",PI);
6. return 0;
7. }
Output:
Compile Time Error: Cannot modify a const object
2) C #define preprocessor
The #define preprocessor is also used to define constant. We will learn about #define preprocessor
directive later.
C #define
The #define preprocessor directive is used to define constant or micro substitution. It can use any
basic data type.
Syntax:
1. #define token value
Example of #define to define a constant.
1. #include <stdio.h>
2. #define PI 3.14
3. main() {
4. printf("%f",PI);
5. }
Output:
3.140000
Keywords - These are reserved words that have special meaning in a language. The compiler
recognizes a keyword as part of the language’s built – in syntax and therefore it cannot be used for
any other purpose such as a variable or a function name. C keywords must be used in lowercase
otherwise they will not be recognized. Also called Reserved words in C programming.
Examples of keywords
auto break case else int void
default do double if sizeof long
float for goto signed unsigned
register return short union continue
struct switch typedef const extern
volatile while char enum static
Escape Sequence in C
An escape sequence in C language is a sequence of characters that doesn't represent itself when used
inside string literal or character. It is composed of two or more characters starting with backslash \.
For example: \n represents new line.
List of Escape Sequences in C
Escape Sequence Meaning
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\' Single Quote
\" Double Quote
\? Question Mark
\nnn octal number
\xhh hexadecimal number
\0 Null