0% found this document useful (0 votes)
36 views

Cse-It - Day1 C Programming

This document provides an overview of enhancing programming skills in C programming. It discusses topics like the introduction to C programming, the structure of a C program, compilation and linking process, constants, variables and data types, expressions and operators, and input and output operations. The duration for each topic ranges from 0.25 to 1 hour. It also discusses why C is commonly used, its applications, standards, and popular implementations.

Uploaded by

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

Cse-It - Day1 C Programming

This document provides an overview of enhancing programming skills in C programming. It discusses topics like the introduction to C programming, the structure of a C program, compilation and linking process, constants, variables and data types, expressions and operators, and input and output operations. The duration for each topic ranges from 0.25 to 1 hour. It also discusses why C is commonly used, its applications, standards, and popular implementations.

Uploaded by

venkat raj
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 137

Enhancing Programming Skills-C Programming

ENHANCING PROGRAMMING SKILLS

C Programming
Enhancing Programming Skills-C Programming

Topic Highlights
S.No Topics Duration
(in hours)

1 Introduction to C Programming 0.25

2 Structure of a C program 0.25

3 Compilation and Linking Process 0.5

4 Constants, Variables and Data Types 1

5 Expressions and Operators 1

6 Input and Output operations 1


Enhancing Programming Skills-C Programming

Introduction to C Programming

• C is general-purpose programming language.


• C was originally developed by Dennis Ritchie between 1969
and 1973 at AT&T Bell Labs.
• C has been standardized by the American National Standards
Institute (ANSI) since 1989 and subsequently by the
International Organization for Standardization (ISO).
Enhancing Programming Skills-C Programming

Why C?

• Performance
– Execution Time
• Interfacing directly with hardware
• Higher level than Assembly Language

– Provides greater abstraction than Assembly Language &


Machine Language
Enhancing Programming Skills-C Programming

Where C is used?

• Embedded Systems
• System Programming
– Operating Systems
– Compilers

– Linkers
Enhancing Programming Skills-C Programming

Popular Applications Written in C

• Kernels of OS - Linux, Windows, Mac OS X


• Some scripting languages like PHP, Python, PERL
• Numerical Computing Softwares: MATLAB, Mathematica,
GNU Scientific Library
• Core of VLC Media Player

• Earlier Java Compiler


Enhancing Programming Skills-C Programming

C Standards

• The current standard for Programming Language C (C11) is


ISO/IEC 9899:2011, published 2011-12-08.
• Previous Standards
– C 99
– C 89/90
Enhancing Programming Skills-C Programming

Structure of C Program

• Preprocessor Directives
– #include, #define

– Header Files
• Main function
• Comments
– Can be placed anywhere

• Other Use-defined functions


Enhancing Programming Skills-C Programming

Structure of C Program
#include <stdio.h>
int main()
{
/*This is main function*/
printf(“Hello World”);
return 0;  
}
Enhancing Programming Skills-C Programming

Structure of C Program
Enhancing Programming Skills-C Programming

Preprocessor Directives & Header Files

• A header file is a file containing C declarations and macro definitions to be

shared between several source files.

• A header files can be programmer defined or compiler supported

• A header file used in the program by including it, with the C preprocessing

directive #include.

• Example: <stdio.h>, <stdlib.h>


– Note <conio.h> is non-standard header file supported by Turbo C. It is not supported

by ISO C.
Enhancing Programming Skills-C Programming

main() Function

There are two valid declarations:


– int main(void)
– int main(int argc, char *argv[])
• Some non-standard compilers also use void main()
Enhancing Programming Skills-C Programming

Comments

• C89 supports only

/*This is comment*/
• C99 and upwards also supports

//This is comment
Enhancing Programming Skills-C Programming

Popular C Implementations

• GCC
• Visual Studio C++
• Clang
• Intel C

• Recommended IDE for C development


– Code Blocks
Enhancing Programming Skills-C Programming

QUIZ

1. Who developed C?

2. What is the return type of main function in C?


3. Name the applications developed using C.

4. What is the primary use of C language?


5. What type of language is C?
Enhancing Programming Skills-C Programming

Compilation and Linking Process


Enhancing Programming Skills-C Programming

C language program is passed through the


following steps

1.C preprocessor

2.C compiler

3.Assembler

4.Linker
Enhancing Programming Skills-C Programming

E d it o r

So urc e C o d e Pr e pr oc e s s or He a d e r F ile s

C o mp i l e r

A s s e mb l e r

O b jec t C o d e

O b jec t F ile s L in ker L i br a r i e s

E x e c ut a b l e f i l e s

St a g e s of C o mp i l a t i o n a n d E x e c ut i o n
Enhancing Programming Skills-C Programming

C preprocessor
These special preprocessor statements libraries include the following.

• # include: The preprocessor adds the information about the object code
used in the body of the main function. These files are called header files.

• # define: this directive assigns a symbolic name to a constant. Symbolic


