KEMBAR78
Fundamentals of c programming techniques | PPT
K.V.Ranga Rao
Dept.of Computer Science
Vignan University
08/11/24
Fundamentals of c programming
The Evolution of Programming Languages
Programming languages fall into three broad categories:
Machine languages
 Assembly languages
 Higher-level languages
08/11/24
Machine Languages
 Machine languages (first-generation languages) are the most
basic type of computer languages, consisting of strings of
numbers the computer's hardware can use.
 Different types of hardware use different machine code. For
example, IBM computers use different machine language than
Apple computers
08/11/24
Assembly Language
 The assembly language program must be translated into m/c
code by a separate program called assembler.
 An assembler converts the assembly code into binary code.
 Advantages of Assembly Language
 Easy to understand and use
 Less Error Prone
 Efficiency
 Disadvantages of Assembly Language
 Machine Dependent
 Harder to Learn
 Less Efficient
08/11/24
08/11/24
Assembler
Assembly
code
Object code
 Third-generation languages
 Fourth-generation languages
 Fifth-generation languages
Higher-level languages are more powerful than assembly
language and allow the programmer to work in a more
English-like environment.
Higher-level programming languages are divided into
three "generations," each more powerful than the last:
High Level Lanugages
FORTAN C
COBOL C++
BASIC Java
Pascal ActiveX
• Third-generation languages (3GLs) are the first to
use true English-like phrasing
• The object code created for one type of system can
be translated for use on a different type of system.
• The following languages are 3GLs:
Higher-Level Languages -
Third-Generation Languages
08/11/24
History of C
ALGOL
BCPL
B
Traditional C
K&R
ANSI C
ANSI/ISO C
1960
1967
1970
1972
1978
1989
1990
International Group
Martin Richards
Ken Thompson
Dennis Ritchie
Kernighan & Ritchie
ANSI Committee
ISO Committee
08/11/24
08/11/24
Limitations of B Language
 Developed for improving Unix System
 Execution of Code faster compared toAssembly Language code
 Does not have DataTypes
08/11/24
Advantages of C
08/11/24
 As a middle-level language, C combines the features of both high-level
and low-level languages
 C is a structured programming language which allows a complex program
to be broken into simpler programs called functions
 C is highly portable and is used for scripting system applications which
form a major part ofWindows, UNIX, and Linux operating system
 C language has a rich library which provides a number of built-in functions
Advantages of C
08/11/24
 C is a general-purpose programming language and can efficiently work
on enterprise applications, games, graphics, and applications requiring
calculations, etc.
 C language is case-sensitive which means lowercase and uppercase letters
are treated differently.
Basic structure of a C program
08/11/24
Documentation section
Link Section
Definition Section
Global Declaration Section
main() function section
{ Declaration Part
Executable part
}
Sub Program Section
function1
………...
Function n
Basic structure of a c program
08/11/24
 Documentation section consists of a set of comment lines
which gives description about the author or program
 Link section provides instructions to the compiler to link
functions from the system library
 Definition Section defines all symbolic constants.
 The variables that are used in more than one function are
declared in the global declaration section.
 Main() function is must in any c program .
 sub program section contains all use defined functions that are
called in main() function.
08/11/24
/* addition of 2 integers* / <- Documentation section
#include<stdio.h> <- Link Section
#define a 5 <- Definition section
#define b 6
void main()
{
int c; // local variable declaration
c=a+b;
printf(“addition of 2 integers is %d”,c);
}
Character set
08/11/24
 Letters ( A…Z, a…..z)
 Digits (0….9)
 Special characters
 White spaces
Special characters
08/11/24
, Comma . Period
; Semicolon : Colon
? Question mark ‘ Apostrophe
“ Quotation mark ! Exclamation mark
| Vertical bar / Slash
 Back slash ~ Tilde
_ Underscore $ Dollar sign
% Percent sign & Ampersand
^ Caret * Asterisk (or multiplication )
- Minus sign + Plus sign
< Less than sign (or opening angle
bracket)
> Greater than sign (or closing angle
bracket)
( Left parenthesis ) Right parenthesis
[ Left bracket ] Right bracket
{ Left brace } Right brace
# Number sign
White spaces
08/11/24
 Blank space
 Horizontal tab
 Carriage return
 New Line
 Form feed
Token
08/11/24
 Smallest individual unit in a c program.
 6 types of tokens
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special symbols
6. operators
Constants
08/11/24
CONSTANTS
Numeric Constants Character constants
Integer Real
Single
character
String
constants
integer constants
08/11/24
 Decimal integer constants
-> consists of one or more decimal digits 0 through 9 preceded by an
optional sign.
ex: 0 276 31467 -7123
 Octal integer constants
-> consists of digit 0 followed by a sequence of one or more digits 0
though 7
 Hexa decimal integer constants
-> consists of one or more digits 0 through 9 or letters through a to f or
A to F preceded with ox or 0X.
Ex: 0x1F 0x9a2F 0XFFFF
Real constants
08/11/24
 A real constant is a sequence of digits with a decimal point. It can be
expressed in either decimal notation or using scientific form.
Ex: 17.458 , .083, +247.0 are valid real constants expressed in decimal
notation.
the real constant 215.65 may be written as 2.1565 e 2 in exponential
( scientific form) form. It’s general form is mantissa e exponent
mantissa can be a real number expressed in decimal notation or can
be an integer. Exponent is an integer with optional plus or minus sign
08/11/24
 What will be the output of the program?
#include<stdio.h>
void main()
{
float d=2.25;
printf("%e,", d);
printf("%f,", d);
printf("%g,", d);
printf("%lf", d);
}
(a) 2.2, 2.50, 2.50, 2.5 (b).2.2e, 2.25f, 2.00, 2.25
© 2.250000e+000, 2.250000, 2.25, 2.250000
(d) error
character constants
08/11/24
 A single character constant contains a single character enclosed with in a
pair of single quote marks.
Ex:‘A’ , ‘5’ ‘+’ etc
 character constants have integer values known as ASCII values.
ex: printf(“%d”, ’a’); would print 97.
 since each single character constant represents an integer value, it is
possible to perform arithmetic operations on single character constants.
 a string constant is a sequence of characters enclosed in double quotes.
Characters can be letters, digits, special characters etc. Ex:“hai”,
“welcome”
identifier
08/11/24
 Every word in c is either a keyword or an identifier.
 First character must be an alphabet or an underscore.
 Must contain only letters, digits or underscore
 Only first 31 characters are significant.
 Must not contain a white space.
Ex:
Which of these is an invalid identifier?
a) wd-count b) wd_count
c) w4count d) wdcountabcd
operators
08/11/24
* Arithmetic operators ( +, -, *, / , % )
* Relational operators ( <, >, <=, >=, ==, !=)
* Logical operators ( &&, ||, !)
* Assignment operators(=, +=, -=, *=, /=….)
* Increment/Decrement operators (++, --)
* conditional operators (?:)
* Bitwise operators ( &, |, ^, <<, >>)
* special operators (comma , size of )
integer arithmetic
08/11/24
 When both operands in a arithmetic expression are integers, the
expression is called arithmetic expression and the operation is called
integer arithmetic.
 integer arithmetic always yields an integer value.
Ex: if a=14 and b=4 then a/b=3
 During integer division, if sign of one operand is negative, then the
result is machine dependent.
ex: -6/7 may be zero or -1.
 during modulo division, the sign of the result is always the sign of the
first operand.
 Ex: -14%3 = -2 14% -3 =2
real and mixed mode arithmetic
08/11/24
 An arithmetic operation involving only real operands is called real
arithmetic
Ex: x=6.0/7.0 = 0.857143
y=-2.0/3.0=-0.666667
 % can not be used with real operands.
 when one of the operands is an integer and another is a real number,
the expression is called mixed mode arithmetic and the result always
will be a real number.
Ex: 15/10.0=1.5
15/10=1
relational operators
08/11/24
 An expression containing a relational operator is termed as relational
expression.
 the value of a relational expression is either 0 or 1.
 general form of a relational expression is
a.e-1 relational operator a.e-2 where ae-1 and ae-2 are arithmetic
expressions which may be constants, variables or their combination.
Ex: 4 <= 10
10 < 7+5
* when arithmetic expressions are used on either side of a relational
operator , the a.e will be evaluated first and then results are compared.
Logical operators
08/11/24
 Logical operators are
logicalAND &&
Logical OR ||
Logical NOT !
 an expression which combines two or more relational expressions is
termed as logical expression which yields either 0 or 1.
 ex: (a>=10) && (b<=5)
Assignment operators
08/11/24
 Used to assign the result of an expression to a variable. It’s
general form will be
v op = exp; which is equivalent to v = v op exp;
where v is a variable, exp is an expression and op is a binary
arithmetic operator.
x= x+1 is equivalent to x+=1 . += is called as short hand
assignment operator.
 Other short hand assignment operators are
-=, *=, /=, %=etc….
Increment/decrement operators
08/11/24
 Increment and decrement operators in c are ++ and --.
 ++ adds 1 to the operand where as – subtracts 1 from the operand.
 Extensively used in for and while loops
 when post fix ++ or – is used with a variable in an expression, the
expression is evaluated first using the original value and variable will be
incremented/ decremented by 1.
 ex: m=5
y=m++;
value of y will be 5 and value of m is incremented to 6.
08/11/24
 When prefix ++ or -- – is used with a variable in an expression, variable
will be incremented/ decremented by 1 and then the expression is
evaluated using the new value of the variable
ex: m=5;
y=++m;
in this case value of y will be 6. as m value is incemented first and
assigned to y.
bitwise operators
08/11/24
 Following are the bitwise operators that are used for
manipulation of data at bit level.
& ……… bitwise AND
| ………... Bitwise OR
^ …………bitwise XOR
<< ……….. Shift left
>> ……….. Shift right
08/11/24
 What will be the output of the following
void main()
{
int a=5;
float b;
printf (“%d”, sizeof(++a +b));
printf(“ %d”, a);
}
(a) 2 6 (b) 2 5 © 4 6 (d) 4 5
08/11/24
• What will be the output of the following
main()
{
int x=100,y;
y= 10 + x++;
printf(“%d”, y);
}
• Find the output of the following
main()
{
int x=5,y=10,z=10;
x=y==z; printf (“%d “, x);
}
08/11/24
 Which of the following is correct .
(a) a>b? c=30;
(b) max= a>b ?a>c ? a: c: b>c ? b:c
(c) return (a>b)?(a:b);
*What will be the output of the following statement ?
printf( 3 + "goodbye");
a) goodbye b) odbye c) bye d) dbye
08/11/24
 What will be the output if the following program is executed.
void main()
{
int i=4,x;
x= ++i + ++i + ++i ;
printf (“%d”,x);
}
(a) 21 (b) 12 © 18 (d) none
08/11/24
 What will be the output if the following program is executed.
void main()
{
int a=10;
printf (“%d %d%d”, a, a++, ++a));
}
 (a) 12 11 11 (b) 12 10 10 © 11 11 12 (d) 10 10 12
08/11/24
 What will be the output of the following.
main()
{
int i=14,j;
j=i>>2;
printf(“%d “,j);
}
a. 3 b. 14 c. 2 d. none
08/11/24
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b=6,c=11;
clrscr();
printf("%d %d %d");
}
What will output when you compile and run the above code?
(a)Garbage value garbage value garbage value
(b)5 6 11
(c)11 6 5
(d)Compiler error
08/11/24
#include<stdio.h>
void main()
{
clrscr();
printf("%d",printf("VIGNANUNIVERSITY"));
getch();
}
What will output when you compile and run the above code?
(a)16VIGNANUNIVERSITY
(b)VIGNANUNIVERSITY16
(c)GarbageVIGNANUNIVERSITY
(d)Compiler error
Evaluation of arithmetic expression
08/11/24
 An arithmetic expression is a combination of variables, constants
and operators arranged as per syntax of the language.
 Expressions are evaluated using assignment statement of the
form variable= expression
 The expression is evaluated first and the result replaces the
previous value of the variable on the left hand side.
Operator precedence andAssociativity
08/11/24
 An arithmetic expression may contain two or more operators.
The order of priority in which the operations are performed in
an expression is called precedence of operators.
 The operators of same precedence are evaluated from either left
to right or right to left depending on the precedence level and
this is the associativity of operators
Operator precedence and associativity table
08/11/24
 Operator associativity precedence
(), [] L to R 1
+,-(unary),++,
--, !, ~, *(pointer), R to L 2
&, sizeof, (type)
*,/, % L to R 3
+,- L to R 4
<<, >> L to R 5
<, <=, > >= L to R 6
++ , != L to R 7
08/11/24
 Operator associativity precedence
& L to R 8
^ L to R 9
| L to R 10
&& L to R 11
|| L to R 12
?: R to L 13
=,*=,/=,%-,+=
-=,&=,^=,|=,<<=
>>= R to L 14
, L to R 15
08/11/24
 The expression a= 30 * 1000 + 2768 evaluates to
(a) 32768 (b) -32768 © 113040 (d) 0
 the expression x = 4 + 2 % -8 evaluates
(a) -6 (b) 6 © 4 (d) none
 the expression a= 7/ 22 * (3.14 +2) * 3/5 evaluates to
(a) 8.28 (b) 6.28 © 3.14 (d) 0
 which of the following arithmetic expressions are valid.
(a) 25/3%2 © -14%3 (e) 7.5 %3
(b) +9/4 + 5 (d) 15.25 +-5.0 (f) (5/3)*3+5%3
 What will be the output of the following arithmetic expression ?
5+3*2%10-8*6
a) -37 b) -42 c) -32 d) -28
key words
08/11/24
int float char struct
short double void typedef
long switch if enum
signed break else union
unsigned case for volatile
auto continue goto while
static const return
register default sizeof
extern do
Modifiers
08/11/24
 The amount of memory space to be allocated for a variable is
derived by modifiers
 Modifiers are prefixed with basic data types to modify (either
increase or decrease) the amount of storage space allocated to a
variable
 For example, storage space for int data type is 4 byte for 32 bit
processor. We can increase the range by using long int which is 8
byte. We can decrease the range by using short int which is 2
byte.
Modifiers
08/11/24
There are 5 modifiers available in C language.They are,
 short
 long
 signed
 unsigned
 long long
C Scopes
08/11/24
 By Scope, we mean accessibility and visibility of the variables at
different points in the program
 A variable or a constant in C has four types of Scope
a. Block scope
b. Function Scope
c. Program scope
d. File scope
Block scope
08/11/24
 A block refers to any sets of statements enclosed in braces
({ and })
 A variable declared within a block has block scope
 If a variable is declared with in a statement block then as soon as
control exits that block, variable will cease to exist
 Such a variable is called as local variable
08/11/24
Block Scope Example
08/11/24
#include <stdio.h>
void main()
{
int x=10;
int i=0;
printf (“the value of x outside while loop is %d”, x);
while (i<3)
{
int x=i ;
printf(“value of x inside while loop is %d”, x);
i++; }
printf(“value of x outside while loop is %d”,x);
}
output of the example
08/11/24
value of x outside while loop is 10
value of x inside while loop is 0
value of x inside while loop is 1
value of x inside while loop is 2
value of x outside while loop is 10
Note :
1. variables declared with same name as those in outer block,
masks the outer block variables while executing the inner block
2. In nested blocks, variables declared outside the inner blocks are
accessible to nested blocks , provided these variables are not re
declared with in inner block
Function Scope
08/11/24
 Function scope indicates that a variable is active and visible from
the beginning to the end of a function
 In C , only go to label has function scope
Example : void main()
{
………
……….
loop: /* go to label has function scope */
…….
go to loop;
……
}
program Scope
08/11/24
 A variable is said to have program scope when it is declared
