Sunteți pe pagina 1din 146

C Fundamentals

Refresher Course on Programming Basics


Using C and C++ (ReCoPB’16) 26/4/2016
Topics to be Covered
• C Fundamentals
• Operators
• Type casting
• preprocessors
• input/output Statements
• Branching and Looping
• Macros
• Data representation in computers
• Arrays
• String
What is C?
making extensive use of subroutines,
block structures and loops

• C is a general-purpose, structured programming


language.
• C was developed at AT&T’s Bell Laboratories of
USA in 1972.
• It was designed and written by a man named
Dennis Ritchie
• Possibly why C seems so popular is because it is
reliable, simple and easy to use.
Question Time

• What are the main differences between these


programming languages?
–C
– C++
– Java
The C Character Set

• Alphabets: A-Z, a-z


• Digits: 0-9
• Special Characters: (all the symbols on the
keyboard) : ~,`,!,@,#,$,%,%,^,&,*,(,),-,_,=,+,[,{,]
• White space characters: The nonprintable
characters like blank space, tab space, newline,
carriage return
Identifiers and Keywords

• Every word in C is either classified as an


Identifier or a keyword.
• Identifiers: Use to identify names of variables,
symbolic constants, function names, etc.
• Keywords: Predefined term having a
predefined meaning, which cannot be changed
by the user.
C Keywords

• The keywords cannot be used as variable


names because if we do so we are trying to
assign a new meaning to the keyword, which is
not allowed by the computer.
• The keywords are also called ‘Reserved words’.
• There are only 32 keywords available in C.
List of C Keywords

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Rules for an Identifier

• It must be a sequence of letters, digits, and must


begin with a letter
• The underscore character ( _ ) is considered as a
letter.
• Names should not be the names of keywords.
• C is case-sensitive i.e., uppercase and lowercase
letters are not interchangeable.
• The first 31 characters of an identifier’s name is
significant in ANSI C compiler.
Variables

• A variable name is an entity that has a value stored in


memory, and the location is known to the program by
a name.
• Rules that apply to identifier applies to variables also.
• E.g emp_number,marks,MAX,_fact,number1
• Every variable must be created to store a specific type
of data (whole numbers, numbers with a fraction,
strings etc.) or data types.
Basic Data Types In C

Data Description Typical Memory


Types Requirements
char single character 1 byte

2 bytes or 1 word (differs


int integer quantity from compiler to compiler)

float floating-point number


1 word (i.e. 4 bytes)
Double-precision
double floating-point number 2 words (i.e. 8 bytes)
Qualifiers Used With Data Types

• The basic data types can be augmented by the


use of data type qualifiers, such as:
– short
– long
– signed, and,
– unsigned
Data Types

Data Types Size in Bytes Possible Range of Values


char 1 -128 to 127
unsigned char 1 0 to 255
int 4 -2147483648 to 2147483647
unsigned int 4 0 to 4294967295
short int 2 -32768 to 32767
long 4 same as int
float 4 3.4 *10-38 to 1.7* 1038
double 8 1.7*10-38 to 3.4 *1038
Variable Declaration

• A declaration associates a group of variables with a


specific data type
• Example: int a, b;
• Here, a and b are variables and int is their data types
• Initial values can be assigned to variables within a
type declaration:
• Example: int a = 12, b = 13;
Constants

• A constant is a value that does not change


• Example:
2*a + b = 20

• In the above example, which are variables and which


are constants?
• Ans: Here, a and b are variables whose values can
change whereas 2 and 20 are constants whose values
cannot change
Types of Constants
• C constants can be divided into three major types:
• Numeric Constants:
–Integer Constant: e.g.: 426,+777,-8976
–Real Constant : Two forms –
Fractional form: e.g.: 426.06, 10.5. 3.0
Exponential form: e.g.: +3.2e+3, 1.5e8
• Character Constants: e.g.: ‘A’, ‘I’, ‘+’, ‘=‘
• String Constants: e.g.: “Shillong”, “Riya”
Rules for Constructing Integer
Constants
1. It must have at least one digit
2. It must not have a decimal point
3. It can be either positive or negative
4. The default sign is positive
5. No commas, or blanks are allowed within an integer
constant
6. The allowable range is -32767 to +32767 (16 bit
machine)
Rules for Constructing Real Constants:
Fractional Form

• It must have at least one digit


• It must have a decimal point
• It can either be positive or negative
• Default sign is positive
• No commas, or blanks are allowed within a real form
Rules for Constructing Real Constants:
Exponential Form
• Example: +2.5e5
• Here, +2.5 is called Mantissa, and 5 is called the
Exponent

1. The mantissa and the exponent should be


separated by the letter e
2. Both can either be positive or negative
3. Both must have at least one digit
4. Default sign is positive
5. Range of real constants is -3.4e38 to 3.4e38
Character Constant
• A character constant is a single character enclosed in
apostrophes (i.e., single quotation marks)
• Each individual character is numerically encoded
with its own unique 7-bit combination by making use
of ASCII (American Standard Code for Information
Interchange)
• Example: ASCII value of ‘A’ is 65, ‘a’ is 97, ‘0’ is 48, etc
• Escape sequences (like ‘\n’, ‘\t’, ‘\a’) are also
character constants
String Constant
• A string constant consists of any number of
consecutive characters (including none), enclosed in
double quotation marks

• Difference between a character constant and a


single-character string constant :
• Character Constant: has an equivalent integer value
• Single-Character String Constant: does not have an
equivalent integer value, and in fact, consists of two
characters – the specified character followed by the
null character (‘\0’)
Comments in C
• Comments are remarks that may appear anywhere
within a program, as long as they are placed within the
delimeters /* and */ or //
• The delimeter // is used for single-line comment
• The delimeters /* and */ are use for multi-line comments
• Example:
// It is a single-line comment
/* This is a more than
one line comment */
C Expressions

• An expression represents a single data item, such as


a number or character, or it may consist of a
combination of various entities, such as, constants,
variables, etc. interconnected by one or more
operators
• Example: a+b
x=3
c=a*b
C Statements

• A statement allows to carry out an action

• There are three different types of statements


in C:
– Expression statements
– Compound statements
– Control statements
Expression Statements
• An expression statement consists of an expression
followed by a semi-colon:
• Example: c = 3;
x = y + z;

Compound Statements
• A compound statement consists of several individual
statements enclosed within a pair of braces:
• Example:
{ c = 3;
x = y + z;
}
Control Statement

• A control statement is used to create special program


features, such as logical tests, loops and branches.

• Example:
while (num<=3)
{ x = x + 1;
num = num + 1;
}
C Instructions: Rules Applicable To
All C Statements
• Blank spaces may be inserted between two words to
improve readability, however no blank spaces are
allowed within a variable, constant, or keyword
• Usually all statements are entered in small case
letters (all keywords are also in small letters)
• C statement always ends with a ; (semicolon)
• Comments are added using /* … …*/ or //
• A block of statement are enclosed within { }
Anatomy of C Program
C Libraries
A Simple C Program
Another C program

//finding product of two numbers


#include <stdio.h> /*using one of C libraries*/
void main()
{
int a=10, b=5, c; /* declaring variables a and b */
c=a*b; /* arithmetic statement*/
printf(“The value of a is %d”, a); /* i/o statement */
return;
}
Quick Answers to Questions
Which of the following language is predecessor to C Programming Language?
a) A
b) B
c) BCPL
d) C++

C programming language was developed by


a) Dennis Ritchie
b) Ken Thompson
c) Bill Gates
d) Peter Norton

C was developed in the year ___


a) 1970
b) 1972
c) 1976
d) 1980
Quick Answers to Questions
Which of the following language is predecessor to C Programming Language?
a) A
b) B
c) BCPL
d) C++

C programming language was developed by


a) Dennis Ritchie
b) Ken Thompson
c) Bill Gates
d) Peter Norton

C was developed in the year ___


a) 1970
b) 1976
c) 1972
d) 1980
Quick Answers to Questions

C is a ___ language
a) High Level
b) Low Level
c) Middle Level
d) Machine Level

C language is available for which of the following Operating Systems?


a) DOS
b) Windows
c) Unix
d) All of these
Quick Answers to Questions

C is a ___ language
a) High Level
b) Low Level
c) Middle Level
d) Machine Level

C language is available for which of the following Operating Systems?


a) DOS
b) Windows
c) Unix
d) All of these
Quick Answers to Questions
The C language terminator is
a) Semicolon
b) Colon
c) Period
d) Exclamation mark

What is false among the following: A compound statement is:


a) A set of simple statements
b) Demarcated on either side by curly brackets
c) Can be used in place of simple statement
d) A C function is not a compound statement
Quick Answers to Questions
The C language terminator is
a) Semicolon
b) Colon
c) Period
d) Exclamation mark

What is false among the following: A compound statement is:


a) A set of simple statements
b) Demarcated on either side by curly brackets
c) Can be used in place of simple statement
d) A C function is not a compound statement
Quick Answers to Questions
A C language consists of …………….. number of keywords
a) 36
b) 32
c) 28
d) 46

Which of the following about the C comments is incorrect?


a) Comments can go over multiple lines
b) Comments can start anywhere in the line
c) A line can contain comments without any language statements
d) Comments can occur within comments
Quick Answers to Questions
A C language consists of …………….. number of keywords
a) 36
b) 32
c) 28
d) 46

Which of the following about the C comments is incorrect?


a) Comments can go over multiple lines
b) Comments can start anywhere in the line
c) A line can contain comments without any language statements
d) Comments can occur within comments
Quick Answers to Questions
What will be the output ?
void main ( ) {
int I= 48;
printf(“\n %c %d” ,I,I ); }
a) Error
b) 48 48
c) 1 48
d) 0 48

A declaration float a,b; occupies ______of memory


a) 1 byte
b) 4 bytes
c) 8 bytes
d) 16 bytes
Quick Answers to Questions
What will be the output ?
void main ( ) {
int I= 48;
printf(“\n %c %d” ,I,I ); }
a) Error
b) 48 48
c) 1 48
d) 0 48

A declaration float a,b; occupies ______of memory


a) 1 byte
b) 4 bytes
c) 8 bytes
d) 16 bytes
Quick Answers to Questions
Which escape character can be used to begin a new line in C?
a) \a
b) \b
c) \m
d) \n

Which escape character can be used to beep from speaker in


C?
a) \a
b) \b
c) \m
d) \n
Quick Answers to Questions
Which escape character can be used to begin a new line in C?
a) \a
b) \b
c) \m
d) \n

Which escape character can be used to beep from speaker in


C?
a) \a
b) \b
c) \m
d) \n
Last Try!

printf ("Characters: %c %c \n", 'a', 65);

a A
Operators Used in C
Operators Used in C
• An operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations.
• There are eight categories of operators used in C. They are:
– Arithmetic operators
– Unary operators
– Relational operators
– Logical operators
– Assignment operators
– Conditional operator
– Bitwise operators
– Special operators
Arithmetic / Binary Operators
Operators Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
% (modulus operator)
Remainder after Integer Division

For example, c=a*b

Here, a, b, and c are operands and * and = are operators


Integer Arithmetic Operations
Example: If a = 10, b = 3, then,
a + b = 10, a – b = 7, a * b = 30, a / b = 3, a % b = 1
If a = 6, b = 7, then,
a + b = 13, a – b = -1, a * b = 42, a / b = 0, a % b = 6

Real Arithmetic Operations


Example: If a = 12.5, b = 2.0, then,
a + b = 14.5, a – b = 10.5, a * b = 25.0, a / b = 6.25

Note: The operator % cannot be used with real operands

Mixed-Mode Arithmetic Operations


Example: If a = 15, b = 10.0, then,
a + b = 25.0, a – b = 5.0, a * b = 150.0, a / b = 1.5

Note: The operator % cannot be used in mixed-mode arithmetic operations


Implicit Type Conversion

• Operands that differ in type may undergo type


conversion before the expression takes on its
final value
• Example: If a=3, b=2.5, then,
c=a+b
= 3.0 + 2.5 (converted to float)
= 5.5 (result is in float)
Rules in Type Conversion
• If both operands are floating-point type whose
precision differ (e.g., a float and a double), then,
lower precision operand will be converted to the
precision of the higher operand.
• That is, an operation between a float and a double
will result in a double.
• Similarly, an operation between a float and an int
will result in a float.
• Also, an operation between an int and a long int will
result in long int
Unary Operators

Operators Example
Unary Minus (-) -a, -3
Increment operator (++) ++a, a++
Decrement operator (--) --a, a--
sizeof operator sizeof(a)
(type) ((int)(i+f) % 4)
Negation operator (!) !(a > b)
Post-Increment & Pre-Increment
Unary Operators

• PRE means do the operation first followed by any


assignment operation.
• POST means do the operation after any assignment
operation.
• Consider the following statements
++count; /* PRE Increment
count++; /* POST Increment
• In the above example, because the value of count is
not assigned to any variable, the effects of the
PRE/POST operation are not clearly visible.
Post-Increment & Pre-Increment
Unary Operators
#include<stdio.h> Same as:
main() count = count+1
loop = count
{
int count=0, loop;
loop = ++count;
printf(“loop = %d, count = %d”, loop, count); Same as:
loop = count
loop = ++count; count = count+1
printf(“loop = %d, count = %d”, loop, count);
}
Type Casting
• The value of an expression can be converted to a
different data type if desired, as shown:
(data type) expression
• This type of construction is known as cast

• Example: If a=7, b=8.5, then,


(a + b) % 4 will be incorrect
So it can be type casted as:
((int) (a + b)) % 4
Relational Operators

Operators Meaning
< Less than
> Greater than
<= Less than or Equal to
>= Greater than or Equal to

Equality == Equal to
Operators
!= Not Equal to
Example of Relational Operators
Example: If a = 1, b = 2, c = 3, then,

Expression Interpretation Value


a<b True 1
! (a < b) False 0
!(!(a<b) True 1
(a + b) >= c True 1
(b + c) > (a + 5) False 0
c != 3 False 0
b ==2 True 1
Note: Relational operators are used to form logical expressions that yields a Boolean value
(false is 0 ; true is 1)
Check: !(x < y) is equivalent to (x >= y)
Logical Operators

Operators Meaning
&& Logical AND
|| Logical OR

Logical operators act upon operands that are themselves logical


expressions
Example of Logical Operators
Example: If a = 7, b = 5.5, c = ‘w’, then,

Expression Interpretation Value


(a >=6) && (c==‘w’) True 1
(a >=6) || (c==119) True 1
(b<11) && (a>100) False 0
(c != ‘p’) || ((a+b) <=10) True 1
Assignment Operators

Operators Example Result


= a=3 a=3
+= a += 4 a=7
-= a -= 2 a=5
*= a *= 3 a = 15
/= a /= 4 a=3
%= a %= 2 a=1

Note: If a = 3, then, c = (a *= 3) = ?
Multiple Assignments

• Multiple assignments are possible in C


• Example: a=b=3
• Assignments are always carried out from Right
to Left
• In the above case, 3 is first assigned to b, and
the value of b is then assigned to a
Difference Between = and ==

• Assignment operator (=) is used to assign a


value to an identifier
• Example: a=3

• Remember
• Equality operator (==) is used to determine if
two expressions have the same value
Conditional / Ternary Operator (?:)
• A conditional expression is written in the form:
expression 1 ? expression 2 : expression 3

Example: a = (b > c) ? b : c;
• When evaluating a conditional expression, expression 1
will be evaluated first. If expression 1 is true, then,
expression 2 is evaluated. However, if expression 1 is
false, expression 3 is evaluated

• Try: Write a program to input two numbers ‘x’ and ‘y’


and display the larger number.
Bitwise Operators
• C also supports bitwise operators for manipulation of
data at bit level.
• Bitwise operators may not be applied to float or double.

Operators Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise EXCLUSIVE OR
<< Shift Left
>> Shift Right
Special Operators
• C also supports various special operators such
as:
– comma operator (used in for loop)
– pointer operators (& and *), and,
– member selection operators (. and ->)
Hierarchy of Operators
Operator Category Operators Associativity
Unary operators - ++ -- ! sizeof (type) RL
Arithmetic multiply, divide * / % LR
and remainder
Arithmetic add and subtract + - LR
Relational operators < <= > >= LR
Equality operators == != LR
Logical and && LR
Logical or || LR
Conditional operator ?: RL
Assignment operators = += -= *= /= %= RL

Operator Precedence is related to the hierarchy of operators, i.e., which operator will be
used first
Questions to Solve
• Evaluate the following expressions:
a) x = -3 * -4 % -6 / -5
b) x = -3 + 4 – 7 * 8 / 5 % 10
c) x = 4 % 5 + 6 % 5
d) y = 2 * 3 /4 + 4 / 4 + 8 – 2 + 5 / 8

• Result:
a) x = 0
b) x = 0
c) x = 5
d) y = 8
Quick Answers to Questions
Which operator has the lowest priority ?
a) ++
b) %
c) +
d) ||

The type cast operator is-


a) (type)
b) cast()
c) //
d) “ “
Quick Answers to Questions
Which operator has the lowest priority ?
a) ++
b) %
c) +
d) ||

The type cast operator is-


a) (type)
b) cast()
c) //
d) “ “
Quick Answers to Questions
Which format specifier is used to print the values of double type variable
a) % ld
b) %f
c) %lf
d) %fd

What is the output of this program ?


void main() {
int a=b=c=10;
a=b=c=50;
printf(“\n %d %d %d”,a,b,c); }
a) 50 50 50
b) Compile Time Error
c) 10 10 10
d) Three Garbage Value
Quick Answers to Questions
Which format specifier is used to print the values of double type variable
a) % ld
b) %f
c) %lf
d) %fd

What is the output of this program ?


void main() {
int a=b=c=10;
a=b=c=50;
printf(“\n %d %d %d”,a,b,c); }
a) 50 50 50
b) Compile Time Error (undefined symbol b)
c) 10 10 10
d) Three Garbage Value
Quick Answers to Questions
What is sizeof In ‘C’ ?
a) Reserved word
b) Operator
c) Both (a) and (b)
d) Function

What will be the value of the variable a, on the execution of the above
program?
void main() {
int a= 0;
for ( ; a ;);
a++; }
a) -1
b) 0
c) 1
d) None of these
Quick Answers to Questions
What is sizeof In ‘C’ ?
a) Reserved word
b) Operator
c) Both (a) and (b)
d) Function

What will be the value of the variable a, on the execution of the above
program?
void main() {
int a= 0;
for ( ; a ;);
a++; }
a) -1
b) 0
c) 1
d) None of these
Quick Answers to Questions
What will be the output ?
void main ( ) {
int x;
unsigned y;
printf(“\n%d %d”, sizeof(x), sizeof(y) ); }
a) 2 2
b) 2 4
c) 4 4
d) None of these
Quick Answers to Questions
What will be the output ?
void main ( ) {
int x;
unsigned y;
printf(“\n%d %d”, sizeof(x), sizeof(y) ); }
a) 2 2
b) 2 4
c) 4 4
d) None of these
Compilation Process in C
Executing a ‘C’ Program

Executing a program written in ‘C’ involves a


series of steps. These are:
1. Creating the program
2. Compiling the program
3. Linking the program with functions that are
needed from the C library, and,
4. Executing the program
System Ready

Program Code Enter Program

Edit Source Program

C Compiler Compile Source Program

Syntax Yes
Errors?
No Object Code
System Library Link With System Library
Executable Object Code
Input Data Executable Object Code

Data Error Logic Logic Error


and Data
Errors?
No Error
Correct Output Fig: Process of
Compiling and
Stop Executing a C Program
• Creating the Program
– The program must be entered into a file.
– The filename consists of letters, digits and special
characters, followed by a dot and a letter c.
– The file is created with the help of a text editor,
either ed or vi.
Example: vi prog1.c
– If the file existed before, it is loaded. If it does not
exist, a new file is created.
– The program that is entered into the file is known as
source program
• Compiling and Linking
– Once the source program has been created in a file, say
prog1.c, it is now ready for compilation.
– The compilation command to achieve this task in Linux is:
gcc prog1.c
– If everything is alright, the compilation proceeds silently
and the translated program is stored on another file with
the name prog1.o. This program is known as object code.

– Linking is the process of putting together other program


files and functions that are required by the program.
– The compiled and linked program is called the executable
object code and is stored automatically in another file
called a.out.
• Executing the Program
– Execution is a simple task.
– The command ./a.out would load the executable
object code into the computer memory and execute
the instructions.
– Sometimes the program does not produce the
desired results. Perhaps, something is wrong with the
program logic or data.
– Then, it would be necessary to correct the source
program or data.
– If the source program is modified, then it must be
compiled, linked and executed again.
Compilation Process

• To compile a C program, we can use the gcc


compiler in Linux, which stands for “GNU
Compiler Collection”, and it is used as follows:
$ gcc hello.c
• This creates an executable called a.out. To run
the executable, you would type
$ ./a.out
The C Compilation
Model

When you invoked the gcc


compiler, a series of steps
were performed in order
to generate an executable
from the text you entered
as your C program.
These steps are as follows:
The Preprocessor

• The main function of the C preprocessor


is to:
– remove comments from the source code,
and,
– interpret preprocessor directives which are
given by the statements that begin with #.
Compiling And Assembling
• Once the C preprocessor has done its job, the compiler
then translates the C code into assembly language,
which is a machine level code that contains instructions
that manipulate the memory and processor.
• This will create a file called “hello.s”

• Usually, you do not need to see the assembly code.


• After creating an assembly code, next the assembler
creates an object code which is usually a binary file. This
will create a file called “hello.o”
Linking

• In order to create the executable hello or a.out,


you need to use the linker to process your
program.
• The linker links other precompiled object files or
libraries together and creates the executable
hello.
Quick Answer to Question
What will be the output of the following program?
Void main ( ) {
Double x=28;
Int r;
R= x%5;
Printf (“\n r=%d”, r); }
a) r= 3
b) Run time Error
c) Compile time Error
d) None of the above
Quick Answer to Question
What will be the output of the following program?
Void main ( ) {
Double x=28;
Int r;
R= x%5;
Printf (“\n r=%d”, r); }
a) r= 3
b) Run time Error
c) Compile time Error
d) None of the above
Quick Answer to Question
What will be the value of x after executing the
following program?
void main ( ) {
int x;
x = printf(“I See, Sea in C”);
printf(“\n x= % d” , x); }
a) x= 15
b) x=2
c) Garbage value
d) Error
Quick Answer to Question
What will be the value of x after executing the
following program?
void main ( ) {
int x;
x = printf(“I See, Sea in C”);
printf(“\n x= % d” , x); }
a) x= 15
b) x=2
c) Garbage value
d) Error (Nonportable pointer conversion)
Standard i/o Functions Used In C
Library Functions Used in C

• C library functions include a number of


input/output functions. Six of these functions
are:
– printf()
– scanf()
– getchar()
– putchar()
– gets()
– puts()
The printf() Library Function
• The printf function does the following:
– Accept a format string followed by a series of arguments
– Apply to each argument, the corresponding format
specifier contained in the format string
– Output the formatted data in the desired format
printf(“control string”,arg1, arg2, …, argn);
– Control string or format specifier contains format
information
– arg1, arg2, …, argn represents the individual output data
items.
Example of using printf() function

#include <stdio.h>
void main()
{
int a = 3, b = 4;
c = a * b;
printf(“%d %d %d”, a, b, c);
}
Format Specifier / Conversion
Character / Control String
Some More Examples of printf() Function

• printf(“Have a Good day!”);

• printf(“The value of a = %d”, a);

• printf(“The value of a= %d \n and the square


of a = %d”, a, a*a);
Using Minimum Field Width
• It can be specified by preceding the conversion
character by an unsigned integer.
• If the number of characters in the corresponding
data item is less than the specified field width, then
the data item will be preceded by enough leading
blanks.
• If the number of characters in the corresponding
data item exceeds the specified field width, then
additional space will be allocated to the data item, so
that the entire data item will be displayed.
Example of Minimum Field Width

Output:
printf(): Precision

• The maximum number of decimal places for a


floating point value , or for characters in a
string can be specified
• A floating point number will be rounded if it
must be shortened to conform to a precision
specification
Example of printf() Precision

float x = 123.456;
printf(“\n %.3f %.2f %.4f”, x, x, x);

Output:

123.456 123.46 123.4560


The scanf() Library Function

• The scanf function can be used to enter any


combination of numerical values, single characters
and strings.
scanf(“control string”,arg1, arg2, …, argn);
• Control string or format specifier contains format
information
• arg1,arg2,…,argn represents the individual input data
items
Commonly Used Conversion Characters for Data Input
Example of scanf() function

int a;
float b;
double p;
char x;

scanf(“%d”, &a);
scanf(“%f”, &b);
scanf(“%lf”, &p);
scanf(“%c”, &x);
The getchar() and putchar()
Library Functions
• Reading a single character can be done using
the function getchar().
• Syntax: variable_name = getchar();

• Similarly, writing a single character can be


done using the function putchar().
• Syntax: putchar(variable_name);
getchar() and putchar(): Example 1
int main()
{
char ch;
printf(“\n Enter any alphabet of your choice :”);
ch = getchar();
ch = ch + 1;
printf(“\n The next character is ”);
putchar(ch);
return 0;
}
The gets() and puts()
Library Functions
• Reading a string can be done using the
function gets().
• Syntax: gets(variable_name);

• Similarly, writing a string can be done using


the function puts().
• Syntax: puts(variable_name);
getchar() and putchar(): Example 1
int main()
{
char n[40];
printf(“\n Enter your name :”);
gets(n);
printf(“\n Your name is : ”);
puts(n);
return 0;
}
Decision Making and Branching
Introduction
C language possesses decision-making
capabilities by supporting the following
decision-making statements:
– if statement
– if-else statement
– switch statement
– Conditional operator statement
– goto statement
The if Statement
• The if statement can be used as follows:

if (expression)
{
statement-block;
}
• Here, if expression is true, then statement-block is
executed. If the expression is false, then, statement-block
is skipped (not executed).
• The statement-block may be a single statement or a group
of statements.
An Example of the if Statement
int main()
{
int x;
printf(“\n Enter a Number : “);
scanf(“%d”, &x);
if (x > 0)
{
printf(“\n The number is : %d”, x);
printf(“\n It is Positive”);
}
return 0;
}
The if-else Statement
• The if … else statement can be used as follows:

if(expression)
{
statement-block1;
}
else
{
statement-block2;
}
• Here, if expression is true, then statement-block1 is executed. If the
expression is false, then, statement-block2, after the else, is executed.
An Example of the if-else Statement
int main()
{
int x;
printf(“\n Enter a Number : “);
scanf(“%d”,&x);
if (x >= 0)
printf(“\n The number %d is positive”, x);
else
printf(“\n The number %d is negative”, x);
return 0;
}
Another Example
int main()
{
int x;
printf(“\n Enter a Number : “);
scanf(“%d”,&x);
if (x > 0)
printf(“\n The number %d is positive”, x);
else if(x < 0)
printf(“\n The number %d is negative”, x);
else if(x == 0)
printf(“\n The number is zero”);
return 0;
}
Try doing the following program
• Write C programs for the following problems:
– to take two numbers as input and display which is the
larger number.
– to enter a number and display whether it is odd or even.
– to input a number and display whether the number is
single-digit or more than single-digit number.
– to input a character and display whether the character is
vowel or not.
– to input three numbers and find out the biggest as well as
smallest among them
Nested if-else statements
When a series of decisions are involved, we may have to use more than one if… else
statement in nested form as shown below:
if (condition1)
{
if (condition2)
{
statement-block1;
Outer Inner }
if if else
{
statement-block2;
}
}
else
{
statement-block3;
}
An Example of Nested if-else
#include <stdio.h>
int main()
{ int n;
printf(“Enter a Number : ”);
scanf(“%d”,&n);
if(n > 0)
{
if ((n>=1) && (n<=9))
printf(“It is single-digit positive number ”);
else
printf(“It is more than single-digit positive number ”);
}
else
printf(“It is either zero or a negative number”);
return 0;
} G. Nandi, Dept. of Computer Sc. & IT, DBU
The switch-case Statement
This control statement allows decision to be made from a number
of choices.

1. It is useful if a variable is
compared with different
constants, and in case it is
equal to a constant.
2. The constant in the case
statement can be of char or
int data type only.
int main()
{ int x, y, res, ch;
switch-case: Example 1
printf(“Enter a Number : ”);
scanf(“%d”,&x);
printf(“Enter another Number : ”);
scanf(“%d”,&y);
printf(“\n Enter Choice: 1. Add 2. Subtract 3. Multiply 4. Divide “);
scanf(“%d”,&ch);
switch(ch)
{
case 1: res = x + y;
break;
case 2: res = x – y;
break;
case 3: res = x * y;
break;
case 4: res = x / y;
break;
default: printf(“\n\n Wrong Choice”);
}
printf(“\n Result = %d “,res);
return 0;
}
int main()
{ char v;
switch-case: Example 2
printf(“Enter a Vowel : ”);
scanf(“%d”,&v);
switch(v)
{
case ‘a’:
case ‘A’: printf(“The vowel is A”);
break;
case ‘e’:
case ‘E’: printf(“The vowel is E”);
break;
case ‘i’:
case ‘I’: printf(“The vowel is I”);
break;
case ‘o’:
case ‘O’: printf(“The vowel is O”);
break;
case ‘u’:
case ‘U’: printf(“The vowel is U”);
break;
default: printf(“\n\n It is not a vowel”);
}
return 0;
}
The goto Statement
• A goto statement is used to branch unconditionally from one
point to another in the program.
• The goto requires a label in order to identify the place where
the branch is to be made.
• The use of goto statement is usually avoided in C programming.
• Example:
int main()
{
int x = 0;
if (x == 0) goto a;
printf(“\n The number is not zero”);
exit(1); // to come out of the program
a: printf(“\n Oops… The number is zero”);
return 0;
}
Quick Answer to Question
What is the output of the following program ?
void main() {
int x=40;y=30;z=80;
if(x<y<z)
printf(“\n Hello world”);
else
printf(“\nGood by”);

a) Hello world
b) Good by
c) Compile time error
d) None of these
Quick Answer to Question
What is the output of the following program ?
void main() {
int x=40;y=30;z=80;
if(x<y<z) X<y -> 0
printf(“\n Hello world”);
else 0<z -> 1
printf(“\nGood by”);

a) Hello world
b) Good by
c) Compile time error
d) None of these
Control Structures: Loops
Control Structures
• Decision Making Statements
– if statement
– if-else statement
– Conditional Operator statement
– switch statement
– goto statement

• Loop Constructs
– while loop
– do-while loop
– for loop
Loop Constructs
Loop Constructs: while loop
• The while loop has the general form:
while (conditional expression)
{
statement-block;
}

• The loop will repeat as long as the condition is true.


• The while tests its condition at the top of the loops.
• Therefore, if the condition is false to begin with, the
loop will not execute at all.
The while Loop: Example 1
// to display numbers from 1 to 20
#include<stdio.h>
int main() Initial Value
{
int i=1;
printf(“\n\n Numbers from 1 to 20 \n\n”);
while(i <= 20)
{ Condition
printf(“\t %d”, i);
i = i + 1;
} Change in
return 0; Value
}
Assignment

• Write ‘C’ programs to display


– all odd numbers from 1 to 100
– all factors of 4 up to 100
– The multiplication table of 8 up to 80
Loop Constructs: do-while loop
• The do-while loop has the general form:
do
{
statement-block;
} while (condition expression);

• The do loop repeats as long as the condition is true.


• The do loop is the only loop in C that will always have
at least one iteration because the condition is tested
at the bottom of the loop.
The do-while Loop: Example 1
// to display numbers from 1 to 20
#include<stdio.h>
int main()
{
int i=1;
printf(“\n\n Numbers from 1 to 20 \n\n”);
do
{
printf(“\t %d”, i);
i = i + 1;
} while(i <= 20);
return 0;
}
Difference Between
while Loop and do-while Loop
int main() int main()
{ {
int i = 10; int i=10;
while(i < 10) do
{ {
printf(“\t %d”, i); printf(“\t %d”, i);
i = i + 1; i = i + 1;
} } while(i < 10);
return 0; return 0;
} }

For the above example, in the first case, the while loop will not be
executed at all.
However, in the second case, the do-while loop will be executed at
least once even if the condition is false.
Loop Constructs: for loop
• This loop is useful when a block of statement is to be
executed a fixed number of times.
• In the syntax given below:
– The initial expression is executed only once
– The test expression is tested once before every iteration. If
it is true the block of statement is executed once else the
loop terminates.
– The update expression is executed once after every
iteration
for (initial expression; test expression; update expression)
{
statement-block;
}
The for Loop: Example 1
//display square of all numbers from 1 to n
#include<stdio.h>
int main()
{
int n, i, sq;
printf(“Enter the limit :”);
scanf(“%d”, &n);
for(i=1; i <= n; i++)
{
sq = i * i;
printf(“\n Square of %d = %d”, i, sq);
}
return 0;
}
Nesting of Loops
• If we are using one loop within another loop that is called as
nested loop. For example:

int main()
{
for(i = 1; i <= 3; i++)
{
for(j = 1; j <= i; j++)
printf(“ * ”);
printf(“\n”);
}
return 0;
}
Valid for Loops
The break and continue Statements

• The break statement terminates the execution


of a loop and the control is transferred to the
statement immediately following the loop
• Can be written as: break;
• The continue statement is used to bypass the
remaining statements after it and the control
is transferred to the beginning of the loop.
• Can be written as: continue;
The break Statement: Example
//display few odd numbers
int main()
{
int n, i=1,x;
printf(“Enter how many numbers :”);
scanf(“%d”, &n);
printf(“ Enter %d odd numbers”, n);
while(i <= n)
{
printf(“ Number ? ”);
scanf(“%d”&x);
if ((x % 2) == 0)
{
printf(“\n Sorry… It is not an odd number”);
break;
}
i++;
}
return 0;
}
The continue Statement: Example
//to find the sum of any five positive numbers
#include<stdio.h>
int main()
{
int n, x = 1, sum = 0;
printf(“Finding the sum of any five positive numbers \n\n”);
while(x <= 5)
{
printf(“\n Enter a positive number (>0) : ”);
scanf(“%d”, &n);
if (n <=0)
continue;
sum = sum + n;
x++;
}
printf(“\n Sum of random five numbers = %d”, sum);
return 0;
}
Questions
1. How does a while loop differ from a do-while
loop?
2. Explain the following along with syntax and
example:
– for loop
– Switch statement
– If-else statement
3. Explain the use of break and continue in case of loops.
4. What do you mean by nesting of loops? Give an
example to illustrate.
Quick Answers to Questions
What is the value of y in the following code?

What among the following represents true statement


either x is in the range of 10 and 50 or y is 0?
Quick Answers to Questions
Concept of Macros
Macros in C
Macros in C
• A macro is a name given to a block of C
statements as a pre-processor directive.
• A macro is defined with the preprocessor
directive, #define.
• Advantage of Using Macro: increases the
execution speed of the program fragment. When
the actual code snippet is to be used, it can be
substituted by the name of the macro. The same
block of statements, on the other hand, need to
be repeatedly hard coded as and when required.
• Disadvantage of Using Macro: The size of the
program increases.
Macros in C: An Example
#include <stdio.h>
#define MACRO1 25
int main(void)
{
#ifdef MACRO1 // test whether MACRO1 is defined...
printf("\n MACRO1 Defined with value [%d]\n", MACRO1);
#endif
return 0;
}
C Tutorial Web Links

• http://www.programiz.com/c-programming/

• http://www.cprogrammingexpert.com/C/
for your patience…
Refresher Course

S-ar putea să vă placă și