names are used to make programs more readable and maintainable.

• # ifdef: This directive is called conditional compilation and allows the


programmer to write programs that are adaptable to different operating
environment.
Enhancing Programming Skills-C Programming

C preprocessor
•C compiler: This program translates the C language source code
into the machine assembly language.

•Assembler: The assembler accepts the C – compiler output and


creates object code. If the program does not contain any external
function calls, this code is directly executable.

•Linker: If a source file references library functions, which is


defined in other source files, the linker combines these functions
with the main() function to create an executable program file.
Enhancing Programming Skills-C Programming

C Tokens
Token is the smallest element in the program , C tokens are
classified into five types
1. Identifier
2. Keywords
3. Constants
4. Operators
5. Special Symbols
Enhancing Programming Skills-C Programming

Keywords
Keywords are predefined words having predefined meaning. User
can use these keywords but cannot change their meaning. There 32
keywords in C

Flow control (6) – if, else, return, switch, case, default


Loops (5) – for, do, while, break, continue
Common types (5) – int, float, double, char, void
For dealing with structures (3) – struct, typedef, union
Counting and sizing things (2) – enum, sizeof
Rare but still useful types (7) – extern, signed, unsigned, long, short, static, const
Keywords that is undiscouraged and which we NEVER use (1) – goto
We don't use unless we're doing something strange (3) – auto, register, volatile
Enhancing Programming Skills-C Programming

Identifier
Identifiers are user defined names, which are used to reference
variables, functions, labels, and various other user-defined elements.
Rules for Identifiers

Rule-1: Identifier name must start with alphabet or under score but
not digit.
Ex: total9 is valid identifier
9total is invalid identifier name
Enhancing Programming Skills-C Programming

Rule-2: Identifier name should not have any space or white space in
between of the characters or word in an identifier.
Ex: sum_of is valid identifier

sum of is invalid identifier name

Rule-3: C is a case sensitive language ,it treats uppercase letters and


lower case letters differently. So we need to any one version of the
Identifier name thought-out the program.

Ex: Total and total are treated as two different identifiers in C.


Enhancing Programming Skills-C Programming

Rule-4: Keywords can not be used as identifier names.

Rule-5: The maximum length of an identifier in C is 32 characters.

Note: Violation of these rules results in error.


Enhancing Programming Skills-C Programming

Constant
An identifier whose value can not be changed though out the
program is known as constant.
In C constants are classified as
1. Integer Constant
2. Real constant
3. Character constant
4. String constant
Enhancing Programming Skills-C Programming

Constant

1. Integer Constant: A constant that does not contain a decimal


point or fractional part is known as Integer Constant.
ex: 1, 10, 45

2. Real constant: A constant that contains a decimal point or


fractional part is known as Integer Constant.
ex: 1.23, 10.56, 45/2
Enhancing Programming Skills-C Programming

Constant
3. Character Constant: Anything placed within single quotes ‘ ‘ is
known as character constant.
ex: ‘a’, ’h’, ’k’
4. String Constant: Anything placed within double quotes “ “‘ is
known as string constant.
ex: “hi”, “hello”.
Enhancing Programming Skills-C Programming

Variables
An identifier whose value can be changed is known as Variable. A
variable usage in C invovles two main aspects

1. Declaring Variables

2. Initializing Variables
Enhancing Programming Skills-C Programming

Declaring Variables
A variable declaration is an intimation to the compiler about the
type of value you are going to store.
Syntax:

Data type variablename;


Here data type is any valid C data type and variable name is user
defined name. While giving variable name identifier rules
must be followed.
Enhancing Programming Skills-C Programming

Data type
Data type specifies what type of value you are going to store in a variable. C
data types are as follows

1. Integer data type: Used to represents the numbers which do not have the
decimal point. The keyword “int” is used to represent this data type. It
occupies 2bytes in memory.
Ex: int a;
Here variable a can contain a value that does not decimal point.

2. Floating point data type: Used to represents the numbers which have the
decimal point. The keyword “float” is used to represent this data type. It
occupies 4 bytes in memory.
Ex: float b;
Here variable b can contain a value that contains decimal point.
Enhancing Programming Skills-C Programming

Data type

3. Character data type: Used to represents the characters . The keyword


“char is used to represent this data type. It occupies 1byte in memory.
Ex: char c;
Here variable c can contain a character.

4.Double data type: it is also used to represent numbers with decimal point
similar to float . Float allows 6 digits after decimal point whereas double
allows 15 digits after decimal point. the keyword “double” is used to
represent this type of data.
Ex: double p;

Note: the int, float and char are known as primitive data types.
Enhancing Programming Skills-C Programming

Precision for real numbers


keywod Size Range

char 1 byte -128 to 127

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

short int or short 2 bytes -32,768 to 32,767

unsigned short
or 2 bytes 0 to 65535
unsigned short int

int 2 bytes -32,768 to 32,767

