PROGRAMMING
IN C
ABOUT C LANGUAGE
C is a programming language developed
by Dennis Ritchie at AT&T‟s BELL
Laboratory of USA in 1972. Because of
its reliability, C is very popular. C is
highly portable & it is well suited for
structured programming. C program
consists of collection of functions.
STRUCTURE OF A C
PROGRAM
A ‘C’ program basically consists of the following parts −
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
Let us look at a simple code that would print the words "HelloWorld" −
Let us take a look at the various parts of the above program −
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.
C - BASIC SYNTAX
After going through the Basic structure, 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"
)
;
C - BASIC SYNTAX
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;
C - BASIC SYNTAX
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 */
line comment // my first program in C
C - BASIC SYNTAX
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 −
man woman abc move_name a_123
myname 50 _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.
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 −
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.
Data Size Description
Type
int 2 or 4 Stores whole numbers, without decimals
bytes
float 4 bytes Stores fractional numbers, containing one or
more decimals. Sufficient for storing 7 decimal
digits
double 8 bytes Stores fractional numbers, containing one or
more decimals. Sufficient for storing 15 decimal
digits
BASIC FORMAT SPECIFIERS
There are different format specifiers for
each data type. Here are some of them:
Format Specifier Data Type
#include >stdio.h>
%d int int main()
%f float { // datatypes
int a = 10;
%lf double
char b = 'S';
%c char float c = 2.88;
%s Used for strings double d = 28.888;
(text) printf("Integer datatype : %d",a);
printf("Character datatype : %c",b);
printf("Float datatype : %f",c);
printf("Double Float datatype : %lf",d);
return 0; }
Here is the output,
Output
Integer datatype : 10
Character datatype : S
Float datatype : 2.880000
Double Float datatype : 28.888000
Variables can be initialized (assigned an
initial value) in their declaration.
Some examples are −
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'.
C – OPERATORS
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:
Relational Operators
The following table shows all the relational
operators supported by C.
Assume variable A holds 10 and variable B
holds 20 then −
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.
PRINTF() AND SCANF() IN C
The printf() and scanf() functions are used for
input and output in C language. Both
functions are inbuilt library functions, defined
in stdio.h (header file).
Printf() function
The printf() function is used for output. It
prints the given statement to the console.
The syntax of printf() function is given below:
printf("format string",argument_list);
The format string can be %d (integer), %c
(character), %s (string), %f (float)
etc.intf("format string",argument_list);
SCANF() FUNCTION
The scanf() function is used for input. It reads the input data from
the console.
scanf("format string",argument_list);
The scanf("%d",&number) statement reads integer number from
the console and stores the given value in number variable.
Program to print cube of given number
Let's see a simple example of c language that gets input from the
user and prints the cube of the given number.
#include<stdio.h>
int main(){
int number;
printf("enter a number:");
scanf("%d",&number);
printf("cube of number is:%d ",number*number*number);
return 0;
}
Output
enter a number:5 cube of number is:125
C – OPERATORS(ARITHMETIC OPERATORS)
CONDITIONS AND IF STATEMENTS
C supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
You can use these conditions to perform different actions for different
decisions.
C has the following conditional statements:
Use if to specify a block of code to be executed, if a specified
condition is true
Use else to specify a block of code to be executed, if the same
condition is false
Use else if to specify a new condition to test, if the first condition is
false
Use switch to specify many alternative blocks of code to be executed
HEADER FILES INCLUSION
The first and foremost component is the inclusion of
the Header files in a C program.
A header file is a file with extension .h which
contains C function declarations and macro
definitions to be shared between several source
files.
Some of C Header files:
stddef.h – Defines several useful types and macros.
stdint.h – Defines exact width integer types.
stdio.h – Defines core input and output functions
stdlib.h – Defines numeric conversion functions, pseudo-
random network generator, memory allocation
string.h – Defines string handling functions
math.h – Defines common mathematical functions
THE IF STATEMENT
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Example
if (20 > 18) {
printf("20 is greater than 18");
}
Example
int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}
THE ELSE STATEMENT
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is
false
}
Example
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
// Outputs "Good evening."
THE ELSE IF STATEMENT
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2
is true
} else {
// block of code to be executed if the condition1 is false and condition2
is false
}
Example
int time = 22;
if (time < 10) {
printf("Good morning.");
} else if (time < 20) {
printf("Good day.");
} else {
printf("Good evening.");
}
// Outputs "Good evening."
SWITCH STATEMENT
Instead of writing many if..else statements, you
can use the switch statement.
Example
int day = 4;
Syntax switch (day) {
switch(expression) { case 1:
printf("Monday");
case x: break;
case 2:
// code block printf("Tuesday");
break;
break; case 3:
printf("Wednesday");
case y: break;
case 4:
// code block printf("Thursday");
break;
break; case 5:
default: printf("Friday");
break;
// code block case 6:
printf("Saturday");
} break;
case 7:
printf("Sunday");
break;
}
// Outputs "Thursday" (day 4)
WHILE LOOP
Loops
Loops can execute a block of code as long as a specified
condition is reached.
Syntax
while (condition) {
// code block to be executed
}
Example
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
THE DO/WHILE LOOP
The do/while loop is a variant of the while loop. This loop will
execute the code block once, before checking if the condition is
true, then it will repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
Example
int i = 0;
do {
printf("%d\n", i);
i++;
}
while (i < 5);
FOR LOOP IN C
The syntax of a for loop in C programming language is −
for ( init; condition; increment )
{
statement(s);
}
Example:
#include <stdio.h>
int main ()
{
int a; /* for loop execution */
for( a = 10; a < 20; a = a + 1 )
{
printf("value of a: %d\n", a);
}
return 0;
}
ARRAYS
Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
To create an array, define the data type (like int) and
specify the name of the array followed by square brackets
[].
To insert values to it, use a comma-separated list, inside
curly braces:
int myNumbers[] = {25, 50, 75, 100};
We have now created a variable that holds an array of four
integers.
Example
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);
// Outputs 25
Example
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
// Now outputs 33 instead of 25
Example
int myNumbers[] = {25, 50, 75, 100};
int i;
for (i = 0; i < 4; i++) {
printf("%d\n", myNumbers[i]);
}
Example
// Declare an array of four integers:
int myNumbers[4];
// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
Find the Largest Number Among Three Numbers
C Program to Display Characters from A to Z Using
Loop
C Program to Count Number of Digits in an Integer
C Program to Check Whether a Number is Palindrome or
Not
C Program to Make a Simple Calculator Using
switch...case
Preprocessor Directives
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.
Preprocessing directives are lines in your program that start with #.
The # is followed by an identifier that is the directive name. For
example, #define is the directive that defines a macro. Whitespace
is also allowed before and after the #.
NOTE: All preprocessor directives starts with hash # symbol.
Including Header Files: #include
• The #include preprocessor is used to include header files to C
programs. For example,
• #include <stdio.h>Here, stdio.h is a header file. The #include
preprocessor directive replaces the above line with the contents of
stdio.h header file.
• That's the reason why you need to use #include <stdio.h> before
THANK YOU