outside a function
int x = 0; /* program scope */
float y = 0.0; /* program scope */
int main()
{
int i; /* block scope */
. . .
return 0;
}
Here the int variable x and the float variable y have program
scope.
08/11/24
 Variables with program scope are also called global variables,
which are visible among different files.
 These files are the entire source files that make up an executable
program.
 Note that a global variable is declared with an initializer
outside a function.
08/11/24
#include <stdio.h>
int x = 1234; /* program scope */
double y = 1.234567; /* program scope */
void function_1()
{
printf("From function_1:n x=%d, y=%fn", x, y);
}
main()
{ int x = 4321; /* block scope 1*/
int y=7.654312; /* block scope 1*/
function_1();
printf("Within the main block:n x=%d, y=%fn", x, y); /* a
nested block */
08/11/24
{
double y = 7.654321; /* block scope 2 */
function_1();
printf("Within the nested block:n x=%d, y=%fn", x, y); }
return 0;
}
output:
From function_1:
x=1234, y=1.234567
Within the main block: x=4321, y=1.234567
From function_1: x=1234, y=1.234567
Within the nested block: x=4321, y=7.654321
File Scope
08/11/24
 When a global variable is accessible until the end of the file,
variable is said to have file scope
 To allow a variable to have file scope, declare that variable with
static key word before specifying its data type such as
static int x =10;
 A global static variable can be sued any where from the file in
which it was declared but it is not accessible by any other files
 A variable with file scope is visible from its declaration point to
the end of the file
File Scope
08/11/24
int x = 0; /* program scope */
static int y = 0; /* file scope */
static float z = 0.0; /* file scope */
int main()
{
int i; /* block scope */
. . .
return 0;
}
Here the int variable y and the float variable z both have file scope.
Data types
08/11/24
 ANSI c supports three types of data types.
 primary data types
 User defined data types
 Derived data types
Primary Data types
08/11/24
 integer character
 float
 float void
Signed unsigned
int unsigned int
Short int unsigned short int
Long int unsigned long int
char
signed char
unsigned char
float
double
long double
08/11/24
Data Type Bytes Range
char/ signed char 1 -128 to 127
un signed char 1 0 to 255
int/ signed int 2 -32768 to 32767
un signed int 2 0 to 65535
short int/signed short int 2 -32768 to 32767
un signed short int 2 0 to 65535
long int/ signed long int 4 -2147483648 to 2147483647
un signed long int 4 0 to 4294967295
float 4 3.4 e -38 to 3.4 e +38
double 8 1.7 e -308 to 1.7 e +308
long double 10 3.4 e -4932 to 1.1 e +4932
Data Types & Format specifiers
08/11/24
Data Type Format Specifier
char/ signed char %c
un signed char %c
int/ short int %d, %i
un signed int /unsigned short int %u
long int/signed long int %ld
un signed long int %lu
float %e, %f, %g
double %lf
User Defined data types
08/11/24
 typedef
the purpose of type def is to give a new name to the existing data
type. It’s general form is
typedef data type identifier
EX: typedef int x;
if the above statement is executed , we can replace the data
type int in the statement int y; as follows
x y;
enumerated data type
08/11/24
 General form is
enum identifier { value1,…….value n};
enum identifier v1,v2,…vn;
 what will be the output of the following
void main()
{
enum color { red, green=-20, blue, yellow};
enum color x;
x=yellow;
printf(“ %d”,x);
}
(a) -22 (b) -18 © 1 (d) compiler error
Derived data types
08/11/24
 Arrays
 Pointers
 Structures
 unions
Type Qualifiers
 The keywords which are used to modify the properties of a
variable are called type qualifiers.
 C defines type qualifiers that control how variables may be
accessed or modified. C defines two of these qualifiers:
1) const
2) volatile
const
 Constants are also like normal variables. But, only difference is,
their values can’t be modified by the program once they are
defined.
 They refer to fixed values.They are also called as literals
 const data_type variable_name; (or) const data_type
*variable_name.
 When any variable is not qualified by const variable then it’s
default qualifier is not const
Example
08/11/24
What will be output of following program?
#include<stdio.h>
int main()
{
const int a=5;
a++;
printf(“%d”, a);
}
Output:
Compiler error, we cannot modify const variable
Volatile
 The modifier volatile tells the compiler that a variable's value
may be changed in ways not explicitly specified by the program.
Syntax:
volatile data_type variable_name; (or) volatile data_type
*variable_name;
 When any variable has qualified by volatile keyword in
declaration statement then value of variable can be changed by
any external device or hardware interrupt
08/11/24
What is meaning of the declaration:
const volatile int a=6;
Answer:
Value of variable cannot be changed by program (due to const) but
its value can be changed by external device or hardware
interrupt (due to volatile).
Punctuations
08/11/24
 Semi colon
 Colon
 Comma
 Quotation mark
 Apostrophe
 Braces
 Brackets
 parenthesis
Semi colon
08/11/24
 Semicolons are used as statement terminators.
 Semicolons are used to separate one statement from the next.
 Semicolons are used to separate three fields of the for statement
 Preprocessor directives do not end with a semicolon since they
are not actually part of the C language
Ex: void main()
{ int a=5;
int b=10;
printf (“addition is %d”, a+b);
}
Colon
08/11/24
 Colons are used to define labels (places we can jump to)
 Colons also terminate case, and default prefixes that appear in
switch statement
Ex: switch(ch)
{
case‘a’ : printf(“vowel”);
break;
………….
case‘u’ : printf(“vowel”);
break;
}
Comma
08/11/24
 Commas separate items that appear in lists
 We can create multiple variables of the same type. E.g.,
unsigned short beginTime,endTime,elapsedTime;
 Lists are also used with functions having multiple parameters (both
when the function is defined and called)
 Commas separate the parameters of a function
08/11/24
Example :
short add(short x, short y)
{ short z;
z = x+y;
if((x>0)&&(y>0)&&(z<0))z = 32767;
if((x<0)&&(y<0)&&(z>0))z = -32768;
return(z);
}
void main()
{ short a,b;
a=add(2000,2000)
b=0
while(1){
b=add(b,1);
}
Apostrophe
08/11/24
Apostrophes are used to specify character literals
Example :
voidAlphabet(void)
{
unsigned char mych;
for(mych = 'a'; mych <= 'z'; mych++)
{
OutChar(mych); /* Print next letter */
}
}
Quotation marks
08/11/24
 Quotation marks are used to specify string literals
Ex:
void main()
{
char x[20]=“Hello”;
printf(“%s” , x);
}
Braces
08/11/24
 Braces {} are used throughout C program
 The most common application is for creating a compound
statement.
 Each open brace { must be matched with a closing brace }
Brackets
08/11/24
 Square brackets enclose array dimensions (in declarations) and
subscripts (in expressions).
short Fifo[100];
declares an integer array named Fifo consisting of 80 words
numbered from 0 through 99
Parentheses
08/11/24
 Parentheses enclose argument lists that are associated with
function declarations and calls
 They are required even if there are no arguments
 C uses parentheses to control the order in which expressions
are evaluated
 (11+3)/2 yields 7, whereas 11+3/2 yields 12.
 Parentheses are very important when writing expressions
Storage Classes in C
 A storage class defines the scope (visibility) and life time of variables
and/or functions within a C Program.
 Scope:The Scope of a variable is the part of a program in which the
variable may be visible or available.
 Visibility: The program ability to access a variable from the
memory.
 Life time: The Lifetime of a variable is the duration of time in
which a variable exists in the memory during execution.
Storage Classes in C
 C supports four storage class specifiers
 Auto
 register
 static
 extern
Auto storage class
 Automatic variables are declared inside a function in which they are to be
utilized.
 Ex: auto int i, j ;
 Storage : Memory.
 Default initial value:An unpredictable value, which is often called a
garbage value.
 Scope: Local to the block in which the variable is defined.
 Life:Till the control remains within the block in which the variable is
defined.
Register Storage Class
 A register is a small amount of storage available on the CPU
whose contents can be accessed more quickly than storage
available elsewhere.
 Ex: register int i ;
Register Storage Class
 Storage: CPU registers.
 Default initial value: Garbage value
 Scope: Local to the block in which the variable is defined.
 Life:Till the control remains within the block in which the
variable is defined.
Static Storage Class
 the value of static variables persists until the end of the program.
Ex: static int i=1;
 Static variables may be either an internal type or an external
type depending on the place of declaration.
1) Internal static variables (Local)
2) External static variables (Global)
Static Storage Class
 Storage: Memory
 Default initial value: Zero
 Scope: Local to the block in which the variable is defined.
 Life:Value of the variable persists between different function
calls.
External Storage Class
 ‘extern’ is the default storage class of all global variables as well
as functions.The life and scope of the extern (global) variable is
throughout the program.
 Storage: Memory
 Default initial value: Zero
 Scope (visibility): Global.
 Life: As long as the program’s execution doesn’t come to
an end.
scope (visibility) and life of a storage
classes:
Storage
class
How it has
declared
Scope Life time
auto Locally Block Block
Globally - -
register Locally Block Block
Globally - -
static Locally Block Program
Globally File Program
extern Locally Block Program
Globally Program Program
Input – Output in ‘C’
Introduction
• Reading input data, processing it and displaying the
results are the three tasks of any program.
• There are two ways to accept the data.
– In one method, a data value is assigned to the variable with an
assignment statement.
•int year = 2005; char letter = ‘a’; int x = 12345;
– Another way of accepting the data is with functions.
• There are a number of I/O functions in C, based
on the data type. The input/output functions are
classified in two types.
– Formatted functions
– Unformatted functions
Formatted function
• With the formatted functions, the input or
output is formatted as per our requirement.
• All the I/O function are defined as stdio.h
stdio.h
header file.
• Header file should be included in the program
at the beginning.
Input and Output Functions
Formatted Functions Unformatted Functions
printf()
scanf()
getch() putch()
getche() putchar()
getchar() puts()
gets()
Formatted Functions
• It read and write all types
of data values.
• Require format string to
produce formatted result
• Returns value after
execution
Unformatted Functions
• Works only with character
data type
• Do not require format
conversion for formatting
data type
printf() function
• This function displays output with specified format
• It requires format conversion symbol or format string
and variables names to the print the data
• The list of variables are specified in the printf()
statement
• The values of the variables are printed as the
sequence mentioned in printf()
• The format string symbol and variable name should
be the same in number and type
printf() function
• Syntax
printf(“control string”, varialbe1, variable2,..., variableN);
• The control string specifies the field format such as
%d, %s, %g, %f and variables as taken by the
programmer
void main()
{
int NumInt = 2;
float NumFloat=2.2;
char LetterCh = ‘C’;
printf(“%d %f %c”, NumInt, NumFloat, LetterCh);
}
Output :
2 2.2000 C
void main()
{
int NumInt = 65;
clrscr();
printf(“%c %d”, NumInt, NumInt);
}
Output :
A 65
• All the format specification starts with % and a
format specification letter after this symbol.
• It indicates the type of data and its format.
• If the format string does not match with the
corresponding variable, the result will not be
correct.
• Along with format specification use
– Flags
– Width
– Precision
• Flag
– It is used for output justification, numeric signs, decimal
points, trailing zeros.
– The flag (-) justifies the result. If it is not given the default
result is right justification.
• Width
– It sets the minimum field width for an output value.
– Width can be specified through a decimal point or using an
asterisk ‘*’.
Sr. No Format Meaning Explanation
1 %wd Format for integer
output
w is width in integer and d
is conversion specification
2 %w.cf Format for float
numbers
w is width in integer, c
specifies the number of
digits after decimal point
and f specifies the
conversion specification
3 %w.cs Format for string
output
w is width for total
characters, c are used
displaying leading blanks
and s specifies conversion
specification
void main()
{
clrscr();
printf(“n%.2s”,”abcdef”);
printf(“n%.3s”,”abcdef”);
printf(“n%.4s”,”abcdef”);
}
OUTPUT
ab
abc
abcd
void main()
{
int x=55, y=33;
clrscr();
printf(“n %3d”, x – y);
printf(“n %6d”, x – y);
}
OUTPUT
22
22
void main()
{
float g=123.456789;
clrscr();
printf(“n %.1f”, g);
printf(“n %.2f”, g);
printf(“n %.3f”, g);
printf(“n %.4f”, g);
}
OUTPUT
123.5
123.46
123.457
123.4568
scanf() function
• scanf() function reads all the types of data
values.
• It is used for runtime assignment of variables.
• The scanf() statement also requires
conversion symbol to identify the data to be
read during the execution of the program.
• The scanf() stops functioning when some
input entered does not match format string.
scanf() function
Syntax :
scanf(“%d %f %c”, &a, &b, &c);
 Scanf statement requires ‘&’ operator called address
operator
 The address operator prints the memory location of
the variable
 scanf() statement the role of ‘&’ operator is to
indicate the memory location of the variable, so that
the value read would be placed at that location.
scanf() function
 The scanf() function statement also return values.
