Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
142 views

Basics of C Programming

This document provides an introduction to the C programming language. It discusses key concepts such as C tokens, data types, variables, constants, and functions. The main points covered are: - C was created in 1972 and is a portable, general-purpose programming language. - The basic building blocks of a C program are tokens such as keywords, identifiers, constants, and operators. - C supports standard data types like int, float, and char that have predefined sizes and behaviors. - Variables and constants are used to store and represent data in a C program. Variables can have their values changed while constants cannot. - The main() function marks the starting point of a C program and contains

Uploaded by

sush241190
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
142 views

Basics of C Programming

This document provides an introduction to the C programming language. It discusses key concepts such as C tokens, data types, variables, constants, and functions. The main points covered are: - C was created in 1972 and is a portable, general-purpose programming language. - The basic building blocks of a C program are tokens such as keywords, identifiers, constants, and operators. - C supports standard data types like int, float, and char that have predefined sizes and behaviors. - Variables and constants are used to store and represent data in a C program. Variables can have their values changed while constants cannot. - The main() function marks the starting point of a C program and contains

Uploaded by

sush241190
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Navrachana University

Introduction to C Programming

-Sushma Vankhede
Assistant Professor
Computer Science and Engineering Department
Introducing C
 C is a programming language developed at AT & T Bell
Laboratories of USA in 1972, designed and written by
“Dennis Ritchie”.
 C is highly portable i.e., software written for one computer
can be run on another computer.
 An important feature of ‘C’ is its ability to extend itself. A C
program is basically a collection of functions.
C Tokens
 A token is an atomic unit (smallest indivisible units) in a
program.
 The most basic elements in a C program recognized by the
compiler are a single character or a group of characters
called C tokens.
 The compiler cannot breakdown the token any further. For