unsigned int 2 bytes 0 to 65535

Long
or 4 bytes -2147483648 to 2147483647 (2.1 billion)
long int

unsigned long
or 4 bytes 0 to 4294967295
unsigned long int

float 4 bytes 3.4 E–38 to 3.4 E+38 6 digits of precision

double 8 bytes 1.7 E-308 to 1.7 E+308 15 digits of precision

provides between 16 and 30


decimal places
long double 10 bytes +3.4 E-4932 to 1.1 E+4932
Enhancing Programming Skills-C Programming

The syntax of the simple type specifier

Short Int

Const Signed
Long

UnSigned
Char

Float

Double

Long
Enhancing Programming Skills-C Programming

Data type

Formula to find the range of numeric data type

-2n-1 to +2n-1 – 1
Where n represents the no of bits.
For example consider int data type
Size is 2bytes=16bits

-216-1 to +216-1 – 1
Enhancing Programming Skills-C Programming

Initializing Variables
Giving values at declaration itself is known as initialization.

Syntax:

Data type variablename=value;


Ex:
int a=10;
float b= 5.23;
char ch=‘u’;
Enhancing Programming Skills-C Programming

Objective Questions
& Assignments
Enhancing Programming Skills-C Programming

#include <stdio.h>
void main()
{
int i=2,j=3,k=4;
printf(“%d”);
}
Output: 4
Enhancing Programming Skills-C Programming

#include <stdio.h>
void main()
{
int i=2,j=3,k=0;
int p;
p=(I,k,j)
printf(“%d”,j);
}
Output: 3
Enhancing Programming Skills-C Programming

Which of the following is not a String constant/s?


a. “see u”
b. “123”
c. ‘h’
d. “sample1”

Ans: C
Enhancing Programming Skills-C Programming

Which of the following is/are not a character


constant/s?
a. ‘u’
b. ‘I’
c. 6
d. ‘5’
Ans: c
Enhancing Programming Skills-C Programming

Which of the following is not a valid identifier?


a. 1_average
b. sum of
c. auto
d. Total_marks

Ans: b
What will be output of the below code?

#include<stdio.h>
int x=40;
void main()
{
int x=20;
Printf(“%d”,x);
}
Ans: 20
Enhancing Programming Skills-C
Programming
What will be output of the below code?
#include<stdio.h>
void main()
{
int x=40;
{
int x=20;
printf(“%d”,x);
}
printf(“%d”,x);
}
Ans: 20 40
Enhancing Programming Skills-C
Programming
Assignments
1. Write a progression of data type sizes in c.

Estimated Time: 5min

Enhancing Programming Skills-C


Programming
Write a program in C to swap the contents of
two variables without using a temporary
variable.

Estimated Time:10min

Enhancing Programming Skills-C


Programming
• Write a program in C to swap the contents of
two variables without using a temporary
variable & arithmetic operators.

Estimated Time:10min

Enhancing Programming Skills-C


Programming
Enhancing Programming Skills-C Programming

• Expressions
5. • Definition and Examples
Expressions • Statements
• Definition and Example
and
• Types of Statements
Operators • Symbolic Constants
Enhancing Programming Skills-C Programming

Expressions

 An expression represents a single data item such as a number or a character.

 It may also consist of a combination of data items interconnected by one or


more operation.

Example:-
x = y; // Single data item
d = a * b + c; // combination of data items
Enhancing Programming Skills-C Programming

Statements

 A statement causes the computer to carry out some action.

Types of Statements:-

There are 3 types of Statements.


i) Expression Statements
ii) Compound Statements
iii) Control Statements

i) Expression Statements – This type of statements of consists of expressions followed by


a semicolon (;)
Ex:- a = 3;
c = a + b;
; // is a Null Statement
Enhancing Programming Skills-C Programming

Statements contd…
ii) Compound Statements – These statements enclosed within a pair of curly braces
{ }. They are also called as Statements Blocks.

Ex:-

{ {
pi = 3.14; l = 5, b = 10;
area = pi * r * r; rect = l * b;
} }
Enhancing Programming Skills-C Programming

Statements contd…

iii) Control Statements – These statements are also called as Looping Statements.
The program may require a group of instructions to be executed repeatedly until some
logical condition has been satisfied.
 The detailed discussion will be dealt under the concept of Looping statements.

Symbolic Constants in ‘C’ – The name that substitutes for a sequence of characters,
that are always defined at the beginning of the program.
Syntax:- # define name text

Where name – indicates a symbolic name mostly of uppercase letters.

text – indicates a sequence of characters associated with symbolic name


Enhancing Programming Skills-C Programming

Operators in

C
Enhancing Programming Skills-C Programming

Operators in ‘C’
Classifications
Definition And
Examples

Objective Interview
Questions Questions

Assignment and
Quiz
Enhancing Programming Skills-C Programming

Operators in ‘C’

Definition –
 An operator specifies the operation to be applied to its operand.

 An operand specifies an entity on which an operation is to be performed. It