The return value is exactly equal to the number of
values correctly read.
 If the read value is convertible to the given format,
conversion is made.
void main()
{
int a;
clrscr();
printf(“Enter value of ‘A’ : “);
scanf(“%c”, &a);
printf(“A : %c”,a);
}
OUTPUT
Enter value of ‘A’ : 8
A : 8
void main()
{
char a;
clrscr();
printf(“Enter value of ‘A’ : “);
scanf(“%d”, &a);
printf(“A : %d”,a);
}
OUTPUT
Enter value of ‘A’ : 255
A : 255
Enter value of ‘A’ : 256
A : 256
Sr. No Format Meaning Explanation
1 %wd Format for integer
input
w is width in integer and d
is conversion specification
2 %w.cf Format for float
point input
w is width in integer, c
specifies the number of
digits after decimal point
and f specifies the
conversion specification
3 %w.cs Format for string
input
w is width for total
characters, c are used
displaying leading blanks
and s specifies conversion
specification
Data Type Format string
Integer Short Integer %d or %i
Short unsigned %u
Long signed %ld
Long unsigned %lu
Unsigned hexadecimal %u
Unsigned octal %o
Real Floating %f or %g
Double Floating %lf
Character Signed Character %c
Unsigned Character %c
String %s
Octal number %o
Displays Hexa decimal
number in lowercase
%hx
Displays Hexa decimal
number in lowercase
%p
Aborts program with
error
%n
Escape Sequence
• printf() and scanf() statement
follows the combination of
characters called escape
sequence
• Escape sequence are special
characters starting with ‘’
Escape Sequence Use ASCII value
n New Line 10
b Backspace 8
f Form feed 12
’ Single quote 39
 Backslash 92
0 Null 0
t Horizontal Tab 9
r Carriage Return 13
a Alert 7
” Double Quote 34
v Variable tab 11
? Question mark 63
void main()
{
int a = 1, b = a + 1, c = b + 1, d = c + 1;
clrscr();
printf(“t A = %dnB = %d ’C = %d’”,a,b,c);
printf(“nb***D = %d**”,d);
printf(“n*************”);
printf(“rA = %d B = %d”, a, b);
}
OUTPUT
A = 1
B = 2 ‘C = 3’
***D=4**
A = 1 B = 2******
Unformatted Functions
• C has three types of I/O functions
– Character I/O
– String I/O
– File I/O
– Character I/O
getchar
• This function reads a character type data from
standard input.
• It reads one character at a time till the user presses
the enter key.
• Syntax
VariableName = getchar();
• Example
char c;
c = getchar();
putchar
• This function prints one character on the
screen at a time, read by the standard input.
• Syntax
– puncher(variableName)
• Example
char c = ‘C’;
putchar(c);
getch() and getche()
• These functions read any alphanumeric character
from the standard input device.
• The character entered is not displayed by the getch()
function.
• The character entered is displayed by the getche()
function.
• Exampe
 ch = getch();
 ch = getche();
gets()
• This function is used for accepting any string through stdin
keyword until enter key is pressed.
• The header file stdio.h is needed for implementing the
above function.
• Syntax
char str[length of string in number];
gets(str);
void main()
{
char ch[30];
clrscr();
printf(“Enter the string : “);
gets();
printf(“n Entered string : %s”, ch);
}
puts()
• This function prints the string or character array.
• It is opposite to gets()
char str[length of string in number];
gets(str);
puts(str);
Control statements
08/11/24
 If statement
 Switch statement
 Conditional operator statement
 goto statement
if statement
08/11/24
 Simple if
 if….else
 nested if…..else
 else if ladder
simple if
08/11/24
 General form is
if (test expression)
{
statement block;
}
statement x;
When the test expression is true, statement block will be
executed and control reaches statement x. if the test expression
is false, statement block will be skipped and control jumps to
statement x.
if…….else
08/11/24
General form is
if (test expression)
{
statement x-block;
}
else
{
statement y-block;
}
If test condition is true, statement –x block will be executed otherwise
statement y block will be executed. In either case, either x-block or y-
block statements will be executed.
08/11/24
 What will be the output for the following.
void main()
{
int a=15,b=10,c=5;
if(a>b>c)
printf(“true”);
else
printf (“ false”);
}
08/11/24
 What will be output if you will execute following c code?
#include<stdio.h>
int main(){
float x=12.25, y=13.65;
if(x=y)
printf("x and y are equal");
else
printf("x and y are not equal");
(A) x and y are equal (B) x and y are not equal
(C) It will print nothing (D) Compilation error
08/11/24
 Identify the incorrect one
1.if(c=1)
2.if(c!=3)
3.if(a<b)then
4.if(c==1)
(a) 1 only (b) 1&3 (c) 3 only (d) All of the above
Nested if…else
08/11/24
 General form is
if( test c ondition1)
{
if (test condition2)
{
statement 1;
}
else
{
statement 2;
}
}
else
{
statement 3;
}
statement –x;
else if ladder
08/11/24
if (condition1)
statement-1;
else if (condition2)
statement-2;
else if (condition3)
statement-3;
……………….
else
default statement;
statement- x;
Switch statement
08/11/24
Switch(expression)
{
case value1: statement-1;
break;
……………………………
case value n : statement –n;
break;
default: default statement;
break;
}
08/11/24
 What will be the output of the following program ?
#include <stdio.h>
void main()
{ int a = 2;
switch(a)
{
case 1:
printf("goodbye"); break;
case 2:
continue;
case 3:
printf("bye");
}
}
a) error b) goodbye c) bye d) bye goodbye
08/11/24
 Point out the error, if any, in the program.