example, the words main, ‘{‘ (brace), ‘(‘ (parenthesis) are all
tokens of C program.
Types of tokens.
1. Keywords Examples: float, int, double, while, for.
2. Identifiers Examples: main, amount
3. Constants Examples: 12.4, 7894
4. Strings Examples: “CSM”, “Thursday”
5. Special Symbols Examples: [,], {, }, (, ) 6. Operators
Examples: +, *, /
The C character set
 The C character set includes the upper case letters A to Z,
the lower case a to z, the decimal digits 0 to 9 and certain
special characters.
 Letters a, b, c, ……………z. A,B,C,…..Z.
 Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
 Special characters ~,.;:?‘“!()[]{}/<>=+ -$#@&*%^
Character/ Meaning
 ~ tilde
 ( Left parenthesis ) Right
 , Comma Parenthesis
 . Period  [ Left Bracket ] Right Bracket
 ; Semicolon  { Left Brace } Right Brace
 ? Questionmark  / Slash Back Slash \ forward slash
 : Colon  < Less than > Greater than =
Equal to
 “ Double Quote
 ! Exclamatory Mark
 ‘ Single Quote
 - Minus + Plus
 ^ Carat  # Hash $ Dolor Sign
 _ Underscore  & Ampersand * Asterisk (or star)
 | Vertical Bar  % Percent
Identifiers
 Identifiers are distinct names given to program elements
such as constants, variables, etc.
 An Identifier is a sequence of letters, digits, and the special
character ‘_’ (underscore).
1. It must start with either a letter or underscore. ‘_’
2. No commas or blanks are allowed within a variable name. 3.
The upper case and lower case letters are treated as distinct,
i.e., identifiers are case-sensitive.
4. An identifier can be of any length.
5. No special symbol can be used in a variable name.
Keywords
 Keywords are predefined tokens in C. These are also called
reserved words.
 Key words have special meaning to the C compiler. These key
words can be used only for their intended action; they cannot
be used for any other purpose.
 C has 32 keywords.
Keywords..Cont..
 The standard keywords are
 Auto, break, case, char, const, continue, default, do, double,
else, enum, extern, float, for, goto, if, int, long, register,
return, short, signed, sizeof, static, struct, switch, typedef,
union, unsigned, void, volatile, while.
Data types
 A data type defines a set of values and the operations that can
be performed on them.
 Every datatype item (constant, variable etc.) in a C program
has a datatype associated with it.
 C also has a special datatype called void, which, indicates that
any data type, i.e., no data type, does not describe the data
items.
 void data type in c. Generally void is an empty data
type and it used as a return type of functions that return no
value in c.
 Eg:-void func(int n) //It indicates that the function returns
no result.
Size
 Char Single character 1byte 0 to 255
 Int An integer 2bytes -32768 to +32767
 Float Floating point number 4bytes -2,147,483,648 to
+2,147,483,647
 Double Floating point number 8 Approximately 15 digits of
Precision
Constants and Variables
 A constant is a literal, which remain unchanged during the
execution of a program.
 A constant is a fixed value that cannot be altered during the
execution of a program.
 C constants can be classified into two categories.
 Primary Constants
 Secondary Constants
Constant –Its value is fixed throughout the program that means
constants are those variables which value is not changed
throughout the program.
Constants and Variables
 Variable is used to store the value. As name indicates its value can
be changed or also it can be reused many times.
 Syntax
 Data type variable_name;
 e.g.
 int a; Where a is the variables.
 There are many types of variables in c:
 local variable
 global variable
 static variable
 external variable
 Automatic variable
Types of Variables
 1. Local variable – A variable which is declared inside the
function is known as local variable. It is used only inside the
function in which it is declared.
 2. Global variable – A variable which is declared outside the
function is known as global variable. It can be used throughout the
program.
 3. Static variable – It is used to retain its value between multiple
function calls. It is declared using static keyword.
 4. External variable –You can share a variable in multiple C
source files by using external variable. It is declared using extern
keyword.
 5. Automatic variable –Variable which is declared inside the
block is known as automatic variable by default.
Structure of a ‘C’ program
 C programs consist of one or more functions.
 Each function performs a specific task.
 A function is a group or sequence of C statements that are
executed together.
 The following is a simple C program that prints a message on the
screen.
/* A simple program for printing a message */
# include <stdio.h>
# include <conio.h>
void main( )
{ clrscr( );
printf(“Welcome to C”);
getch( );
}
 Description The first line
 /* A simple program for printing a message */ is a comment
line.
 Comments in the c program are optional and may appear
anywhere in a C program. Comments are enclosed between /*
and */.
 The second line
 # include <stdio.h> tells the compiler to read the file stdio.h
and include its contents in this file. stdio.h, one of header files,
contain the information about input and output functions.
stdio.h means Standard Input Output Header file. This file contains
the information about printf() function.
 The third line
 # include <conio.h> tells the compiler to read the file conio.h
and include its contents in this file. conio.h means Consoled
Input Output Header file. This file contains the information
about clrscr() and getch() functions.
 The fourth line
 void main( ) is the stat of the main program. The word main is
followed by a pair of ordinary parenthesis ( ), which indicates
that main is also a function.
 The fifth line
 { the left brace represents the beginning of the program.
 The sixth line
 clrscr( ); tells the compiler to clear the screen and kept the
cursor at left side corner.
 The seventh line
 printf( “Welcome to C”); this function causes its
arguments to be printed on the screen on the computer.
 The eight line
 getch( ); is reads the single character directly from the keyboard
without printing on the screen.
 The ninth line
 } the right brace represents the ending of the program.
Rules to write a C program
1. All C statements must end with semicolon.
2. C is case-sensitive. That is, upper case and lower case characters
are different. Generally the statements are typed in lower case.
3. A C statement can be written in one line or it can split into
multiple lines.
4. Braces must always match upon pairs, i.e., every opening brace {
must have a matching closing brace }.
5. Every C program starts with void main( ) function.
6. Comments cannot be nested. For example, /* Welcome to ‘C’ ,/*
programming*/ */ A comment can be split into more than one
line.
Execution of C Program Steps to be followed in writing
and running a C program.
 Creation of Source Program Create a C program file in
various C compilers are available under MS-DOS, Turbo C
Editor, gcc compiler etc.
 Compilation of the Program Turbo C compiler is user
friendly and provides integrated program development
environment.
 Thus, selecting key combination can do compilation. That
means press Alt + F9 for compilation.
 Program Execution In Turbo C environment, the RUN
option will do the compilation and execution of a program.
Press Ctrl + F9 for execution the program.
printf( ) Function:
 Writing Output Data The printf( ) function is used to write
information to standard output (normally monitor screen).
 The structure of this function is printf(format string, list of
arguments);
 The format string contains the following:
 1. Characters that are simply printed on the screen.
 2. Specifications that begin with a % sign and define the output
format for display of each item.
 3. Escape sequence characters that begin with a sign such as n, t
etc.
 Character Argument Resulting Output c Character A single
character d Integer Signed decimal integer s String Prints
character strings f Floating Single floating point number point
scanf( ) Function:
 getting user input The real power of a technical C program is
its ability to interact with the program user.
 This means that the program gets input values for variables
from users.
 The scanf( ) function is a built-in C function that allows a
program to get user input from the keyboard.
 The structure of this function is
 scanf(format string &list of arguments);
 Examples scanf(“%d”, &a ); scanf(“%d %c %f ”,&a, &b, &c );
Operators & Expressions
 An operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations.
 Operators are used in program to manipulate data and
variables.
 The data items that operators act upon are called operands.
 Some operators require two operands, while others act upon
only one operand.
 The operators are classified into unary, binary and ternary
depending on whether they operate on one, two or three
operands respectively.
Operators
Types of operators C has four classes of operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bit-wise Operators
In addition, C has some special operators, which are unique to
C, they are
1. Increment & Decrement Operators
2. Conditional Operators
3. Assignment Operators, etc.
Arithmetic Operators
 There are five arithmetic operators in C.
 The following table lists the arithmetic operators allowed in
C:
Operator Meaning
+ Addition
- Subtraction; also for unary minus
* Multiplication
/ Division
% Modulo division (remainder after integer
division)
Relational Operators
 Relational Operators are symbols that are used to test the
relationship between two variables or between a variable and a
constant. We often compare two quantities, and depending on
their relation takes certain decisions. These comparisons can be
done with the help of relational operators. C has six relational
operators as shown below.
Logical Operators
 Logical Operators are symbols that are used to combine or
negate expressions containing relational operators. C has
three logical operators as defined below.
Bitwise operators
 The lowest logical element in the memory is bit. C allows the
programmer to interact directly with the hardware of a particular
system through bitwise operators and expression. These operators
work only with int and char datatypes and cannot be used with
float and double type. The following table shows the bitwise
operators that are available in C.
Increment & Decrement operators
 C has two very useful operators for adding and subtracting a
variable. These are the increment and decrement operators,
++ and -- .
 These two operators are unary operators. The increment
operator ++ adds 1 to its operand, and the decrement
operator -- subtracts 1 from its operand.
 Therefore, the following are equivalent operations.
 ++i is equivalent to i = i + 1;
 --i is equivalent to i = i – 1;
 These operators are very useful in loops.
Assignment operators
 In addition to usual assignment operator =, C has a set of
shorthand operators, that simplifies the coding of a certain
type of assignment statement.
 It is of the form var op = exp
 where var is a variable, op is a C binary arithmetic operator and
exp is an expression.
Conditional Operator
 C provides a peculiar operator ? : which is useful in reducing
the code.
 It is ternary operator requiring three operands.
 The general format is exp1 ? exp2 : exp3;
 where exp1, exp2 and exp3 are expressions.
 In the above conditional expression, exp1 is evaluated first.
 If the value of exp1 is non zero (true), then the value
returned will be exp2.
 if the value of exp1 is zero (false), then the value returned
will be exp3.
Hierarchy (precedence) of operators
 The priority or precedence in which the operations of an
arithmetic statement are performed is called the hierarchy of
operators.
 The operators of at the higher level of precedence are evaluated
first.
 The operators of the same precedence are evaluated either from
left to right or from right to left, depending on the level.
 This is known as the Associativity property of an operator.
CONTROL STRUCTURES
 The control flow statements of a language determine the
order in which the statements are executed.
 We also need to be able to specify that a statement, or a
group of statements, is to be carried out conditionally, only if
some condition is true.
 Also we need to be able to carry out a statement or a group
of statements repeatedly based on certain conditions.
 These kinds of situations are described in C using
Conditional Control and Loop Control structures.
Conditional & loop structures
 A conditional structure can be implemented in C using
 The if statement
 The if-else statement
 The nested if-else statement
 The switch statement.
 whereas loop control structures can be implemented in C
using
 while loop
 do-while loop
 for statement
The if statement
 The if statement is used to control the flow of execution of
statements. The general form of if statement is
if (condition)
statement;
 Suppose if it is required to include more than one statement, then
a compound statement is used, in place of single statement. The
form of compound statement is
if (condition)
{ statement1;
statement2; }
 If the condition is true, then the statement/statements will be
executed. If the condition is false, then the statement/statements
will not be executed.
The if statement : Program
 /* Inputting year is Leap or not */
#include<stdio.h>
#include<conio.h>
void main()
{
int year;
clrscr();
printf(“Enter year:”);
scanf(“%d”,&year);
if(year%4==0)
printf(“Leap year”);
if(year%4!=0)
printf(“Not leap year”);
getch(); }
The if-else Statement
 The general form of if-else statement is…
if (condition)
statement1;
else
statement2;
 If the condition is true, then statement1 is executed. Otherwise if
the condition is false, then the statement2 is executed. Here
statements statement1 and statement2 are either simple
statements or compound statements. That is…
if (condtion)
{ statements /* if block */ }
else { statements /* else */ }
The if-else Statement : Program
 /* Single digit or not */
#include<stdio.h>
#include<conio.h>
void main() {
int n;
clrscr();
printf(“Enter a number:”);
scanf(“%d”,&n);
if(n<=9)
printf(“Single digit”);
else
printf(“Not single digit”);
getch();
}
Nested if-else Statements
 When a series of conditions are involved, we can use more than
one if-else statement in nested form.
 This form is also known as if-else if-else statements. The general
form of if-else if-else statement is
if (condition)
statements;
else if (condition)
statements;
else
statements;
 Note that a program contains number of else if statements and
must be ended with else statement.
Nested if-else Statements : Program
 /* To check whether +ve, -ve or zero */
 #include<stdio.h>
 #include<conio.h>
 void main()
 {
 int n;
 clrscr();
 printf(“Enter a number:”);
 scanf(“%d”,&n);
 If(n>0)
 printf(“+ve”);
 else if(n<0)
 printf(“-ve”);
 else printf(“zero”);
 getch(); }
The Switch Statement : Program
 Program /* Letter -> color name */
 #include<stdio.h>
 #include<conio.h>
 void main()
 {
 char x;
 Enter a char:w
 clrscr(); w->
 White
 printf(“Enter a char:”);
 scanf(“%c”,&x);
 Enter a char:b switch(x) b->black {case
‘w’:printf(“w->white”); Enter a char:c
break; No color case ‘b’:printf(“b-
>black”); break; default:printf(“No
color”); } getch(); } A
LOOPS
 A portion of program that is executed repeatedly is called a
loop.
 The C programming language contains three different
program statements for program looping.
 They are
 For loop
 While loop
 Do-While loop
The For Loop
 The for loop is used to repeat the execution statement for some fixed
number of times.
 The general form of for loop is
for(initialization; condition; increment/decrement)
statement;
 where the statement is single or compound statement.
 initialization is the initialization expression, usually an assignment to
the loop-control variable. This is performed once before the loop
actually begins execution.
 condition is the test expression, which evaluated before each iteration
of the loop, which determines when the loop will exist.
 increment is the modifier expression, which changes the value of loop
control variable. This expression is executed at the end of each loop.
The For Loop : Program
/* Print 1 to 10 numbers */ Output:
#include<stdio.h>
1
#include<conio.h> 2
void main() 3
{ 4
int i;
5
clrscr(); 6
for(i=1;i<=10;i++) 7
printf(“\n%d”,i); 8
getch();
9
} 10
The While Loop
 The while loop is best suited to repeat a statement or a set of
statements as long as some condition is satisfied.
The general form of while loop is initial expression;
while(conditional-expression)
{ statement;
increment/decrement;
}
 where the statement (body of the loop) may be a single
statement or a compound statements. The expression (test
condition) must results zero or non-zero.
The While Loop : Program
/* Print a message 3 times */ Output:
#include<stdio.h>
#include<conio.h> Navrachana University
void main() Navrachana University
{ Navrachana University
int i=1;
clrscr();
while(i<=3)
{
printf(“Navrachana University \n”);
i++;
} getch();
}
The do-while loop
 The structure of do-while loop is similar to while loop.
 The difference is that in case of do-while loop the expression is
evaluated after the body of loop is executed.
 In case of while loop the expression is evaluated before executing
body of loop.
 The general form of do-while statement is
do { statement; }
while(expression);
where statement is a single statement or compound statement. In
contrast to while loop statement (body of loop), do-while loop is
executed one or more times.
END

You might also like