can be a variable name, a constant, a function call or a macro name.


Enhancing Programming Skills-C Programming

Classification of Operators Syntax


Arithmetic Operators + - * / % pow() operand operator value / operand

Unary Operators + Unary plus - Unary Minus


Relational Operators < <= > >= ae1 relational Operator ae2
Logical Operators && - AND, || - OR, ! - NOT cond1 logicalOperator cond2
Assignment Operators = += -= *= /= Identifier = expression;
Equality Operators == != cond1 equalityOperator cond2
Conditional Operators ?: (Ternary Operator) exp1?exp2:exp3
Increment ++ --
Decrement Operators --
Bitwise & - AND | - OR XOR --
Shift Operators << - Shift Left >> - Shift Right
~ Negation
Special Operators () [] , & * . -> sizeof() --
Enhancing Programming Skills-C Programming

Operators in ‘C’ contd…


a) Integer Arithmetic

Ex :-
- 14 % 3 = -2
- 14 % -3 = -2
14 % -3 = 2

b) Real Arithmetic

Ex :-
float x , y;
6.0 / 7.0 = 0.857
1.0 / 0.3 = 3.333
- 0. 66 / 4.50 = - 0.1466
Enhancing Programming Skills-C Programming

Operators in ‘C’ contd…

 Operator percentage cannot be applied with real operands.

c) Mixed Mode Arithmetic

Ex :-
int a = 15;
float f = 10;
internally inside a / f is
calculated as 15 / 10.0 = 1.5
Enhancing Programming Skills-C Programming

Operators in ‘C’ contd…


d) Casting / Type casting

 The value of an expression can be converted to a different data type, if desired.

Syntax:-
(datatype) expression ;

Ex :-
int a = 5;
float b = 10;
(int) b % a = 10 % 5 = 0

 From the above example, the variable ‘b’ is converted to integer datatype

producing the result.


Enhancing Programming Skills-C Programming

Operators in ‘C’ contd…


Increment and Decrement operators

Increment operator => ++


Decrement operator => - -

Pre-increment = ++ a; // Adds 1 to a and displays a


Post–increment = a++; // display the previous value and then add 1 to a

 Similarly, for decrement operator.


Enhancing Programming Skills-C Programming

Operators in ‘C’ contd…

int a = 5; Output
Example : -
printf(“%d”, a ++); 5
printf(“%d”, ++a); 7
printf(“%d”, --a); 6
printf(“%d”, a--); 6
printf(“%d”, a); 5
Enhancing Programming Skills-C Programming

Operators in ‘C’ contd…


Bitwise and Shift operators

 The bitwise operators used are,

& Bitwise AND


| Bitwise OR
^ Bitwise XOR

 These operators cannot be applied to float and double.

 They do the manipulation at the bit level.


Enhancing Programming Skills-C Programming

Operators in ‘C’ contd…


b1 b2 b1 & b2 b1 | b2 b1 ^ b2
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

 Shift operators

<< Shift Left


>> Shift Right
~ Negation or Complement

<< performs multiplication by 2^n, where n is the number of bits

>> performs division by 2^n, where n is the number of bits


Enhancing Programming Skills-C Programming

Operators in ‘C’ contd…


 Shift left operation:-

7 6 5 4 3 2 1 0
10 = 1 0 1 0
1 0 1 0 0 0
40 =

 In the above example, the number 10 is shifted 2 bits to the left.

 Shift right operation:-

7 6 5 4 3 2 1 0
10 = 1 0 1 0

2= 1 0

 In the above example, the number 10 is shifted 2 bits to the right.


Enhancing Programming Skills-C Programming

Operators in ‘C’ contd…


Masking

It is a process in which a given bit pattern is transformed into another bit pattern by means of a logical

bitwise operator.

Special operators

Function call operator ( ) = used in functions

Array subscript operator [ ] = used for array variables

Comma operator ,

Pointer operators => & - “Address of ” operator * - Indirection operator

Member Selection Operators => . – Direct member access operator

-> - Indirect member access operator

sizeof ( ) operator – Returns the number of bytes occupied by the specified datatype.
Enhancing Programming Skills-C Programming

sizeof Operator
 Returns the number of bytes occupied by the specified datatype.

 The sizeof operator returns a size_t type.

 %zu is the conversion specifier


(eg) printf(“%zu”, sizeof(int));
Enhancing Programming Skills-C Programming

Operator Precedence Chart


Operator Description Associativity
left-to-right
() Parentheses (function call)
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement

right-to-left
++ -- Prefix increment/decrement
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation

*  /  % Multiplication/division/modulus left-to-right


+  - Addition/subtraction left-to-right
Enhancing Programming Skills-C Programming

Operator Description Associativity


left-to-right
<<  >> Bitwise shift left, Bitwise shift right

<  <= Relational less than/less than or equal to left-to-right