main()
{
int i=1;
switch(i)
{
printf(“hello”);
case 1: printf (“Vignan “);
break;
case 2: printf(“university”);
break;
}
}
08/11/24
Point out the error, if any in the program
main()
{
int i=1;
switch(i)
{
case 1: printf (“Vignan “);
break;
case 1*2+0: printf(“university”);
break;
}
08/11/24
Point out the error, if any in the program
main()
{
int i=1;
switch(i)
{
}
printf(“Vignan university”);
}
08/11/24
 Consider the following program segment
int n,sum=1;
switch(n)
{
case 2:sum=sum+2;
case 3:sum*=2;
break;
default: sum=0;
}
If n=2, what is the value of sum
(a) 0 (b) 6 (c) 3 (d) None of these
conditional operator
08/11/24
 General form is
conditional exp? exp1: exp2;
conditional expression will be evaluated first and if the result is non zero,
exp1 will be evaluated otherwise exp2 will be evaluated and returned as
value of the conditional expression.
goto statement
08/11/24
 goto statement is used to jump control from one point to another point in
the same program.
 goto requires a label to identify the place where control is to be moved.
 general form is
goto label; label: statement;
………… …………….
………… ……………
label: statement; goto label;
08/11/24
 Point out the error if any in the following program
main()
{
int i=1;
while(i<=5)
{
printf(“%d”,i);
if(i>2)
goto here;
}
}
fun()
{ here: printf(“Hi”); }
Iterative statements
08/11/24
 While
 do…while
 for
while
08/11/24
 Syntax for while loop is
while (condition)
{
Body of the loop
}
* While is an entry controlled loop.The test condition is
evaluated first and if the condition is true, statements in the
body of the loop will be executed.Then again the condition is
evaluated and if it is true again body of the loop will be
executed.This process will be continued until the condition
becomes false
08/11/24
 What will be the output of the following.
void main()
{
int i=1;
while(i<=10);
{
printf(“%d”,i);
i=i+1;
}
getch();
}
08/11/24
 What will be the output of the following.
void main()
{
int i=1;
while(i<=32767)
{
printf(“%d”,i);
i=i+1;
}
getch();
}
do ……. while
08/11/24
 General form is
do
{
body of the loop
} while (condition);
Do while is an exit controlled loop. First the statements in the
body of the loop will be executed and then condition will be
evaluated. If it is true, again body of loop will be executed and
this process will be continued until the condition became false
08/11/24
 How many times a do while loop is guaranteed to loop?
(a) 0 (b) 1 © infinite (d) variable
 what will be the output of the following
void main()
{ int m=0;
do
{
if(m>10)
continue;
m=m+10;
} while(m<50);
printf(“ %d “,m);
}
for loop
08/11/24
 Syntax of for loop is
for( initialization; test condition; updation)
{
body of the loop
}
* for loop as an entry controlled loop. If the test condition is false
for the first time it self, body of the loop will not be executed
even once.
Arrays
08/11/24
 An array is a fixed size sequential collection of elements of same
data type.
Arrays cal be classified in to
 1-D arrays
 2-D arrays
 Multi dimensional arrays
1-D arrays
08/11/24
 General form for declaring a 1-D array is
type variblename [size];
ex: int x[10]; declares x as an array to contain maximum of 10 integer
elements
 initialization of 1-d array is
type array name[size]={ list of values};
Ex: int x[3]={0,0,0};
if number of initializers is less than declared size, then the remaining
elements are initialized to zero.
ex: int n[5]={1,2};
The first 2 elements are initialized to 1 and 2 and the remaining elements
are initialized to zero.
08/11/24
 What will be the output of the following
void main()
{
int i;
int x[3]={5};
for(i=0;i<=2;i++)
printf(“%d”,x[i]);
}
(a) 5 garbage garbage (b) 5 0 0 © 5 NULL NULL
(d) compiler error
08/11/24
 What will happen if in a C program you assign a value to an
array element whose subscript exceeds the size of array?
A.The element will be set to 0.
B.The compiler would report an error.
C.The program may crash if some important data gets
overwritten
D.The array size would appropriately grow
08/11/24
 What does the following declaration mean?
int (*ptr)[10];
A. ptr is array of pointers to 10 integers
B. ptr is a pointer to an array of 10 integers
C. ptr is an array of 10 integers
D. ptr is an pointer to array
08/11/24
 In C, if you pass an array as an argument to a function, what
actually gets passed?
A.Value of elements in array
B. First element of the array
C. Base address of the array
D.Address of the last element of array
08/11/24
 Which of the following statements are correct about an array?
1. The array int num[26]; can store 26 elements.
2. The expression num[1] designates the very first element in the
array.
3. It is necessary to initialize the array at the time of declaration.
4. The declaration num[SIZE] is allowed if SIZE is a macro.
A. 1 B. 1,4 C. 2,3 D. 2,4
08/11/24
 .Consider the following program
main()
{
int a[5]={1,3,6,7,0};
int *b;
b=&a[2];
}
The value of b[-1] is
(a) 1 (b) 3 (c) -6 (d) none
2-D arrays
08/11/24
 Two dimensional arrays are declared as
type array name [row size][column size];
 Ex: int x[2][3]={0,0,0,1,1,1};
 Initializes the elements of first row to zero and second row to one.
 when an array is initialized with values, size of the first dimension need
not be specified.
 Ex: int x[][3]={{0,0,0},{1,1,1,}};
 If the values are missing in an initializer, they are automatically set to
zero.
ex: int x[2][3]={ {1,1},{2}}; will initialize the first two elements of
first row to one, first element of 2nd
row to 2 and all other elements to
zero.
08/11/24
 Which of the following statements are correct about the program
below?
void main()
{ int size, i;
scanf("%d", &size);
int arr[size];
for(i=1; i<=size; i++)
{ scanf("%d", arr[i]); printf("%d", arr[i]); } return 0; }
 A. The code is erroneous since the subscript for array used in for loop is
in the range 1 to size. B. The code is erroneous since the values of array
are getting scanned through the loop. C. The code is erroneous since the
statement declaring array is invalid. D.The code is correct and runs
successfully.
08/11/24
 #include<stdio.h>
#include<conio.h>
main()
{
int a[3],i;
for(i=0;i<3;i++)
a[i]=i++;
for(i=0;i<3;i++)
printf("t %d", a[i]);
}
What will be the output?
08/11/24
 What will be the output if we execute the following code
void main()
{
char c=125;
c=c+10;
printf(“%d”, c)
}
(a) 135
(b) compiler error
© -121
(d) -8
08/11/24
 What will be the output if we execute the following code
#include<string.h>
void main()
{
int i=0;
for(;i<=2;)
{
printf(“%d”, i++);
}
(a) 0 1 2
(b)0 1 2 3
© 1 2 3
(d) compiler error
Declaring and initializing string
variables
08/11/24
 General form for declaring a string variable is
char string name[ size ];
* size must be equal to the maximum no of characters in the
string plus 1 as compiler automatically appends 0 at the end of
the string
* characters arrays can be initialized similar to the numeric
arrays.
ex: char name [5]={‘c’ , ’z’,’0’};
char name[5]=“cz”;
08/11/24
 What will be output of following code?
void main()
{
char a[5];
a[0]='q';
a[1]='u';
a[2]='e';
printf("%s",a);
getch();
}
reading strings from terminal
08/11/24
 Scanf can be used with %s format specifier to read a string of
characters.
 The problem with scanf is it terminates the input on the first
white space it finds.
 Ex: if we give input as NEW DELHI in to the array x, only the
string NEW will be read in to x.
 We can specify field width using %ws in scanf for reading a
specified number of characters.
 Ex: char name[10];
scanf(“ %5s”,name);
if we give input as krishna , only the string krish will be stored
in name.
Writing strings to the screen
08/11/24
 Printf function with %s format can be used to print strings to
the screen.
 Ex: char x[15]=“ united kingdom”;
printf(“ %15sn”, x);
output: united kingdom
printf(“ %5sn “, x);
Output: united kingdom
printf(“ 15.6sn”, x);
output: united
printf(“% -15.6sn” , x);
Output: united
String handling functions
08/11/24
 Strcat()
 Strcmp()
 Strlen()
 Strcpy()
08/11/24
 What will be the output of the following
void main()
{
char st1[]=“Kolkata”;
char st2[]=“pune”;
strcpy(s1,s2);
printf(“string1 is %s”, s1);
}
* What will be the output of the following.
printf(“%d”, strcmp(“acef” ,“abcd” ) );
08/11/24
 Identify the correct statement
(a) a=b=3=4;
(b) a=b=c=d=0;
© float a= int b = 3.5;
(d) int a; float b; a=b=3.5;
* which of the following is an invalid expression
(a) +0XAB5
(b) -0525
© 15-
(d) +a
08/11/24
main( )
{
unsigned int i=10;
while(i>=0)
{
printf(“%u”, i);
i--;
}
}
how many times the loop will get executed.
(a) 10 (b) 9 © 11 (d) infinite
08/11/24
 what will be the output of the following.
void main()
{
char ch;
int i ;
scanf(“%c”, &i);
scanf(“ %d”, &ch);
printf(“ %c %d”, ch, i);
}
(a)error: suspicious char to int conversion in scanf
(b) error: we may not get input for the second scanf statement
(c) no error
(d) none of the above
08/11/24
 the default return type in the function definition is
(a) void (b) int © float (d) char
 what will be the output of the following program if value 25 is given to
scanf.
void main()
{
int i ;
Printf(“%d”, scanf(“%d”, &i));
}
(a)25 (b) 2 © 1 (d) 5
what will be the output of following.
main()
{ int x=10, y=20; printf(“%d”,x,y);}
function
08/11/24
 A function is a self contained block of statements that are used to
perform a specific task.
Function types are
 Library functions
 User defined functions.
Library functions are the functions which are pre defined.
User defined functions are the functions whose code must be
developed by the user
08/11/24
 Which of the following is correct way to define the function fun() in the
below program?
#include<stdio.h>
void main()
{
int a[3][4];
fun(a);
}
A. void fun(int p[][4]) { } B. void fun(int *p[4]) { }
C. void fun(int *p[][4]) { } D. void fun(int *p[3][4]) { }
Elements of user defined function
08/11/24
 Function definition
 Function call
 Function declaration
Function definition
08/11/24
 General form of a function definition is
function type function name( parameter list)
{
local variable declaration;
executable statement-1;
………….
return statement;
}
Function call
08/11/24
 A function can be called by using the function name followed by
a list of actual parameters , if any, enclosed in parentheses.
 Ex:
main()
{
int x;
x=add(10,5); /* function call */
printf(“ %d “,x);
}
Function declaration
08/11/24
 Also known s function prototype
 Consists of
* function (return )type
* function name
* parameter list
* terminating semicolon
General form is
function type function name( parameter list) ;
Ex: int add(int x, int y);
08/11/24
 What is true about the following c functions.
(a) need not return any value
(b) should always return an integer
© should always return more than one value
(d) should always return any value
Categories of functions
08/11/24
 with arguments, return a value
 With arguments, no return of value
 With out arguments, return a value
 With out arguments, no return of value
 Returns multiple values
with arguments, return a value
08/11/24
int add(int,int);
void main()
{
int a=5,b=6,c;
clrscr();
c=add(a,b);
printf(“addition is %d”,c);
}
int add(int x, int y)
{
return (x+y );
}
With arguments, no return value
08/11/24
void add(int,int);
void main()
{
int a=5,b=6,c;
clrscr();
add(a,b);
printf(“addition is %d”,c);
}
void add(int x, int y)
{
printf(“%d”, x+y );
}
With out arguments, returns a value
08/11/24
int add();
void main()
{
int c;
clrscr();
c=add();
printf(“addition is %d”,c);
}
int add()
{
int x=5,y=6;
printf(“%d”, x+y );
}
08/11/24
Point out the error in the program
f(int a, int b)
{
int a;
a = 20;
return a;
}
(a). Missing parenthesis in return statement
(b)The function should be defined as int f(int a,int b)
© Redeclaration of a
(d) None of above
08/11/24
 what will be the output of the following.
int f(int);
int main()
{
int b;
b = f(20); printf("%dn", b); }
int f(int a)
{
a > 20? return(10): return(20);
}
A. Error: Prototype declaration B. No error C. Error: return statement
cannot be used with conditional operators D. None of above
08/11/24
 Point out the error in the program
void f();
void main()
{
int a=10;
a = f();
printf("%dn", a);
}
void f() { printf("Hi"); }
A. Error: Not allowed assignment
B. Error: Doesn't print anything
C. No error
D. None of above
With out arguments, without return value
08/11/24
void add();
void main()
{
int c;
clrscr();
add();
}
void add()
{
int x=5,y=6;
printf(“%d”, x+y );
}
Function that returns multiple values
08/11/24
int xyz(int *, int *);
void main()
{
int a, b, c, d;
clrscr();
a=5; b=10;
xyz(a, b, &c, &d);
printf(“ sum is %d difference is %d”, c, d);
}
int xyz(int p, int q, int *sum, int *diff)
{
sum = p + q;
diff=p-q; }
08/11/24
int fun(int);
void main()
{
int i=3;
i=fun(i);
i=fun(i);
printf("i is %d",i);
}
fun(int i)
{
if(i%2)
return 0;
else
return 1; } what will be the output?
storage classes
08/11/24
a variable’s storage class describes
 Where the variable will be stored
 The initial value of the variable
 Scope of the variable
 How long would the variable exists
there are 4 storage classes in c
 Automatic
 External
 Static
 Register
automatic
08/11/24
Storage : memory
Default initial value: garbage value
Scope: local to the block in which variable is defined.
Life: till the control remains with in the block in which the variable
is declared.
08/11/24
void increment();
Void main()
{
increment();
increment();
increment();
}
void increment()
{
auto int i=1;
printf(“%d”, i);
i=i+1;
} what will be the output?
register
08/11/24
Storage : cpu registers
Default initial value: garbage value
Scope: local to the block in which variable is defined.
Life: till the control remains with in the block in which the variable
is declared.
static
08/11/24
Storage : memory
Default initial value: zero
Scope: local to the block in which variable is defined.
Life: value of the variable persists between different function calls.
08/11/24
void increment();
Void main()
{
increment();
increment();
increment();
}
void increment()
{
static int i=1;
printf(“%d”, i);
i=i+1;
} what will be the output
extern
08/11/24
Storage : memory
Default initial value: zero
Scope: global
Life: as long as program execution does not come to an end.
08/11/24
int i;
void main()
{
printf(“%d”,i);
increment();
decrement();
}
void increment()
{ i=i+1;
printf(“%d”,i);
}
void decrement()
{ i=i-1; printf(“%d”,i); } find the output
08/11/24
 What will be the output for the following.
int x=10;
void display();
void main()
{
int x=20;
printf(“%d”,x);
display();
}
void display()
{
printf(“%d”,x);
}
08/11/24
int x=21;
void main()
{
extern int y;
printf(“%d %d”,x,y);
}
int y=31;
What will be the output?
08/11/24
 Which of the following is true about the automatic variables with in a
function.
(a)it’s type must be declared before using the variable
(b)They are local
(c) they are global.
Identify the incorrect statement
(a)Automatic variables are automatically initialized to zero.
(b) static variables are automatically initialized to zero.
(c) the address of a register variable is not accessible
(d) static variables can not be initialized with any statement
08/11/24
main()
{
int i=3,x;
while(i>0)
{
x=func(i);
i--;
}
}
int func(int n)
{
static sum=0;
sum=sum + n;
return(sum); }
The final value of x is
(a) 6 (b) 8 (c) 1 (d) 3
08/11/24
 #include <stdio.h>
void func()
{
int x = 0;
static int y = 0;
x++; y++;
printf( "%d %dn", x, y );
}
void main()
{
func();
func();
}
what will be the output?
structures
08/11/24
 A structure is a derived data type.
 It’s general form is
struct tag name
{
data type member-1;
data type membe-2;
…………………….
data type member –n;
}
Accessing structure members
08/11/24
 Structure members can be accessed and assigned with some
values by linking with structure variable .
Ex: struct book bank
{
char title[20];
int pages;
float price;
} b1;
we can assign values to structure members as follows.
b1.pages=200;
b1.price=150.50;
strcpy(b1. title, ”C”);
08/11/24
 Using pointers also, structure members can be accessed. Consider the
following example.
struct abc
{
int a;
float b;
char c;
} e, *p;
(*p).a=5;
p->c=‘a’;
08/11/24
 What will be the output of the following program.
main()
{ struct emp
{
char name[20];
float salary;
} ;
struct emp e1={“dravid” };
printf(“name is %s and salary is %f”, e1.name,e1.salary);
}
Copying and comparing structure variables
08/11/24
 Two variables of same structure can be copied the same way as
ordinary variables.
 If p1 and p2 are two structure variables of same structure, then
the following are valid.
 p1=p2, p2=p1
 The statements such as p1==p2, p1!=p2 are not permitted.
 Structure variables can be compared by comparing members
individually.
08/11/24
 What will be the output of the following program.
main()
{ struct emp
{
char name[20];
int age;
} ;
struct emp e1={“dravid” , 23};
struct emp e2;
e2=e1;
if(e1==e2)
printf(“equal”);
}
Arrays of structures and arrays with in
structures
08/11/24
 In array of structures, each element of the array represents a
structure variable.
 Ex: struct class student[100]; defines an array student that consists
of 100 elements.
 In arrays with in structures, arrays can be used as structure
members.
Ex: struct marks
{
int no;
float subject[3];
} student[2];
Structures with in structures
08/11/24
structures with in structures means nesting of structures.
Consider the following example
Struct salary
{
char name[20];
char dept;
struct
{
int DA;
int HRA;
} allowance;
}employee;
Size of structures
08/11/24
 The unary operator sizeof() can be used to find the size of
structures
 The expression sizeof(struct x) ; will give no of bytes required to
hold all the members of structure x.
 If y is a structure variable of struct x then the expression
sizeof(y) would give the no of bytes required to hold all the
members of structure x
08/11/24
 What will be the output of the following program.
main()
{ struct emp
{
char name[20];
int age;
};
printf(“ size of the structure is %d”, sizeof( struct emp));
}
Bit fields
08/11/24
 General form is
struct tag name
{
data type name1: bit length;
data type name2: bit length;
…………………………….
data type name n: bit length;
}
The data type is either an int or signed int or unsigned int
08/11/24
 Scanf can not be used to read values in to a bit field. First read the value
in to a temporary variable and then assign its value to the bit field.
 Ex : struct personal
{
unsigned sex:1;
unsigned age: 7;
unsigned Children:3;
}emp;
scanf(“%d%d”, & AGE, & CHILDREN”);
emp.age=AGE;
emp. Children= CHILDREN;
* Pointers can not be used to access the bit fields.
unions
08/11/24
 Similar to structures.
 general form is
union tagname
{
data type member1;
……………
……………
};
08/11/24
 unions differ with structures in many aspects.
 in structures , every member has individual memory location where as
in case of unions, the memory of the member of largest data type will be
shared by other members.
 the size of the structure is the number of bytes required to store all the
elements of the structure.The size of the union is the size of the
member of largest data type.
08/11/24
 in structures, all members can be initialized at a time where as in
unions, we can initialize the first member of the union and other
elements will be initialized in sequential statements.
union x
{
int a;
float b;
char c;
}p={10};
printf(“a value is %d”, p.a);
p.b=2.3;
printf(“value of b is %f “ ,p.b);
08/11/24
union {
int no;
char ch;
} u;
u.ch = '2';
u.no = 0;
printf ("%d", u.ch);
What is the output?
a) 2 b) 0 c) null character d) none
08/11/24
 What will be the size of the following union
union abc
{
int x;
float y;
char z;
};
pointers
08/11/24
 Derived data type in c
 Pointer is a variable that stores address of another variable.
 Can be used to return multiple values from a function
 Reduces length and complexity of programs
 Supports dynamic memory management.
Declaring and initializing pointer variable
08/11/24
 General form for pointer declaration is
data type * pt_name;
ex: int *p; declares that p is a pointer variable that points to an integer
data type
* we can use the assignment operator to initialize a pointer variable as
follows
int q;
int *p;
p= &q;
* a pointer variable can be initialized with NULL or 0
int *p=NULL;
int *p=0;
Pointer Arithmetic
08/11/24
 If p1 and p2 are pointers, the following arithmetic operations can be
performed on pointers.
P1+2
p2-4
P1-p2
P1++
 Pointers can be compared using relational operators as follows
P1 == p2
P1!= p2
P1>p2
08/11/24
 Find the output of the following program
main()
{
int x=5, *p;
p=&x
printf("%d",++*p);
}
(a) 5 (b) 6 (c) 0 (d) none of these
scale factor
08/11/24
 When we increment a pointer, its value is increased by length of
the data type that the pointer points to.This length is called as
scale factor
 Ex: if p is an integer pointer with initial value 28, after the
operation p= p+1 ,the value of p1 will be 30 and not 29.
Pointers and arrays
08/11/24
 When an array is declared, compiler allocates a base address and
sufficient storage in contiguous memory locations.
 ex: int x[5]={1,2,3,4,5};
int *p;
p=x;
this is equivalent to p= & x[0]
Files
08/11/24
 A file is a place on the disk where a group of related data is
stored.
 Basic operations on files are
* creating a file
* opening a file
* reading data from a file
* writing data to a file
* closing a file
Input/output operations on files
08/11/24
 Putc() and getc() - to write and read a character to and from
a file
 Putw() and getw()- - to write and read an integer to and from
a file
 fopen () – to create a new file or to open an existing file
 fclose() – to close the file that has been opened for use
 fscanf() and fprintf() – to read set of data values from a file and
to write a set of data values to a file
Random access to files
08/11/24
 ftell() – gives the current position in the file
n= ftell(fp); n would give the current position in bytes.
 rewind() – set the position to beginning of the file
rewind(fp); rewind takes the file pointer to the
beginning of the file.
 fseek() – set the position to the desired point in the file
fseek(file pointer, .offset , position);
ex: fseek(fp , -m, 2); means go back ward by m bytes from
the end of file.
Dynamic memory allocation
08/11/24
 Process of allocating memory at runtime
 Malloc – allocates requested size of bytes and returns a pointer
to the first byte of allocated space.
ptr= (cast type *)malloc(byte size);
 Calloc – allocates memory for an array of elements, initializes
them to zero and returns a pointer to the memory.
ptr= (cast type *)calloc(n, byte size);
 Free- frees previously allocated memory
free(ptr);
 Realloc – modifies size of previously allocated memory.
ptr= (cast type *)realloc(ptr, new size);
08/11/24
 pick out the add one out
a. malloc()
b. calloc()
c. free()
d. realloc()
08/11/24
 . Point out the error/warning in the program?
#include<stdio.h>
int main()
{
unsigned char ch;
FILE *fp;
fp=fopen("trial", "r");
while((ch = getc(fp))!=EOF)
printf("%c", ch);
fclose(fp);
}
A. Error: in unsigned char declaration B. Error: while statement C. No
error D. prints all characters in file "trial"
08/11/24
 What will be the output of the following