>  >= Relational greater than/greater than or equal to
==  != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

&& Logical AND left-to-right

|| Logical OR left-to-right

?: Ternary conditional right-to-left

= Assignment right-to-left
+=  -= Addition/subtraction assignment
*=  /= Multiplication/division assignment
%=  &= Modulus/bitwise AND assignment
^=  |= Bitwise exclusive/inclusive OR assignment
<<=  >>= Bitwise shift left/right assignment

, Comma (separate expressions) left-to-right


Enhancing Programming Skills-C Programming

?
?
Objective
?
Questions
Enhancing Programming Skills-C Programming

What will be the output of the following programs:-


1. main()
{
int x=10,y=5,p,q;
p=x>9;
q=x>3&&y!=3;
printf(“p=%d q=%d”,p,q);
}

2. main()
{
int a=30,b=40,x;
x=(a!=10) && (b=50);
printf(“x=%d”,x);
}
Enhancing Programming Skills-C Programming

3. main()
{
int a=100,b=200,c;
c=(a==100 || b > 200);
printf(“c=%d”,c);
}

4. main()
{
int x=11,y=6,z;
z=x==5|| y!=4;
printf(“z=%d”,z);
}
Enhancing Programming Skills-C Programming

5. main()
{
int x=10,y= -20;
x=!x;
y=!y;
printf(“x=%d y= %d”,x,y);
}

6. main()
{
int x=0,y=1;
y=!x;
x=!y;
printf(“x=%d y=%d”,x,y);
}
Enhancing Programming Skills-C Programming

7. main()
{
if(!3.14)
printf(“Hello”);
else
printf(“Fine”);
}

8. main()
{
int x=3,y=4,z=4;
printf(“Ans=%d”,(z>=y>=x?100:200));
}
Enhancing Programming Skills-C Programming

9. main()
{
int i= -4,j,num=10;
j=i% -3;
j=(j ? 0 : num*num);
printf(“j=%d”,j);
}

10. main()
{
int k=12,n=30;
k=(k>5 && n=4 ? 100 : 200);
printf(“k = %d”,k);
}
Enhancing Programming Skills-C Programming

11. main()
{
int c=0,d=5,e=10,a;
a=c>1 ? d>1 || e>1 ? 100 :200:300);
printf(“a=%d”,a);
}

12. main()
{
int x=10,y=20;
x=!x;
y=!x && !y);
printf(“x=%d y=%d”,x,y);
}
Enhancing Programming Skills-C Programming

?
?
Interview ?
Questions
Enhancing Programming Skills-C Programming

1. What would be the output of the following program?

int x=40;
main()
{ Ans:- 20
int x=20;
printf(“\n%d”,x);
}

Reason:- Whenever there is a conflict between a local and global


variable, it is the local variable that gets a priority
Enhancing Programming Skills-C Programming

2. What would be the output of the following program?

main()
{
static int a[20];
int i=0;
a[i]=i++; Ans:- 0 0 1
printf(“\n%d%d%d”,a[0],a[1],i);
}

Reason:- That’s what some compilers would give. But some may give
different answer. i.e., When a single expression causes the same object to
be modified or to be modified and then inspected the behavior is
undefined.
Enhancing Programming Skills-C Programming

3. What would be the output of the following program?

int x=40;
main()
{ Ans:- 20
int x=20;
printf(“\n%d”,x);
}

Reason:- Whenever there is a conflict between a local and global


variable, it is the local variable that gets a priority
Enhancing Programming Skills-C Programming

4. We want to round off x, a float, to an int value. The correct


way to do so would be

A) y=(int) (x+0.5);
B) y=int(x+0.5);
C) y=(int)x+0.5; Ans:- A
D) Y=(int)((int)x+0.5);
Enhancing Programming Skills-C Programming

5. What would be the output of the following program?

void main()
{
printf(“%d%d%d”,sizeof(3.14f,sizeof(3.14),sizeof(3.14l));
}

Ans:- 4 8 10
Enhancing Programming Skills-C Programming

6. What would be the output of the following program?

void main()
{
int i=32,j=0x20,k,l,m;
k=i|j;
l=i&j;
m=k^l;
printf(“%d%d%d%d%d”,i,j,k,l,m);
}

Ans:- 32 32 32 32 0
Enhancing Programming Skills-C Programming

7. What would be the output of the following program?

void main()
{
unsigned int m=32;
printf(“%x”,~m);
}

Ans:- f f d f
Enhancing Programming Skills-C Programming

8. What would be the output of the following program?

void main()
{
unsigned int a=0xffff;
~a;
printf(“%x”,a);
}

Ans:- f f f f
Enhancing Programming Skills-C Programming

9. Point out the error in the following program.


void main()
{
unsigned int a,b,c,d,e,f;
a=b=c=d=e=f=32;
a<<=2;
b>>=2;
c^=2;
d|=2;
e&=2;
f~=2;
printf(“%x%x%x%x%x%x”,a,b,c,d,e,f);
}

Ans:- f~=2;
Enhancing Programming Skills-C Programming

10. Which bitwise operator is suitable for putting on a particular


bit in a number?

Ans:- The Bitwise OR operator


|
Enhancing Programming Skills-C Programming

11. Which bitwise operator is suitable for checking whether a


particular bit is on or off?

Ans:- The Bitwise AND operator &


Enhancing Programming Skills-C Programming

12. What would be the output of the program?

void main()
{
int i=2;
printf(“\n%d%d”,++i,++i);
}

Ans:- Output may vary from compiler to compiler


Enhancing Programming Skills-C Programming

13. What would be the output of the program?

void main()
{
int x=10,y=20,z=5,i;
i=x<y<z;
printf(“\n%d”,i);
}

Ans:- 1
Enhancing Programming Skills-C Programming

14. Are the following two statements same?

<Yes / No> Ans:- No

15. Can you suggest any other way of writing the following
expression such that 30 is used only once?

a<=20?b=30:c=30; Ans:- ((a<=20)? &b:&c)=30;

16. How come that the C standard says that the expression j=i++
* i++; is undefined, whereas, the expression j=i++ && i++ ; is
perfectly legal?
According to the C standard, an object’s stored value can
be modified only once between 2 sequence points
Enhancing Programming Skills-C Programming

17. What would be the output of the program?

void main()
{
int i= -3,j=2,k=0,m;
m= ++i && ++j || ++k;
printf(“\n%d%d%d%d”,i,j,k,m);
}

Ans:- -2 3 0 1
Enhancing Programming Skills-C Programming

18. What would be the output of the program?

void main()
{
int i= -3,j=2,k=0,m;
m= ++j && ++i || ++k;
printf(“\n%d%d%d%d”,i,j,k,m);
}

Ans:- -2 3 0 1
Enhancing Programming Skills-C Programming

19. What would be the output of the program?

void main()
{
int i= -3,j=2,k=0,m;
m= ++i && ++j && ++k;
printf(“\n%d%d%d%d”,i,j,k,m);
}

Ans:- -2 3 1 1
Enhancing Programming Skills-C Programming

20. Point out the error, if any in the program.

void main()
{
int a=10,b;
a>=5 ? b=100 : b=200;
printf(“\n%d”,b);
}

Ans:- Lvalue required in main(). The second assignment


should be written in parentheses as follows:-
a>=5 ? b=100 : ( b=200);
Enhancing Programming Skills-C Programming

?
?
Program ?
Assignment
Enhancing Programming Skills-C Programming

1. Write a C program to add 2 numbers without


using + operator.
Input format:- 2 3
Constraint:- Accept only integers
Output format:- 5
Test Cases:-
Input :- 25 35 Input:- 15000 20000
Output:- 60 Output:-35000

Duration:- 10 mins
Enhancing Programming Skills-C Programming

2. Write a C program to count the no. of digits


without using mod operator
Input format:- 564
Constraint:- Accept only integer
Output format:- 3
Test Cases:-
Input :- 1234567 Input:- 54398
Output:- 7 Output:-5

Duration:- 10 mins
Enhancing Programming Skills-C Programming

3. Write a C program to add reversed number


with original number.
Input format:- 564
Constraint:- Accept only integer
Output format:- 1029
Test Cases:-
Input :- 132 Input:- 54398
Output:- 363 Output:-143743

Duration:- 20 mins
Enhancing Programming Skills-C Programming

4. Write a C program to subtract 2 numbers


without using - operator
Input format:- 5 6
Constraint:- Accept only integer
Output format:- -1
Test Cases:-
Input :- 132 100 Input:- 543987 543986
Output:- 32 Output:-1

Duration:- 20 mins
Enhancing Programming Skills-C Programming

Input
Output

Operations in C
Enhancing Programming Skills-C Programming

Input and Output Operations in ‘C’

 The Input and Output operations in ‘C’ are classified as shown below:-

I/O Functions

Formatted I/O Unformatted I/O


Input Functions Output Functions Input Functions Output Functions
scanf() printf() getc() / fgetc() putc() / fputc()
fscanf() fprintf() getchar() putchar()
gets() puts()
getch() putch()
getche() ---
getw() putw()
Enhancing Programming Skills-C Programming

Input and Output Operations in ‘C’

• Avoid non-standard library functions under


conio.h
– getch, getche, putch
• gets may cause buffer overflow, since it don't
consider length of the data. It is deprecated
from C11
• Use fgets instead
– (eg): fgets(str, 10, stdin);

Enhancing Programming Skills-C


Programming
Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…

Formatted Input Operations


i) scanf() – This function is used to read the data or accept the data using the

standard input device – keyboard.

Syntax:- scanf (“control string”, arg1,arg2,…arg n);

where control string – specifies the field format in which data has to be entered.

arg1, arg2,…arg n – refers to the number of arguments.


Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…