#include<stdio.h>
void main()
{
FILE *fp;
fp=fopen(“trail”, ”r”);
fseek(fp,20,SEEK_SET);
fclose(fp);
}
(a)Un recognized word SEEK_SET
(b) fseek() long off set value
(c) no error
(d) none of the above

Fundamentals of c programming techniques

  • 1.
    K.V.Ranga Rao Dept.of ComputerScience Vignan University 08/11/24 Fundamentals of c programming
  • 2.
    The Evolution ofProgramming Languages Programming languages fall into three broad categories: Machine languages  Assembly languages  Higher-level languages 08/11/24
  • 3.
    Machine Languages  Machinelanguages (first-generation languages) are the most basic type of computer languages, consisting of strings of numbers the computer's hardware can use.  Different types of hardware use different machine code. For example, IBM computers use different machine language than Apple computers 08/11/24
  • 4.
    Assembly Language  Theassembly language program must be translated into m/c code by a separate program called assembler.  An assembler converts the assembly code into binary code.  Advantages of Assembly Language  Easy to understand and use  Less Error Prone  Efficiency  Disadvantages of Assembly Language  Machine Dependent  Harder to Learn  Less Efficient 08/11/24
  • 5.
  • 6.
     Third-generation languages Fourth-generation languages  Fifth-generation languages Higher-level languages are more powerful than assembly language and allow the programmer to work in a more English-like environment. Higher-level programming languages are divided into three "generations," each more powerful than the last: High Level Lanugages
  • 7.
    FORTAN C COBOL C++ BASICJava Pascal ActiveX • Third-generation languages (3GLs) are the first to use true English-like phrasing • The object code created for one type of system can be translated for use on a different type of system. • The following languages are 3GLs: Higher-Level Languages - Third-Generation Languages
  • 8.
  • 9.
    ALGOL BCPL B Traditional C K&R ANSI C ANSI/ISOC 1960 1967 1970 1972 1978 1989 1990 International Group Martin Richards Ken Thompson Dennis Ritchie Kernighan & Ritchie ANSI Committee ISO Committee
  • 10.
  • 11.
  • 12.
    Limitations of BLanguage  Developed for improving Unix System  Execution of Code faster compared toAssembly Language code  Does not have DataTypes 08/11/24
  • 13.
    Advantages of C 08/11/24 As a middle-level language, C combines the features of both high-level and low-level languages  C is a structured programming language which allows a complex program to be broken into simpler programs called functions  C is highly portable and is used for scripting system applications which form a major part ofWindows, UNIX, and Linux operating system  C language has a rich library which provides a number of built-in functions
  • 14.
    Advantages of C 08/11/24 C is a general-purpose programming language and can efficiently work on enterprise applications, games, graphics, and applications requiring calculations, etc.  C language is case-sensitive which means lowercase and uppercase letters are treated differently.
  • 15.
    Basic structure ofa C program 08/11/24 Documentation section Link Section Definition Section Global Declaration Section main() function section { Declaration Part Executable part } Sub Program Section function1 ………... Function n
  • 16.
    Basic structure ofa c program 08/11/24  Documentation section consists of a set of comment lines which gives description about the author or program  Link section provides instructions to the compiler to link functions from the system library  Definition Section defines all symbolic constants.  The variables that are used in more than one function are declared in the global declaration section.  Main() function is must in any c program .  sub program section contains all use defined functions that are called in main() function.
  • 17.
    08/11/24 /* addition of2 integers* / <- Documentation section #include<stdio.h> <- Link Section #define a 5 <- Definition section #define b 6 void main() { int c; // local variable declaration c=a+b; printf(“addition of 2 integers is %d”,c); }
  • 18.
    Character set 08/11/24  Letters( A…Z, a…..z)  Digits (0….9)  Special characters  White spaces
  • 19.
    Special characters 08/11/24 , Comma. Period ; Semicolon : Colon ? Question mark ‘ Apostrophe “ Quotation mark ! Exclamation mark | Vertical bar / Slash Back slash ~ Tilde _ Underscore $ Dollar sign % Percent sign & Ampersand ^ Caret * Asterisk (or multiplication ) - Minus sign + Plus sign < Less than sign (or opening angle bracket) > Greater than sign (or closing angle bracket) ( Left parenthesis ) Right parenthesis [ Left bracket ] Right bracket { Left brace } Right brace # Number sign
  • 20.
    White spaces 08/11/24  Blankspace  Horizontal tab  Carriage return  New Line  Form feed
  • 21.
    Token 08/11/24  Smallest individualunit in a c program.  6 types of tokens 1. Keywords 2. Identifiers 3. Constants 4. Strings 5. Special symbols 6. operators
  • 22.
    Constants 08/11/24 CONSTANTS Numeric Constants Characterconstants Integer Real Single character String constants
  • 23.
    integer constants 08/11/24  Decimalinteger constants -> consists of one or more decimal digits 0 through 9 preceded by an optional sign. ex: 0 276 31467 -7123  Octal integer constants -> consists of digit 0 followed by a sequence of one or more digits 0 though 7  Hexa decimal integer constants -> consists of one or more digits 0 through 9 or letters through a to f or A to F preceded with ox or 0X. Ex: 0x1F 0x9a2F 0XFFFF
  • 24.
    Real constants 08/11/24  Areal constant is a sequence of digits with a decimal point. It can be expressed in either decimal notation or using scientific form. Ex: 17.458 , .083, +247.0 are valid real constants expressed in decimal notation. the real constant 215.65 may be written as 2.1565 e 2 in exponential ( scientific form) form. It’s general form is mantissa e exponent mantissa can be a real number expressed in decimal notation or can be an integer. Exponent is an integer with optional plus or minus sign
  • 25.
    08/11/24  What willbe the output of the program? #include<stdio.h> void main() { float d=2.25; printf("%e,", d); printf("%f,", d); printf("%g,", d); printf("%lf", d); } (a) 2.2, 2.50, 2.50, 2.5 (b).2.2e, 2.25f, 2.00, 2.25 © 2.250000e+000, 2.250000, 2.25, 2.250000 (d) error
  • 26.
    character constants 08/11/24  Asingle character constant contains a single character enclosed with in a pair of single quote marks. Ex:‘A’ , ‘5’ ‘+’ etc  character constants have integer values known as ASCII values. ex: printf(“%d”, ’a’); would print 97.  since each single character constant represents an integer value, it is possible to perform arithmetic operations on single character constants.  a string constant is a sequence of characters enclosed in double quotes. Characters can be letters, digits, special characters etc. Ex:“hai”, “welcome”
  • 27.
    identifier 08/11/24  Every wordin c is either a keyword or an identifier.  First character must be an alphabet or an underscore.  Must contain only letters, digits or underscore  Only first 31 characters are significant.  Must not contain a white space. Ex: Which of these is an invalid identifier? a) wd-count b) wd_count c) w4count d) wdcountabcd
  • 28.
    operators 08/11/24 * Arithmetic operators( +, -, *, / , % ) * Relational operators ( <, >, <=, >=, ==, !=) * Logical operators ( &&, ||, !) * Assignment operators(=, +=, -=, *=, /=….) * Increment/Decrement operators (++, --) * conditional operators (?:) * Bitwise operators ( &, |, ^, <<, >>) * special operators (comma , size of )
  • 29.
    integer arithmetic 08/11/24  Whenboth operands in a arithmetic expression are integers, the expression is called arithmetic expression and the operation is called integer arithmetic.  integer arithmetic always yields an integer value. Ex: if a=14 and b=4 then a/b=3  During integer division, if sign of one operand is negative, then the result is machine dependent. ex: -6/7 may be zero or -1.  during modulo division, the sign of the result is always the sign of the first operand.  Ex: -14%3 = -2 14% -3 =2
  • 30.
    real and mixedmode arithmetic 08/11/24  An arithmetic operation involving only real operands is called real arithmetic Ex: x=6.0/7.0 = 0.857143 y=-2.0/3.0=-0.666667  % can not be used with real operands.  when one of the operands is an integer and another is a real number, the expression is called mixed mode arithmetic and the result always will be a real number. Ex: 15/10.0=1.5 15/10=1
  • 31.
    relational operators 08/11/24  Anexpression containing a relational operator is termed as relational expression.  the value of a relational expression is either 0 or 1.  general form of a relational expression is a.e-1 relational operator a.e-2 where ae-1 and ae-2 are arithmetic expressions which may be constants, variables or their combination. Ex: 4 <= 10 10 < 7+5 * when arithmetic expressions are used on either side of a relational operator , the a.e will be evaluated first and then results are compared.
  • 32.
    Logical operators 08/11/24  Logicaloperators are logicalAND && Logical OR || Logical NOT !  an expression which combines two or more relational expressions is termed as logical expression which yields either 0 or 1.  ex: (a>=10) && (b<=5)
  • 33.
    Assignment operators 08/11/24  Usedto assign the result of an expression to a variable. It’s general form will be v op = exp; which is equivalent to v = v op exp; where v is a variable, exp is an expression and op is a binary arithmetic operator. x= x+1 is equivalent to x+=1 . += is called as short hand assignment operator.  Other short hand assignment operators are -=, *=, /=, %=etc….
  • 34.
    Increment/decrement operators 08/11/24  Incrementand decrement operators in c are ++ and --.  ++ adds 1 to the operand where as – subtracts 1 from the operand.  Extensively used in for and while loops  when post fix ++ or – is used with a variable in an expression, the expression is evaluated first using the original value and variable will be incremented/ decremented by 1.  ex: m=5 y=m++; value of y will be 5 and value of m is incremented to 6.
  • 35.
    08/11/24  When prefix++ or -- – is used with a variable in an expression, variable will be incremented/ decremented by 1 and then the expression is evaluated using the new value of the variable ex: m=5; y=++m; in this case value of y will be 6. as m value is incemented first and assigned to y.
  • 36.
    bitwise operators 08/11/24  Followingare the bitwise operators that are used for manipulation of data at bit level. & ……… bitwise AND | ………... Bitwise OR ^ …………bitwise XOR << ……….. Shift left >> ……….. Shift right
  • 37.
    08/11/24  What willbe the output of the following void main() { int a=5; float b; printf (“%d”, sizeof(++a +b)); printf(“ %d”, a); } (a) 2 6 (b) 2 5 © 4 6 (d) 4 5
  • 38.
    08/11/24 • What willbe the output of the following main() { int x=100,y; y= 10 + x++; printf(“%d”, y); } • Find the output of the following main() { int x=5,y=10,z=10; x=y==z; printf (“%d “, x); }
  • 39.
    08/11/24  Which ofthe following is correct . (a) a>b? c=30; (b) max= a>b ?a>c ? a: c: b>c ? b:c (c) return (a>b)?(a:b); *What will be the output of the following statement ? printf( 3 + "goodbye"); a) goodbye b) odbye c) bye d) dbye
  • 40.
    08/11/24  What willbe the output if the following program is executed. void main() { int i=4,x; x= ++i + ++i + ++i ; printf (“%d”,x); } (a) 21 (b) 12 © 18 (d) none
  • 41.
    08/11/24  What willbe the output if the following program is executed. void main() { int a=10; printf (“%d %d%d”, a, a++, ++a)); }  (a) 12 11 11 (b) 12 10 10 © 11 11 12 (d) 10 10 12
  • 42.
    08/11/24  What willbe the output of the following. main() { int i=14,j; j=i>>2; printf(“%d “,j); } a. 3 b. 14 c. 2 d. none
  • 43.
    08/11/24 #include<stdio.h> #include<conio.h> void main() { int a=5,b=6,c=11; clrscr(); printf("%d%d %d"); } What will output when you compile and run the above code? (a)Garbage value garbage value garbage value (b)5 6 11 (c)11 6 5 (d)Compiler error
  • 44.
    08/11/24 #include<stdio.h> void main() { clrscr(); printf("%d",printf("VIGNANUNIVERSITY")); getch(); } What willoutput when you compile and run the above code? (a)16VIGNANUNIVERSITY (b)VIGNANUNIVERSITY16 (c)GarbageVIGNANUNIVERSITY (d)Compiler error
  • 45.
    Evaluation of arithmeticexpression 08/11/24  An arithmetic expression is a combination of variables, constants and operators arranged as per syntax of the language.  Expressions are evaluated using assignment statement of the form variable= expression  The expression is evaluated first and the result replaces the previous value of the variable on the left hand side.
  • 46.
    Operator precedence andAssociativity 08/11/24 An arithmetic expression may contain two or more operators. The order of priority in which the operations are performed in an expression is called precedence of operators.  The operators of same precedence are evaluated from either left to right or right to left depending on the precedence level and this is the associativity of operators
  • 47.
    Operator precedence andassociativity table 08/11/24  Operator associativity precedence (), [] L to R 1 +,-(unary),++, --, !, ~, *(pointer), R to L 2 &, sizeof, (type) *,/, % L to R 3 +,- L to R 4 <<, >> L to R 5 <, <=, > >= L to R 6 ++ , != L to R 7
  • 48.
    08/11/24  Operator associativityprecedence & L to R 8 ^ L to R 9 | L to R 10 && L to R 11 || L to R 12 ?: R to L 13 =,*=,/=,%-,+= -=,&=,^=,|=,<<= >>= R to L 14 , L to R 15
  • 49.
    08/11/24  The expressiona= 30 * 1000 + 2768 evaluates to (a) 32768 (b) -32768 © 113040 (d) 0  the expression x = 4 + 2 % -8 evaluates (a) -6 (b) 6 © 4 (d) none  the expression a= 7/ 22 * (3.14 +2) * 3/5 evaluates to (a) 8.28 (b) 6.28 © 3.14 (d) 0  which of the following arithmetic expressions are valid. (a) 25/3%2 © -14%3 (e) 7.5 %3 (b) +9/4 + 5 (d) 15.25 +-5.0 (f) (5/3)*3+5%3  What will be the output of the following arithmetic expression ? 5+3*2%10-8*6 a) -37 b) -42 c) -32 d) -28
  • 50.
    key words 08/11/24 int floatchar struct short double void typedef long switch if enum signed break else union unsigned case for volatile auto continue goto while static const return register default sizeof extern do
  • 51.
    Modifiers 08/11/24  The amountof memory space to be allocated for a variable is derived by modifiers  Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount of storage space allocated to a variable  For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the range by using long int which is 8 byte. We can decrease the range by using short int which is 2 byte.
  • 52.
    Modifiers 08/11/24 There are 5modifiers available in C language.They are,  short  long  signed  unsigned  long long
  • 53.
    C Scopes 08/11/24  ByScope, we mean accessibility and visibility of the variables at different points in the program  A variable or a constant in C has four types of Scope a. Block scope b. Function Scope c. Program scope d. File scope
  • 54.
    Block scope 08/11/24  Ablock refers to any sets of statements enclosed in braces ({ and })  A variable declared within a block has block scope  If a variable is declared with in a statement block then as soon as control exits that block, variable will cease to exist  Such a variable is called as local variable
  • 55.
  • 56.
    08/11/24 #include <stdio.h> void main() { intx=10; int i=0; printf (“the value of x outside while loop is %d”, x); while (i<3) { int x=i ; printf(“value of x inside while loop is %d”, x); i++; } printf(“value of x outside while loop is %d”,x); }
  • 57.
    output of theexample 08/11/24 value of x outside while loop is 10 value of x inside while loop is 0 value of x inside while loop is 1 value of x inside while loop is 2 value of x outside while loop is 10 Note : 1. variables declared with same name as those in outer block, masks the outer block variables while executing the inner block 2. In nested blocks, variables declared outside the inner blocks are accessible to nested blocks , provided these variables are not re declared with in inner block
  • 58.
    Function Scope 08/11/24  Functionscope indicates that a variable is active and visible from the beginning to the end of a function  In C , only go to label has function scope Example : void main() { ……… ………. loop: /* go to label has function scope */ ……. go to loop; …… }
  • 59.
    program Scope 08/11/24  Avariable is said to have program scope when it is declared outside a function int x = 0; /* program scope */ float y = 0.0; /* program scope */ int main() { int i; /* block scope */ . . . return 0; } Here the int variable x and the float variable y have program scope.
  • 60.
    08/11/24  Variables withprogram scope are also called global variables, which are visible among different files.  These files are the entire source files that make up an executable program.  Note that a global variable is declared with an initializer outside a function.
  • 61.
    08/11/24 #include <stdio.h> int x= 1234; /* program scope */ double y = 1.234567; /* program scope */ void function_1() { printf("From function_1:n x=%d, y=%fn", x, y); } main() { int x = 4321; /* block scope 1*/ int y=7.654312; /* block scope 1*/ function_1(); printf("Within the main block:n x=%d, y=%fn", x, y); /* a nested block */
  • 62.
    08/11/24 { double y =7.654321; /* block scope 2 */ function_1(); printf("Within the nested block:n x=%d, y=%fn", x, y); } return 0; } output: From function_1: x=1234, y=1.234567 Within the main block: x=4321, y=1.234567 From function_1: x=1234, y=1.234567 Within the nested block: x=4321, y=7.654321
  • 63.
    File Scope 08/11/24  Whena global variable is accessible until the end of the file, variable is said to have file scope  To allow a variable to have file scope, declare that variable with static key word before specifying its data type such as static int x =10;  A global static variable can be sued any where from the file in which it was declared but it is not accessible by any other files  A variable with file scope is visible from its declaration point to the end of the file
  • 64.
    File Scope 08/11/24 int x= 0; /* program scope */ static int y = 0; /* file scope */ static float z = 0.0; /* file scope */ int main() { int i; /* block scope */ . . . return 0; } Here the int variable y and the float variable z both have file scope.
  • 65.
    Data types 08/11/24  ANSIc supports three types of data types.  primary data types  User defined data types  Derived data types
  • 66.
    Primary Data types 08/11/24 integer character  float  float void Signed unsigned int unsigned int Short int unsigned short int Long int unsigned long int char signed char unsigned char float double long double
  • 67.
    08/11/24 Data Type BytesRange char/ signed char 1 -128 to 127 un signed char 1 0 to 255 int/ signed int 2 -32768 to 32767 un signed int 2 0 to 65535 short int/signed short int 2 -32768 to 32767 un signed short int 2 0 to 65535 long int/ signed long int 4 -2147483648 to 2147483647 un signed long int 4 0 to 4294967295 float 4 3.4 e -38 to 3.4 e +38 double 8 1.7 e -308 to 1.7 e +308 long double 10 3.4 e -4932 to 1.1 e +4932
  • 68.
    Data Types &Format specifiers 08/11/24 Data Type Format Specifier char/ signed char %c un signed char %c int/ short int %d, %i un signed int /unsigned short int %u long int/signed long int %ld un signed long int %lu float %e, %f, %g double %lf
  • 69.
    User Defined datatypes 08/11/24  typedef the purpose of type def is to give a new name to the existing data type. It’s general form is typedef data type identifier EX: typedef int x; if the above statement is executed , we can replace the data type int in the statement int y; as follows x y;
  • 70.
    enumerated data type 08/11/24 General form is enum identifier { value1,…….value n}; enum identifier v1,v2,…vn;  what will be the output of the following void main() { enum color { red, green=-20, blue, yellow}; enum color x; x=yellow; printf(“ %d”,x); } (a) -22 (b) -18 © 1 (d) compiler error
  • 71.
    Derived data types 08/11/24 Arrays  Pointers  Structures  unions
  • 72.
    Type Qualifiers  Thekeywords which are used to modify the properties of a variable are called type qualifiers.  C defines type qualifiers that control how variables may be accessed or modified. C defines two of these qualifiers: 1) const 2) volatile
  • 73.
    const  Constants arealso like normal variables. But, only difference is, their values can’t be modified by the program once they are defined.  They refer to fixed values.They are also called as literals  const data_type variable_name; (or) const data_type *variable_name.  When any variable is not qualified by const variable then it’s default qualifier is not const
  • 74.
    Example 08/11/24 What will beoutput of following program? #include<stdio.h> int main() { const int a=5; a++; printf(“%d”, a); } Output: Compiler error, we cannot modify const variable
  • 75.
    Volatile  The modifiervolatile tells the compiler that a variable's value may be changed in ways not explicitly specified by the program. Syntax: volatile data_type variable_name; (or) volatile data_type *variable_name;  When any variable has qualified by volatile keyword in declaration statement then value of variable can be changed by any external device or hardware interrupt
  • 76.
    08/11/24 What is meaningof the declaration: const volatile int a=6; Answer: Value of variable cannot be changed by program (due to const) but its value can be changed by external device or hardware interrupt (due to volatile).
  • 77.
    Punctuations 08/11/24  Semi colon Colon  Comma  Quotation mark  Apostrophe  Braces  Brackets  parenthesis
  • 78.
    Semi colon 08/11/24  Semicolonsare used as statement terminators.  Semicolons are used to separate one statement from the next.  Semicolons are used to separate three fields of the for statement  Preprocessor directives do not end with a semicolon since they are not actually part of the C language Ex: void main() { int a=5; int b=10; printf (“addition is %d”, a+b); }
  • 79.
    Colon 08/11/24  Colons areused to define labels (places we can jump to)  Colons also terminate case, and default prefixes that appear in switch statement Ex: switch(ch) { case‘a’ : printf(“vowel”); break; …………. case‘u’ : printf(“vowel”); break; }
  • 80.
    Comma 08/11/24  Commas separateitems that appear in lists  We can create multiple variables of the same type. E.g., unsigned short beginTime,endTime,elapsedTime;  Lists are also used with functions having multiple parameters (both when the function is defined and called)  Commas separate the parameters of a function
  • 81.
    08/11/24 Example : short add(shortx, short y) { short z; z = x+y; if((x>0)&&(y>0)&&(z<0))z = 32767; if((x<0)&&(y<0)&&(z>0))z = -32768; return(z); } void main() { short a,b; a=add(2000,2000) b=0 while(1){ b=add(b,1); }
  • 82.
    Apostrophe 08/11/24 Apostrophes are usedto specify character literals Example : voidAlphabet(void) { unsigned char mych; for(mych = 'a'; mych <= 'z'; mych++) { OutChar(mych); /* Print next letter */ } }
  • 83.
    Quotation marks 08/11/24  Quotationmarks are used to specify string literals Ex: void main() { char x[20]=“Hello”; printf(“%s” , x); }
  • 84.
    Braces 08/11/24  Braces {}are used throughout C program  The most common application is for creating a compound statement.  Each open brace { must be matched with a closing brace }
  • 85.
    Brackets 08/11/24  Square bracketsenclose array dimensions (in declarations) and subscripts (in expressions). short Fifo[100]; declares an integer array named Fifo consisting of 80 words numbered from 0 through 99
  • 86.
    Parentheses 08/11/24  Parentheses encloseargument lists that are associated with function declarations and calls  They are required even if there are no arguments  C uses parentheses to control the order in which expressions are evaluated  (11+3)/2 yields 7, whereas 11+3/2 yields 12.  Parentheses are very important when writing expressions
  • 87.
    Storage Classes inC  A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program.  Scope:The Scope of a variable is the part of a program in which the variable may be visible or available.  Visibility: The program ability to access a variable from the memory.  Life time: The Lifetime of a variable is the duration of time in which a variable exists in the memory during execution.
  • 88.
    Storage Classes inC  C supports four storage class specifiers  Auto  register  static  extern
  • 89.
    Auto storage class Automatic variables are declared inside a function in which they are to be utilized.  Ex: auto int i, j ;  Storage : Memory.  Default initial value:An unpredictable value, which is often called a garbage value.  Scope: Local to the block in which the variable is defined.  Life:Till the control remains within the block in which the variable is defined.
  • 90.
    Register Storage Class A register is a small amount of storage available on the CPU whose contents can be accessed more quickly than storage available elsewhere.  Ex: register int i ;
  • 91.
    Register Storage Class Storage: CPU registers.  Default initial value: Garbage value  Scope: Local to the block in which the variable is defined.  Life:Till the control remains within the block in which the variable is defined.
  • 92.
    Static Storage Class the value of static variables persists until the end of the program. Ex: static int i=1;  Static variables may be either an internal type or an external type depending on the place of declaration. 1) Internal static variables (Local) 2) External static variables (Global)
  • 93.
    Static Storage Class Storage: Memory  Default initial value: Zero  Scope: Local to the block in which the variable is defined.  Life:Value of the variable persists between different function calls.
  • 94.
    External Storage Class ‘extern’ is the default storage class of all global variables as well as functions.The life and scope of the extern (global) variable is throughout the program.  Storage: Memory  Default initial value: Zero  Scope (visibility): Global.  Life: As long as the program’s execution doesn’t come to an end.
  • 95.
    scope (visibility) andlife of a storage classes: Storage class How it has declared Scope Life time auto Locally Block Block Globally - - register Locally Block Block Globally - - static Locally Block Program Globally File Program extern Locally Block Program Globally Program Program
  • 96.
    Input – Outputin ‘C’
  • 97.
    Introduction • Reading inputdata, processing it and displaying the results are the three tasks of any program. • There are two ways to accept the data. – In one method, a data value is assigned to the variable with an assignment statement. •int year = 2005; char letter = ‘a’; int x = 12345; – Another way of accepting the data is with functions. • There are a number of I/O functions in C, based on the data type. The input/output functions are classified in two types. – Formatted functions – Unformatted functions
  • 98.
    Formatted function • Withthe formatted functions, the input or output is formatted as per our requirement. • All the I/O function are defined as stdio.h stdio.h header file. • Header file should be included in the program at the beginning.
  • 99.
    Input and OutputFunctions Formatted Functions Unformatted Functions printf() scanf() getch() putch() getche() putchar() getchar() puts() gets()
  • 100.
    Formatted Functions • Itread and write all types of data values. • Require format string to produce formatted result • Returns value after execution Unformatted Functions • Works only with character data type • Do not require format conversion for formatting data type
  • 101.
    printf() function • Thisfunction displays output with specified format • It requires format conversion symbol or format string and variables names to the print the data • The list of variables are specified in the printf() statement • The values of the variables are printed as the sequence mentioned in printf() • The format string symbol and variable name should be the same in number and type
  • 102.
    printf() function • Syntax printf(“controlstring”, varialbe1, variable2,..., variableN); • The control string specifies the field format such as %d, %s, %g, %f and variables as taken by the programmer
  • 103.
    void main() { int NumInt= 2; float NumFloat=2.2; char LetterCh = ‘C’; printf(“%d %f %c”, NumInt, NumFloat, LetterCh); } Output : 2 2.2000 C
  • 104.
    void main() { int NumInt= 65; clrscr(); printf(“%c %d”, NumInt, NumInt); } Output : A 65
  • 105.
    • All theformat specification starts with % and a format specification letter after this symbol. • It indicates the type of data and its format. • If the format string does not match with the corresponding variable, the result will not be correct. • Along with format specification use – Flags – Width – Precision
  • 106.
    • Flag – Itis used for output justification, numeric signs, decimal points, trailing zeros. – The flag (-) justifies the result. If it is not given the default result is right justification. • Width – It sets the minimum field width for an output value. – Width can be specified through a decimal point or using an asterisk ‘*’.
  • 107.
    Sr. No FormatMeaning Explanation 1 %wd Format for integer output w is width in integer and d is conversion specification 2 %w.cf Format for float numbers w is width in integer, c specifies the number of digits after decimal point and f specifies the conversion specification 3 %w.cs Format for string output w is width for total characters, c are used displaying leading blanks and s specifies conversion specification
  • 108.
  • 109.
    void main() { int x=55,y=33; clrscr(); printf(“n %3d”, x – y); printf(“n %6d”, x – y); } OUTPUT 22 22
  • 110.
    void main() { float g=123.456789; clrscr(); printf(“n%.1f”, g); printf(“n %.2f”, g); printf(“n %.3f”, g); printf(“n %.4f”, g); } OUTPUT 123.5 123.46 123.457 123.4568
  • 111.
    scanf() function • scanf()function reads all the types of data values. • It is used for runtime assignment of variables. • The scanf() statement also requires conversion symbol to identify the data to be read during the execution of the program. • The scanf() stops functioning when some input entered does not match format string.
  • 112.
    scanf() function Syntax : scanf(“%d%f %c”, &a, &b, &c);  Scanf statement requires ‘&’ operator called address operator  The address operator prints the memory location of the variable  scanf() statement the role of ‘&’ operator is to indicate the memory location of the variable, so that the value read would be placed at that location.
  • 113.
    scanf() function  Thescanf() function statement also return values. The return value is exactly equal to the number of values correctly read.  If the read value is convertible to the given format, conversion is made.
  • 114.
    void main() { int a; clrscr(); printf(“Entervalue of ‘A’ : “); scanf(“%c”, &a); printf(“A : %c”,a); } OUTPUT Enter value of ‘A’ : 8 A : 8
  • 115.
    void main() { char a; clrscr(); printf(“Entervalue of ‘A’ : “); scanf(“%d”, &a); printf(“A : %d”,a); } OUTPUT Enter value of ‘A’ : 255 A : 255 Enter value of ‘A’ : 256 A : 256
  • 116.
    Sr. No FormatMeaning Explanation 1 %wd Format for integer input w is width in integer and d is conversion specification 2 %w.cf Format for float point input w is width in integer, c specifies the number of digits after decimal point and f specifies the conversion specification 3 %w.cs Format for string input w is width for total characters, c are used displaying leading blanks and s specifies conversion specification
  • 117.
    Data Type Formatstring Integer Short Integer %d or %i Short unsigned %u Long signed %ld Long unsigned %lu Unsigned hexadecimal %u Unsigned octal %o Real Floating %f or %g Double Floating %lf Character Signed Character %c Unsigned Character %c String %s Octal number %o Displays Hexa decimal number in lowercase %hx Displays Hexa decimal number in lowercase %p Aborts program with error %n
  • 118.
    Escape Sequence • printf()and scanf() statement follows the combination of characters called escape sequence • Escape sequence are special characters starting with ‘’ Escape Sequence Use ASCII value n New Line 10 b Backspace 8 f Form feed 12 ’ Single quote 39 Backslash 92 0 Null 0 t Horizontal Tab 9 r Carriage Return 13 a Alert 7 ” Double Quote 34 v Variable tab 11 ? Question mark 63
  • 119.
    void main() { int a= 1, b = a + 1, c = b + 1, d = c + 1; clrscr(); printf(“t A = %dnB = %d ’C = %d’”,a,b,c); printf(“nb***D = %d**”,d); printf(“n*************”); printf(“rA = %d B = %d”, a, b); } OUTPUT A = 1 B = 2 ‘C = 3’ ***D=4** A = 1 B = 2******
  • 120.
    Unformatted Functions • Chas three types of I/O functions – Character I/O – String I/O – File I/O – Character I/O
  • 121.
    getchar • This functionreads a character type data from standard input. • It reads one character at a time till the user presses the enter key. • Syntax VariableName = getchar(); • Example char c; c = getchar();
  • 122.
    putchar • This functionprints one character on the screen at a time, read by the standard input. • Syntax – puncher(variableName) • Example char c = ‘C’; putchar(c);
  • 123.
    getch() and getche() •These functions read any alphanumeric character from the standard input device. • The character entered is not displayed by the getch() function. • The character entered is displayed by the getche() function. • Exampe  ch = getch();  ch = getche();
  • 124.
    gets() • This functionis used for accepting any string through stdin keyword until enter key is pressed. • The header file stdio.h is needed for implementing the above function. • Syntax char str[length of string in number]; gets(str); void main() { char ch[30]; clrscr(); printf(“Enter the string : “); gets(); printf(“n Entered string : %s”, ch); }
  • 125.
    puts() • This functionprints the string or character array. • It is opposite to gets() char str[length of string in number]; gets(str); puts(str);
  • 126.
    Control statements 08/11/24  Ifstatement  Switch statement  Conditional operator statement  goto statement
  • 127.
    if statement 08/11/24  Simpleif  if….else  nested if…..else  else if ladder
  • 128.
    simple if 08/11/24  Generalform is if (test expression) { statement block; } statement x; When the test expression is true, statement block will be executed and control reaches statement x. if the test expression is false, statement block will be skipped and control jumps to statement x.
  • 129.
    if…….else 08/11/24 General form is if(test expression) { statement x-block; } else { statement y-block; } If test condition is true, statement –x block will be executed otherwise statement y block will be executed. In either case, either x-block or y- block statements will be executed.
  • 130.
    08/11/24  What willbe the output for the following. void main() { int a=15,b=10,c=5; if(a>b>c) printf(“true”); else printf (“ false”); }
  • 131.
    08/11/24  What willbe output if you will execute following c code? #include<stdio.h> int main(){ float x=12.25, y=13.65; if(x=y) printf("x and y are equal"); else printf("x and y are not equal"); (A) x and y are equal (B) x and y are not equal (C) It will print nothing (D) Compilation error
  • 132.
    08/11/24  Identify theincorrect one 1.if(c=1) 2.if(c!=3) 3.if(a<b)then 4.if(c==1) (a) 1 only (b) 1&3 (c) 3 only (d) All of the above
  • 133.
    Nested if…else 08/11/24  Generalform is if( test c ondition1) { if (test condition2) { statement 1; } else { statement 2; } } else { statement 3; } statement –x;
  • 134.
    else if ladder 08/11/24 if(condition1) statement-1; else if (condition2) statement-2; else if (condition3) statement-3; ………………. else default statement; statement- x;
  • 135.
    Switch statement 08/11/24 Switch(expression) { case value1:statement-1; break; …………………………… case value n : statement –n; break; default: default statement; break; }
  • 136.
    08/11/24  What willbe the output of the following program ? #include <stdio.h> void main() { int a = 2; switch(a) { case 1: printf("goodbye"); break; case 2: continue; case 3: printf("bye"); } } a) error b) goodbye c) bye d) bye goodbye
  • 137.
    08/11/24  Point outthe error, if any, in the program. main() { int i=1; switch(i) { printf(“hello”); case 1: printf (“Vignan “); break; case 2: printf(“university”); break; } }
  • 138.
    08/11/24 Point out theerror, if any in the program main() { int i=1; switch(i) { case 1: printf (“Vignan “); break; case 1*2+0: printf(“university”); break; }
  • 139.
    08/11/24 Point out theerror, if any in the program main() { int i=1; switch(i) { } printf(“Vignan university”); }
  • 140.
    08/11/24  Consider thefollowing program segment int n,sum=1; switch(n) { case 2:sum=sum+2; case 3:sum*=2; break; default: sum=0; } If n=2, what is the value of sum (a) 0 (b) 6 (c) 3 (d) None of these
  • 141.
    conditional operator 08/11/24  Generalform is conditional exp? exp1: exp2; conditional expression will be evaluated first and if the result is non zero, exp1 will be evaluated otherwise exp2 will be evaluated and returned as value of the conditional expression.
  • 142.
    goto statement 08/11/24  gotostatement is used to jump control from one point to another point in the same program.  goto requires a label to identify the place where control is to be moved.  general form is goto label; label: statement; ………… ……………. ………… …………… label: statement; goto label;
  • 143.
    08/11/24  Point outthe error if any in the following program main() { int i=1; while(i<=5) { printf(“%d”,i); if(i>2) goto here; } } fun() { here: printf(“Hi”); }
  • 144.
  • 145.
    while 08/11/24  Syntax forwhile loop is while (condition) { Body of the loop } * While is an entry controlled loop.The test condition is evaluated first and if the condition is true, statements in the body of the loop will be executed.Then again the condition is evaluated and if it is true again body of the loop will be executed.This process will be continued until the condition becomes false
  • 146.
    08/11/24  What willbe the output of the following. void main() { int i=1; while(i<=10); { printf(“%d”,i); i=i+1; } getch(); }
  • 147.
    08/11/24  What willbe the output of the following. void main() { int i=1; while(i<=32767) { printf(“%d”,i); i=i+1; } getch(); }
  • 148.
    do ……. while 08/11/24 General form is do { body of the loop } while (condition); Do while is an exit controlled loop. First the statements in the body of the loop will be executed and then condition will be evaluated. If it is true, again body of loop will be executed and this process will be continued until the condition became false
  • 149.
    08/11/24  How manytimes a do while loop is guaranteed to loop? (a) 0 (b) 1 © infinite (d) variable  what will be the output of the following void main() { int m=0; do { if(m>10) continue; m=m+10; } while(m<50); printf(“ %d “,m); }
  • 150.
    for loop 08/11/24  Syntaxof for loop is for( initialization; test condition; updation) { body of the loop } * for loop as an entry controlled loop. If the test condition is false for the first time it self, body of the loop will not be executed even once.
  • 151.
    Arrays 08/11/24  An arrayis a fixed size sequential collection of elements of same data type. Arrays cal be classified in to  1-D arrays  2-D arrays  Multi dimensional arrays
  • 152.
    1-D arrays 08/11/24  Generalform for declaring a 1-D array is type variblename [size]; ex: int x[10]; declares x as an array to contain maximum of 10 integer elements  initialization of 1-d array is type array name[size]={ list of values}; Ex: int x[3]={0,0,0}; if number of initializers is less than declared size, then the remaining elements are initialized to zero. ex: int n[5]={1,2}; The first 2 elements are initialized to 1 and 2 and the remaining elements are initialized to zero.
  • 153.
    08/11/24  What willbe the output of the following void main() { int i; int x[3]={5}; for(i=0;i<=2;i++) printf(“%d”,x[i]); } (a) 5 garbage garbage (b) 5 0 0 © 5 NULL NULL (d) compiler error
  • 154.
    08/11/24  What willhappen if in a C program you assign a value to an array element whose subscript exceeds the size of array? A.The element will be set to 0. B.The compiler would report an error. C.The program may crash if some important data gets overwritten D.The array size would appropriately grow
  • 155.
    08/11/24  What doesthe following declaration mean? int (*ptr)[10]; A. ptr is array of pointers to 10 integers B. ptr is a pointer to an array of 10 integers C. ptr is an array of 10 integers D. ptr is an pointer to array
  • 156.
    08/11/24  In C,if you pass an array as an argument to a function, what actually gets passed? A.Value of elements in array B. First element of the array C. Base address of the array D.Address of the last element of array
  • 157.
    08/11/24  Which ofthe following statements are correct about an array? 1. The array int num[26]; can store 26 elements. 2. The expression num[1] designates the very first element in the array. 3. It is necessary to initialize the array at the time of declaration. 4. The declaration num[SIZE] is allowed if SIZE is a macro. A. 1 B. 1,4 C. 2,3 D. 2,4
  • 158.
    08/11/24  .Consider thefollowing program main() { int a[5]={1,3,6,7,0}; int *b; b=&a[2]; } The value of b[-1] is (a) 1 (b) 3 (c) -6 (d) none
  • 159.
    2-D arrays 08/11/24  Twodimensional arrays are declared as type array name [row size][column size];  Ex: int x[2][3]={0,0,0,1,1,1};  Initializes the elements of first row to zero and second row to one.  when an array is initialized with values, size of the first dimension need not be specified.  Ex: int x[][3]={{0,0,0},{1,1,1,}};  If the values are missing in an initializer, they are automatically set to zero. ex: int x[2][3]={ {1,1},{2}}; will initialize the first two elements of first row to one, first element of 2nd row to 2 and all other elements to zero.
  • 160.
    08/11/24  Which ofthe following statements are correct about the program below? void main() { int size, i; scanf("%d", &size); int arr[size]; for(i=1; i<=size; i++) { scanf("%d", arr[i]); printf("%d", arr[i]); } return 0; }  A. The code is erroneous since the subscript for array used in for loop is in the range 1 to size. B. The code is erroneous since the values of array are getting scanned through the loop. C. The code is erroneous since the statement declaring array is invalid. D.The code is correct and runs successfully.
  • 161.
  • 162.
    08/11/24  What willbe the output if we execute the following code void main() { char c=125; c=c+10; printf(“%d”, c) } (a) 135 (b) compiler error © -121 (d) -8
  • 163.
    08/11/24  What willbe the output if we execute the following code #include<string.h> void main() { int i=0; for(;i<=2;) { printf(“%d”, i++); } (a) 0 1 2 (b)0 1 2 3 © 1 2 3 (d) compiler error
  • 164.
    Declaring and initializingstring variables 08/11/24  General form for declaring a string variable is char string name[ size ]; * size must be equal to the maximum no of characters in the string plus 1 as compiler automatically appends 0 at the end of the string * characters arrays can be initialized similar to the numeric arrays. ex: char name [5]={‘c’ , ’z’,’0’}; char name[5]=“cz”;
  • 165.
    08/11/24  What willbe output of following code? void main() { char a[5]; a[0]='q'; a[1]='u'; a[2]='e'; printf("%s",a); getch(); }
  • 166.
    reading strings fromterminal 08/11/24  Scanf can be used with %s format specifier to read a string of characters.  The problem with scanf is it terminates the input on the first white space it finds.  Ex: if we give input as NEW DELHI in to the array x, only the string NEW will be read in to x.  We can specify field width using %ws in scanf for reading a specified number of characters.  Ex: char name[10]; scanf(“ %5s”,name); if we give input as krishna , only the string krish will be stored in name.
  • 167.
    Writing strings tothe screen 08/11/24  Printf function with %s format can be used to print strings to the screen.  Ex: char x[15]=“ united kingdom”; printf(“ %15sn”, x); output: united kingdom printf(“ %5sn “, x); Output: united kingdom printf(“ 15.6sn”, x); output: united printf(“% -15.6sn” , x); Output: united
  • 168.
    String handling functions 08/11/24 Strcat()  Strcmp()  Strlen()  Strcpy()
  • 169.
    08/11/24  What willbe the output of the following void main() { char st1[]=“Kolkata”; char st2[]=“pune”; strcpy(s1,s2); printf(“string1 is %s”, s1); } * What will be the output of the following. printf(“%d”, strcmp(“acef” ,“abcd” ) );
  • 170.
    08/11/24  Identify thecorrect statement (a) a=b=3=4; (b) a=b=c=d=0; © float a= int b = 3.5; (d) int a; float b; a=b=3.5; * which of the following is an invalid expression (a) +0XAB5 (b) -0525 © 15- (d) +a
  • 171.
    08/11/24 main( ) { unsigned inti=10; while(i>=0) { printf(“%u”, i); i--; } } how many times the loop will get executed. (a) 10 (b) 9 © 11 (d) infinite
  • 172.
    08/11/24  what willbe the output of the following. void main() { char ch; int i ; scanf(“%c”, &i); scanf(“ %d”, &ch); printf(“ %c %d”, ch, i); } (a)error: suspicious char to int conversion in scanf (b) error: we may not get input for the second scanf statement (c) no error (d) none of the above
  • 173.
    08/11/24  the defaultreturn type in the function definition is (a) void (b) int © float (d) char  what will be the output of the following program if value 25 is given to scanf. void main() { int i ; Printf(“%d”, scanf(“%d”, &i)); } (a)25 (b) 2 © 1 (d) 5 what will be the output of following. main() { int x=10, y=20; printf(“%d”,x,y);}
  • 174.
    function 08/11/24  A functionis a self contained block of statements that are used to perform a specific task. Function types are  Library functions  User defined functions. Library functions are the functions which are pre defined. User defined functions are the functions whose code must be developed by the user
  • 175.
    08/11/24  Which ofthe following is correct way to define the function fun() in the below program? #include<stdio.h> void main() { int a[3][4]; fun(a); } A. void fun(int p[][4]) { } B. void fun(int *p[4]) { } C. void fun(int *p[][4]) { } D. void fun(int *p[3][4]) { }
  • 176.
    Elements of userdefined function 08/11/24  Function definition  Function call  Function declaration
  • 177.
    Function definition 08/11/24  Generalform of a function definition is function type function name( parameter list) { local variable declaration; executable statement-1; …………. return statement; }
  • 178.
    Function call 08/11/24  Afunction can be called by using the function name followed by a list of actual parameters , if any, enclosed in parentheses.  Ex: main() { int x; x=add(10,5); /* function call */ printf(“ %d “,x); }
  • 179.
    Function declaration 08/11/24  Alsoknown s function prototype  Consists of * function (return )type * function name * parameter list * terminating semicolon General form is function type function name( parameter list) ; Ex: int add(int x, int y);
  • 180.
    08/11/24  What istrue about the following c functions. (a) need not return any value (b) should always return an integer © should always return more than one value (d) should always return any value
  • 181.
    Categories of functions 08/11/24 with arguments, return a value  With arguments, no return of value  With out arguments, return a value  With out arguments, no return of value  Returns multiple values
  • 182.
    with arguments, returna value 08/11/24 int add(int,int); void main() { int a=5,b=6,c; clrscr(); c=add(a,b); printf(“addition is %d”,c); } int add(int x, int y) { return (x+y ); }
  • 183.
    With arguments, noreturn value 08/11/24 void add(int,int); void main() { int a=5,b=6,c; clrscr(); add(a,b); printf(“addition is %d”,c); } void add(int x, int y) { printf(“%d”, x+y ); }
  • 184.
    With out arguments,returns a value 08/11/24 int add(); void main() { int c; clrscr(); c=add(); printf(“addition is %d”,c); } int add() { int x=5,y=6; printf(“%d”, x+y ); }
  • 185.
    08/11/24 Point out theerror in the program f(int a, int b) { int a; a = 20; return a; } (a). Missing parenthesis in return statement (b)The function should be defined as int f(int a,int b) © Redeclaration of a (d) None of above
  • 186.
    08/11/24  what willbe the output of the following. int f(int); int main() { int b; b = f(20); printf("%dn", b); } int f(int a) { a > 20? return(10): return(20); } A. Error: Prototype declaration B. No error C. Error: return statement cannot be used with conditional operators D. None of above
  • 187.
    08/11/24  Point outthe error in the program void f(); void main() { int a=10; a = f(); printf("%dn", a); } void f() { printf("Hi"); } A. Error: Not allowed assignment B. Error: Doesn't print anything C. No error D. None of above
  • 188.
    With out arguments,without return value 08/11/24 void add(); void main() { int c; clrscr(); add(); } void add() { int x=5,y=6; printf(“%d”, x+y ); }
  • 189.
    Function that returnsmultiple values 08/11/24 int xyz(int *, int *); void main() { int a, b, c, d; clrscr(); a=5; b=10; xyz(a, b, &c, &d); printf(“ sum is %d difference is %d”, c, d); } int xyz(int p, int q, int *sum, int *diff) { sum = p + q; diff=p-q; }
  • 190.
    08/11/24 int fun(int); void main() { inti=3; i=fun(i); i=fun(i); printf("i is %d",i); } fun(int i) { if(i%2) return 0; else return 1; } what will be the output?
  • 191.
    storage classes 08/11/24 a variable’sstorage class describes  Where the variable will be stored  The initial value of the variable  Scope of the variable  How long would the variable exists there are 4 storage classes in c  Automatic  External  Static  Register
  • 192.
    automatic 08/11/24 Storage : memory Defaultinitial value: garbage value Scope: local to the block in which variable is defined. Life: till the control remains with in the block in which the variable is declared.
  • 193.
    08/11/24 void increment(); Void main() { increment(); increment(); increment(); } voidincrement() { auto int i=1; printf(“%d”, i); i=i+1; } what will be the output?
  • 194.
    register 08/11/24 Storage : cpuregisters Default initial value: garbage value Scope: local to the block in which variable is defined. Life: till the control remains with in the block in which the variable is declared.
  • 195.
    static 08/11/24 Storage : memory Defaultinitial value: zero Scope: local to the block in which variable is defined. Life: value of the variable persists between different function calls.
  • 196.
    08/11/24 void increment(); Void main() { increment(); increment(); increment(); } voidincrement() { static int i=1; printf(“%d”, i); i=i+1; } what will be the output
  • 197.
    extern 08/11/24 Storage : memory Defaultinitial value: zero Scope: global Life: as long as program execution does not come to an end.
  • 198.
    08/11/24 int i; void main() { printf(“%d”,i); increment(); decrement(); } voidincrement() { i=i+1; printf(“%d”,i); } void decrement() { i=i-1; printf(“%d”,i); } find the output
  • 199.
    08/11/24  What willbe the output for the following. int x=10; void display(); void main() { int x=20; printf(“%d”,x); display(); } void display() { printf(“%d”,x); }
  • 200.
    08/11/24 int x=21; void main() { externint y; printf(“%d %d”,x,y); } int y=31; What will be the output?
  • 201.
    08/11/24  Which ofthe following is true about the automatic variables with in a function. (a)it’s type must be declared before using the variable (b)They are local (c) they are global. Identify the incorrect statement (a)Automatic variables are automatically initialized to zero. (b) static variables are automatically initialized to zero. (c) the address of a register variable is not accessible (d) static variables can not be initialized with any statement
  • 202.
    08/11/24 main() { int i=3,x; while(i>0) { x=func(i); i--; } } int func(intn) { static sum=0; sum=sum + n; return(sum); } The final value of x is (a) 6 (b) 8 (c) 1 (d) 3
  • 203.
    08/11/24  #include <stdio.h> voidfunc() { int x = 0; static int y = 0; x++; y++; printf( "%d %dn", x, y ); } void main() { func(); func(); } what will be the output?
  • 204.
    structures 08/11/24  A structureis a derived data type.  It’s general form is struct tag name { data type member-1; data type membe-2; ……………………. data type member –n; }
  • 205.
    Accessing structure members 08/11/24 Structure members can be accessed and assigned with some values by linking with structure variable . Ex: struct book bank { char title[20]; int pages; float price; } b1; we can assign values to structure members as follows. b1.pages=200; b1.price=150.50; strcpy(b1. title, ”C”);
  • 206.
    08/11/24  Using pointersalso, structure members can be accessed. Consider the following example. struct abc { int a; float b; char c; } e, *p; (*p).a=5; p->c=‘a’;
  • 207.
    08/11/24  What willbe the output of the following program. main() { struct emp { char name[20]; float salary; } ; struct emp e1={“dravid” }; printf(“name is %s and salary is %f”, e1.name,e1.salary); }
  • 208.
    Copying and comparingstructure variables 08/11/24  Two variables of same structure can be copied the same way as ordinary variables.  If p1 and p2 are two structure variables of same structure, then the following are valid.  p1=p2, p2=p1  The statements such as p1==p2, p1!=p2 are not permitted.  Structure variables can be compared by comparing members individually.
  • 209.
    08/11/24  What willbe the output of the following program. main() { struct emp { char name[20]; int age; } ; struct emp e1={“dravid” , 23}; struct emp e2; e2=e1; if(e1==e2) printf(“equal”); }
  • 210.
    Arrays of structuresand arrays with in structures 08/11/24  In array of structures, each element of the array represents a structure variable.  Ex: struct class student[100]; defines an array student that consists of 100 elements.  In arrays with in structures, arrays can be used as structure members. Ex: struct marks { int no; float subject[3]; } student[2];
  • 211.
    Structures with instructures 08/11/24 structures with in structures means nesting of structures. Consider the following example Struct salary { char name[20]; char dept; struct { int DA; int HRA; } allowance; }employee;
  • 212.
    Size of structures 08/11/24 The unary operator sizeof() can be used to find the size of structures  The expression sizeof(struct x) ; will give no of bytes required to hold all the members of structure x.  If y is a structure variable of struct x then the expression sizeof(y) would give the no of bytes required to hold all the members of structure x
  • 213.
    08/11/24  What willbe the output of the following program. main() { struct emp { char name[20]; int age; }; printf(“ size of the structure is %d”, sizeof( struct emp)); }
  • 214.
    Bit fields 08/11/24  Generalform is struct tag name { data type name1: bit length; data type name2: bit length; ……………………………. data type name n: bit length; } The data type is either an int or signed int or unsigned int
  • 215.
    08/11/24  Scanf cannot be used to read values in to a bit field. First read the value in to a temporary variable and then assign its value to the bit field.  Ex : struct personal { unsigned sex:1; unsigned age: 7; unsigned Children:3; }emp; scanf(“%d%d”, & AGE, & CHILDREN”); emp.age=AGE; emp. Children= CHILDREN; * Pointers can not be used to access the bit fields.
  • 216.
    unions 08/11/24  Similar tostructures.  general form is union tagname { data type member1; …………… …………… };
  • 217.
    08/11/24  unions differwith structures in many aspects.  in structures , every member has individual memory location where as in case of unions, the memory of the member of largest data type will be shared by other members.  the size of the structure is the number of bytes required to store all the elements of the structure.The size of the union is the size of the member of largest data type.
  • 218.
    08/11/24  in structures,all members can be initialized at a time where as in unions, we can initialize the first member of the union and other elements will be initialized in sequential statements. union x { int a; float b; char c; }p={10}; printf(“a value is %d”, p.a); p.b=2.3; printf(“value of b is %f “ ,p.b);
  • 219.
    08/11/24 union { int no; charch; } u; u.ch = '2'; u.no = 0; printf ("%d", u.ch); What is the output? a) 2 b) 0 c) null character d) none
  • 220.
    08/11/24  What willbe the size of the following union union abc { int x; float y; char z; };
  • 221.
    pointers 08/11/24  Derived datatype in c  Pointer is a variable that stores address of another variable.  Can be used to return multiple values from a function  Reduces length and complexity of programs  Supports dynamic memory management.
  • 222.
    Declaring and initializingpointer variable 08/11/24  General form for pointer declaration is data type * pt_name; ex: int *p; declares that p is a pointer variable that points to an integer data type * we can use the assignment operator to initialize a pointer variable as follows int q; int *p; p= &q; * a pointer variable can be initialized with NULL or 0 int *p=NULL; int *p=0;
  • 223.
    Pointer Arithmetic 08/11/24  Ifp1 and p2 are pointers, the following arithmetic operations can be performed on pointers. P1+2 p2-4 P1-p2 P1++  Pointers can be compared using relational operators as follows P1 == p2 P1!= p2 P1>p2
  • 224.
    08/11/24  Find theoutput of the following program main() { int x=5, *p; p=&x printf("%d",++*p); } (a) 5 (b) 6 (c) 0 (d) none of these
  • 225.
    scale factor 08/11/24  Whenwe increment a pointer, its value is increased by length of the data type that the pointer points to.This length is called as scale factor  Ex: if p is an integer pointer with initial value 28, after the operation p= p+1 ,the value of p1 will be 30 and not 29.
  • 226.
    Pointers and arrays 08/11/24 When an array is declared, compiler allocates a base address and sufficient storage in contiguous memory locations.  ex: int x[5]={1,2,3,4,5}; int *p; p=x; this is equivalent to p= & x[0]
  • 227.
    Files 08/11/24  A fileis a place on the disk where a group of related data is stored.  Basic operations on files are * creating a file * opening a file * reading data from a file * writing data to a file * closing a file
  • 228.
    Input/output operations onfiles 08/11/24  Putc() and getc() - to write and read a character to and from a file  Putw() and getw()- - to write and read an integer to and from a file  fopen () – to create a new file or to open an existing file  fclose() – to close the file that has been opened for use  fscanf() and fprintf() – to read set of data values from a file and to write a set of data values to a file
  • 229.
    Random access tofiles 08/11/24  ftell() – gives the current position in the file n= ftell(fp); n would give the current position in bytes.  rewind() – set the position to beginning of the file rewind(fp); rewind takes the file pointer to the beginning of the file.  fseek() – set the position to the desired point in the file fseek(file pointer, .offset , position); ex: fseek(fp , -m, 2); means go back ward by m bytes from the end of file.
  • 230.
    Dynamic memory allocation 08/11/24 Process of allocating memory at runtime  Malloc – allocates requested size of bytes and returns a pointer to the first byte of allocated space. ptr= (cast type *)malloc(byte size);  Calloc – allocates memory for an array of elements, initializes them to zero and returns a pointer to the memory. ptr= (cast type *)calloc(n, byte size);  Free- frees previously allocated memory free(ptr);  Realloc – modifies size of previously allocated memory. ptr= (cast type *)realloc(ptr, new size);
  • 231.
    08/11/24  pick outthe add one out a. malloc() b. calloc() c. free() d. realloc()
  • 232.
    08/11/24  . Pointout the error/warning in the program? #include<stdio.h> int main() { unsigned char ch; FILE *fp; fp=fopen("trial", "r"); while((ch = getc(fp))!=EOF) printf("%c", ch); fclose(fp); } A. Error: in unsigned char declaration B. Error: while statement C. No error D. prints all characters in file "trial"
  • 233.
    08/11/24  What willbe the output of the following #include<stdio.h> void main() { FILE *fp; fp=fopen(“trail”, ”r”); fseek(fp,20,SEEK_SET); fclose(fp); } (a)Un recognized word SEEK_SET (b) fseek() long off set value (c) no error (d) none of the above