Format Codes-

%c – reads a single character


%d – reads a decimal integer
%g, %f, %e – reads a floating point value
%h – reads a short integer
%i – reads a decimal, hexadecimal or octal integer
%o – reads an octal integer
%s – reads a string
%u – reads an unsigned decimal integer
%x – reads a hexadecimal integer
%[...] – reads a string of white space characters
Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…


Examples:-
int a, b, c;
scanf(“%d%d%d”, &a,&b,&c);

float f1,f2;
scanf(“%f%f”, &f1,&f2);

Let the data for a be 50 and b be 31426


scanf(“%2d%5d”, &a,&b); // Internally a = 50 and b = 31426

Let the data be 123, 456, 789


scanf(“%d%*d%d”, &a,&b); // Internally a = 123 and b = 789

Reason:- 456 will be dropped because of *


Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…


Search Set:-
Output:-

# include<stdio.h> Enter the name : Meka

#include<conio.h> Name : Mek

void main()
{
How it happens???
char name[20];
printf(“\nEnter the name :”);
scanf(“%[^abcd]”, name); Reason:-
printf(“\n Name : %s”, name); The search set is inverted to
getch(); include all the characters even
} blank space except those inside
the square brackets
Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…

Formatted Input Operations


ii) fscanf() – This function is used to read the contents from the file to the screen.

Syntax:- fscanf ( “file pointer”, “control string”, arg1,arg2,…arg n);

where file pointer – specifies the file pointer variable.

control string – specifies the field format in which data has to be entered.

arg1, arg2,…arg n – refers to the number of arguments.

Ex:- fscanf ( “fp”, “%d%f”, &n1,&n2);


Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…

Formatted Output Operations


i) printf() – This function is used to display the data on to the screen.
Syntax:- printf (“control string”, arg1,arg2,…arg n);

where control string – specifies the field format in which data has to be entered.

arg1, arg2,…arg n – refers to the number of arguments.

Ex:- printf (“%d %s%f”, n,s,f);


Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…

Assume n = 9876
9 8 7 6
printf(“%d”, n);
9 8 7 6
printf(“%6d”, n);
9 8 7 6
printf(“%2d”,n);
9 8 7 6
printf(“%-6d”,n);
0 0 9 8 7 6
printf(“%06d”,n);
Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…


Formatted Output Operations

ii) fprintf() – This function is used to read the contents from the keyboard and writes to

the file.

Syntax:- fprintf ( “file pointer”, “control string”, arg1,arg2,…arg n);

where file pointer – specifies the file pointer variable.

control string – specifies the field format in which data has to be entered.

arg1, arg2,…arg n – refers to the number of arguments.

Ex:- fprintf ( “fp”, “%d%f”, &n1,&n2);


Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…

Unformatted Input Operations


i) getc() / fgetc() – This function returns the character read as an

unsigned char cast to an int or EOF on end of file or error.

Syntax:- getc (FILE *stream);

#include<stdio.h>
Ex:- Output:-
int main()
{ Enter character: a
char c; Character entered: a
printf("Enter character: ");
c = getc(stdin);
printf("Character entered: ");
putc(c, stdout);
return(0);
}
Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…


ii) getchar() – Simplest of all the input operations.

Reads a character from the keyboard.

Syntax:- variableName = getchar();

Ex:- Output:-

#include<stdio.h>
void main()
{
char c; Enter character: a
printf("Enter character: "); // Assigns a to c
c = getchar();
}
Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…


iii) gets() – Reads a string from the keyboard.

Unlike scanf(), it ignores blank spaces between strings

Syntax:- gets (characterArray);

Ex:- Output:-

#include<stdio.h>
void main()
{
char s[15]; Enter the string:
printf("Enter the string: "); India Shines
gets(s);
}
Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…


iv) getch() – Reads the character from the keyboard, but does not display it.

Syntax:-variableName = getch();

v) getche() – Reads the character from keyboard, but displays or echoes it onto the screen.

Syntax:- variableName = getche();

#include<stdio.h>
void main()
{
Ex:- char ch,ch1; Output:-
printf(“\n Enter 2 characters”);
ch=getch(); Enter 2 characters
ch1=getche(); a // no dispay
} b // displays
Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…


v) getw() – Reads only integer from the file

Syntax:- int getw(FILE *);

#include<stdio.h>
Ex:- Output:-
void main()
{
FILE *fp;
fp=fopen("file1.txt","r"); 65
printf("%d",getw(fp)); // Returns the ASCII
fclose(fp); value of A that is already
} written into the file.
Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…

Unformatted Output Operations


i) putc() / fputc() – This writes a character (an unsigned char) specified

by the argument char to the specified stream and advances the

position indicator for the stream.


#include<stdio.h>
Syntax:- int putc(int char, FILE *stream) int main()
{
char c;
Enter character: a printf("Enter character: ");
Character entered: a c = getc(stdin);
printf("Character entered: ");
putc(c, stdout);
return(0);
}
Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…


ii) putchar() – Simplest of all the output operations.

Displays a character onto the screen.

Syntax:- putchar(variableName);

Ex:- Output:-
#include<stdio.h>
void main()
{
char c;
Enter character: a
printf("Enter character: ");
// Assigns a to c
c = getchar();
a //displays
putchar( c);
}
Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…


iii) puts() – Displays the string onto the monitor.

Syntax:- puts (characterArray);

#include<stdio.h>
Ex:- Output:-
void main()
{
char s[15];
printf("Enter the string: "); Enter the string:
gets(s); India Shines
puts(s); India Shines
}
Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…


iv) putch() – Displays the character onto the screen.

Syntax:-putch(characterVariable);

Ex:- Output:-
#include<stdio.h> Enter 2 characters
void main() a // no dispay
{ b // displays
char ch,ch1; a
printf(“\n Enter 2 characters”); b
ch=getch();
ch1=getche();
putch(ch);
putch(ch1);
}
Enhancing Programming Skills-C Programming

I/O operations in ‘C’ contd…


v) putw() – Writes only integer value onto the file.

Syntax:-int putw(integer, FILE*);

Ex:- #include<stdio.h>Writes the integer number 65


void main() onto the “file1.txt
{
FILE *fp;
fp=fopen("file1.txt","w");
putw(65,fp);
fclose(fp);
}
Enhancing Programming Skills-C Programming

?
?
Objective
?
Questions
Enhancing Programming Skills-C Programming

1. How are real floating numbers treated in C?

2. The following piece of code is written to get a value from the


user:
main()
{
int num;
scanf(“Enter a number %d”, &num);
printf(“The number is %d”,num);
}
What is the purpose to get a garbage value??
Enhancing Programming Skills-C Programming

3. What is the purpose of format specifiers in C?

4. The following piece of code is written to get a value from the


user:
main()
{
int num;
scanf(“%d”, &num);
printf(“The number is %d”,num);
}
What is the purpose to get a garbage value??
Enhancing Programming Skills-C Programming

5. What is a data object?? How it is used in C?

6. Guess the output :


main()
{
int a,b;
scanf(“%d%d”, &a,&b);
printf(“%d+%d=%d”,a,b,a+b);
printf(“%d%%d=%d”,a,b,a%b);
}
Enhancing Programming Skills-C Programming

7. What will be the output of the code below:-


main()
{
int a=10,b=5,c;
c=a/**//b;
printf(“%d”,c);
}

8. Guess the output:-


main()
{
printf(“%d%d%d%d”,72,072,0x72,0X72);
}
Enhancing Programming Skills-C Programming

9. What will be the output of the code below:-


main()
{
printf(“%d%c”);
}

10. Guess the output:-


main()
{
printf(“hello, world
”);
}
Enhancing Programming Skills-C Programming

Interview ?
Questions
& ?
Quiz
Enhancing Programming Skills-C Programming

1. What would be the output of the following program?

void main()
{
printf(“%d”,sizeof(‘\n’));
}

Ans:- ‘\n’ is a character, more specifically a new line


character. Hence, sizeof operator returns 1,
Enhancing Programming Skills-C Programming

2. What would be the output of the following program?

void main()
{
printf(“%d%c”);
}

Ans:- Garbage value


Enhancing Programming Skills-C Programming

3. Write a program to print “hello world” without using ;

Ans:-
void main()
{
if (printf(“hello world”))
{ }
}
Enhancing Programming Skills-C Programming

4. What would be the output of the following program?

void main()
{
printf(“c:\tc\bin”);
}

Ans:- c: in
Enhancing Programming Skills-C Programming

5. What would be the output of the following program?

void main()
{
printf(“%05d,%5d,%-5d”,32,32,32);
}

Ans:- 00032, 32,32


Enhancing Programming Skills-C Programming

?
?
Program ?
Assignment
Enhancing Programming Skills-C Programming

1. Write a C program to write C program without


using main()
Input format:- hello
Constraint:- Integers and strings
Output format:- hello
Test Cases:-
Input :- 132 231 Input:- God is Great
Output:- 132 231 Output:-God is Great

Duration:- 10 mins
Enhancing Programming Skills-C Programming

2. Write a C program to input password for


validation of username
Input format:- hello
Constraint:- Integers and strings
Output format:- *****
Test Cases:-
Input :- Password Input:- krishna
Output:- ******** Output:-*******

Duration:- 30 mins
Enhancing Programming Skills-C Programming

3. Accept paragraph using scanf()


Input format:- Happy New Year 2016
Constraint:- strings
Output format:- Happy New Year 2016
Test Cases:-
Input :- Lets celebrate the Input:- Humpty Dumpty sat
result on the wall
Output:- Lets celebrate the Output:-Humpty Dumpty sat
result on the wall

Duration:- 20 mins
Enhancing Programming Skills-C Programming

THANK YOU

You might also like