• No results found

Program Examples

N/A
N/A
Protected

Academic year: 2022

Share "Program Examples"

Copied!
23
0
0

Loading.... (view fulltext now)

Full text

(1)

Unit-I Introduction to C

What is a Programming Language?

• A Programming Languages is a set of rules that provides a way of telling a computer what operations to perform

• A programming language is a set of rules for communicating an algorithm

• It provides a linguistic framework for describing computations

• A programming language is a tool for developing executable models for a class of problem domains

• A programming language is a notational system for describing computation in a machine- readable and a human-readable form

Levels of Programming Languages:

• Executable Machine Code Ex: Hex code or coding in 0s and 1s

• Low-level Programming Languages

Ex: Assembly language program, 8085, 8086 programming

• High-level Programming Languages

Ex: FORTRAN, COBOL, Basic, C, C++, Java, HTML, XML

• HTML & XML are the high-level mark-up languages Concepts of Programming Language:

• English is a natural language. It has words, symbols and grammatical rules

• A programming language also has words, symbols and rules of grammar, called syntax

• Each programming language has different set of syntax rules

• Different programming languages are designed for different types of programs Types of Programming Languages

• First Generation Languages Ex: Machine language, hex code

(2)

• Second Generation Languages Ex: Assembly languages, 8085, 8086

• Third Generation Languages: Closer to English, program written in source code Ex: Fortran, COBOL, C, C++, Visual Basic

• Fourth Generation Languages: used with databases Ex: query languages, report generators, form designers

• Fifth Generation Languages Ex: LISP, Scheme, SML, Prolog

Evolution of C language:

• C evolved from two previous languages, BCPL (Basic Combined Programming Language) and B

• BCPL developed in 1967 for writing OSes and compilers.

• B was used to create an early versions of UNIX OS at bell Laboratories in 1970 on a DEC PDP-7 computer.

• Both BCPL and B were typeless languages: the only data type is machine word History of C language:

• The C language developed from B by Dennis Ritchie at Bell Laboratories in 1972.

• It was named C for new language (after B)

• Initially, C used widely as the development language of the UNIX OS.

• Today, almost all new major OS are written in C including Windows

• The American National Standards Institute (ANSI) Committee approved C language in 1989, called ANSI C.

• Then, the document is referred to as ANSI/ISO 9899:1990.

• The second edition of Kernighan and Ritchie, published in 1988, this version called ANSI C, then used in worldwide.

(3)

• Historically, C programming language evolved from C89/C90/C95, C99 and the latest is C11.

Introduction to C:

• The programming language C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories

• It was named ‘C’ because many of its features were derived from an earlier language called

‘B’

• C was designed for implementing system software, later on widely used for developing portable application software

• C was developed by Dennis Ritchie in 1972 that took concepts from ALGOL, BCPL, and B.

• For many years, C was mainly used in academic institutions

• C was documented and popularized in the book The C Programming Language in 1978 by Kernighan and Ritchie

• In 1983, the American National Standards Institute (ANSI) started working on defining the standard for C

• This standard was approved in December 1989 and came to known as ANSI C

• In 1990, the International Standards Organization (ISO) adopted the ANSI standard

Taxonomy of C language

(4)

Characteristics of C:

• C is a robust language

• Built-in functions and operators can be used to write complex C programs

• C compiler combines the features of assembly language and high-level language

• A high level programming language enables the programmer to concentrate on the problem

• Not worry about the machine code on which the program would be run

• Small size – C has only 32 keywords

• Extensive use of function calls

• Well suited for structured programming, provides easiness in debugging, testing and maintenance

• Loose typing - unlike PASCAL

• Structured language

• Stable language

• Quick language

• Facilitates low level (bitwise) programming

• Supports pointers to refer computer memory, array, structures, and functions

• Core language, learning other computer languages becomes much easier, if you know C

• Portable language, C program written for one computer can be run on another computer

• Extensible language, it enables the user to add his own functions to the C library

• Often treated as second best language, best language depends on the particular task to be performed

C is the widely used professional language:

• It has high-level constructs

• It can handle low-level activities

• It produces efficient programs

• It can be compiled on a variety of computers Drawback:

• it has poor error detection which can make it off putting to the beginner Features of C Language

(5)

Features of C:

• Simple

• Machine Independent or Portable

• Mid-level programming language

• structured programming language

• Rich Library

• Memory Management

• Fast Speed

• Pointers

• Recursion

• Extensible

Application (used) of C language:

• It is primarily used for system programming, implementing operating system and embedded system applications

• Compilers, libraries and interpreters of other programming languages are often implemented in C

• It is sometimes used as an intermediate language for implementations of other languages

• C is widely used to implement end-user applications Structure of a C Program:

• C program is composed of preprocessor commands, a global declaration section, and one or more functions

• The preprocessor directives contain special instructions that indicate ho to prepare the program for compilation

• Most important and commonly used preprocessor commands is include

• it tells the compiler that to execute the program, some information is needed from the specified header files

• A function is defined as a group of C statements that are executed together

• The statement in a C program are written in logical sequence to perform a specific task

• The main( ) function is the most important function and is a part of every C program

• The execution of C program begins at this function

• All functions are divided in two parts – the declaration section and the statement section

• The declaration section proceeds the statement section and is used to describe the data that will be used in function

• The statement section in a function contains the code that manipulates the data to perform a specified task

Basic Structure of a C program:

(6)

First C Program:

#include <stdio.h>

int main ( ) {

printf(“\n Welcome to the world of C”);

return 0;

}

Output: Welcome to the world of C

• If you are a Windows user you may use Notepad or compiler’s own editor

• If you prefer working on UNIX you can use emacs or vi

Description of the First C Program:

#include <stdio.h>: This is a processor command that comes as the first statement in the code

• All processor commands start with symbol hash (#)

• Include the standard input/output library of header file

• Some built-in functions of this library we can use directly in the program int main ( ): int is the return value of the main function

• The last statement of the program will return an integer value to the operating system {}: all the statements between the braces form the function body

• The function body contains a set of instructions to perform the given task

printf(“\n Welcome to the world of C”); :The printf function is defined in the stdio.h file

• It is used to print the text on the screen

• The message that has to displayed on the screen is enclosed within double quotes and put inside brackets

• The ‘\n’ is an escape sequence and represents a newline character

• It is used to print the message on a new line on the screen

• Every statement in the function’s body ends with a semicolon (;) return 0; : This is used to return the value 0 to the operating system

• Give an indication that there is no error in the code during program execution Compilation and Execution of a C Program:

(7)

Special Characters used in C:

Comments are just a way of explaining what a program does

• The compiler ignores the comments when forming object file C supports two types of commenting:

• // is used to comment a single line, this is know as a line comment

• /* is used to comment multiple statements

• A /* is ended with */ and all statements within these characters are commented, this is known as block comment

Escape sequences are actually non-printing control characters that begin with a backslash (\)

Escape Sequences supported by C language:

Escape Sequence Meaning

\a Audible signal

\b Backspace

\t Tab or tabular gap

\n New line

\v Vertical tab

\r Carriage return

\` Single quote

\” Double quote

\f New page\ Clear screen

(8)

Special Symbols used in C:

Special Symbol Description

Semicolon (;) It is known as a terminator

It is used to terminate the C statements

Every statement of a C program must be terminated by a semicolon Comma (,) It is known as a separator

It is used to separate the C statements

Example: int a, b; it is separated as two statements such as int a; and int b;

Colon (:) It is known as a continuator,

It is used to continue the next C statement It is mostly used in switch-case statement

Declaration of a C Program:

In declaration of a C program following topics has to cover:

• Keywords

• Identifiers

• Data Types

• Variables

• Constants

• Expressions

• Statements

• Operators Keywords:

• C has a set of reserved words often known as keywords

• That can not be used as an identifier

• All keywords are basically a sequence of characters that have a fixed meaning

• All keywords must be written in lowercase letters

• C has 32 keywords: listed in table

auto break case char const continue default double

else enum extern float for goto int long

register return short signed sizeof struct switch typedef union unsigned void volatile do if static while

Identifiers:

• Help to identify data and other objects in the program

• Basically the names given to program elements such as variables, arrays, and functions

• It may consists of an alphabet, digit, or an underscore (_)

• It can not include any special characters or punctuations

• There can not be two successive underscore

• Keywords can not be used as identifiers

• The identifier name must begin with an alphabet or an underscore `_`

(9)

• It can be of any reasonable length

• C is a case-sensitive language, therefore rno, Rno, RNO are different considered as identifiers

Basic Data Types:

C language provides very few basic data types

• Different data representations need different types in programming

• A data type, in programming, is a classification that specifies which type of value a variable has and

• What type of mathematical, relational or logical operations can be applied to it without causing an error

• A string, for example, is a data type that is used to classify text and an integer is a data type used to classify whole numbers

• In programming, a data type is an attribute of data which tells the compiler how the programmer intends to use the data

Data Type Keyword used

Size in bytes

Range Use Format used in

programming Character char 1 -128 to 127 To store characters %c

Integer int 2 -32768 to 32767 To store integers %d, %i, %ld Floating Point flaot 4 3.4E-38 to 3.4E+38 To store floating

point numbers

%f, %e, %E

Double double 8 1.7E-308 to 1.7E+308 To store big floating point numbers

%lf

valueless void 0 valueless - -

(10)

Modern Category of Data Types:

• In C, data type categorized as:

• Primitive Types in ANSI C (C89)/ISO C (C90) -char, short, int, float and double

• Primitive Types added to ISO C (C99) -long long

• User Defined Types –struct, union, and typedef (will be discussed in Unit-III)

• Derived Types –pointer, array and function pointer (will be discussed in Unit-III) Format Specifiers in C:

• The format specifier is used during input and output

• It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf()

• Some examples are %c, %d, %f, etc…

• Character format specifier : %c

• Integer format specifier : %d, %i

• Floating-point format specifier : %f, %e or %E

• Unsigned Octal number for integer : %o

• Unsigned Hexadecimal for integer : %x, %X

• String printing : %s

• Decimal integer : %d

• Integer may be octal or in hexadecimal : %i

• Double floating-point number : %lf

• Long integer : %ld

other format specifiers are also there:

%u for an unsigned integer

%lld for long long int

Program Examples

#include <stdio.h> //Program1.c int main()

{

int a = 0;

printf("%d\n", a);

return 0;

} //Output: 0

#include <stdio.h> //Program2.c int main()

{

char ch = 'A';

printf("%c\n", ch);

return 0;

} //Output : A

#include <stdio.h> //Program3.c int main()

{

int x = 45, y = 90;

printf("%d\n", x);

printf("%i\n", x);

return 0;

} Output:

45 45

(11)

Variables:

• A variable is defined as a meaningful name given to the data storage location in computer memory

• Using a variable actually refer to address of the memory where the data is stored

• C language supports two basic kinds of variables: numeric variables and characters variables

• Numeric variables can be used to store either integer values or floating point values

• Character variables can include any letter from the alphabet or from the ASCII chart and number 0 – 9

• ASCII – American Standard Code for Information Interchange Concepts of Variables:

• Are named blocks of memory & is any valid identifier

• Have two properties in syntax: name—a unique identifier & type—what kind of value is stored

• It is identifier, that value may change during the program execution

• Every variable stored in the computer’s memory has a name, a value and a type Variable Definition in C:

• A variable definition tells the compiler where and how much storage to create for the variable

• A variable definition specifies a data type and contains a list of one or more variables of that type as follows –

type variable_list;

• Here, type must be a valid C data type including char, int, float, double, or any user-defined object;

variable_list may consist of one or more identifier names separated by commas

• Some valid declarations are shown here − int i, j, k; float f, salary;

char c, ch; double d;

Variable Declaration in C:

• To declare a variable, specify the data type of the variable followed by its name

• The data type indicates the kind of data store by the variable

• C variables are declared at three basic places as follows:

• When a variable is declared inside a function it is known as a local variable

• When a variable is declared in the definition of function parameters it is known as formal parameters (Unit-III)

• When the variable is declared outside all functions, it is known as a global variable

• A variable cannot be of type void

• A variable declaration provides assurance to the compiler that there exists a variable with the given type and name

• so that the compiler can proceed for further compilation without requiring the complete detail about the variable

• A variable declaration has its meaning at the time of compilation only

(12)

Correct Declaration Incorrect Declaration int x, y, z; int 3a, 1 P;

char num_one; char num+one;

long int Type_Num; long int #number;

float c, num = 4.5;

int my_data = 4;

Constants:

• Constants are identifiers whose value does not change

• Constants are used to define fixed values like Pi

• Constants refer to fixed values that the program may not alter during its execution

• These fixed values are also called literals

• Constants are treated just like regular variables except that their values cannot be modified after their definition

• The value of the constant is known to the compiler at the compile time

• C allows the programmer to specify constants of integer type, floating point type, character type, and string type

Declaring Constants:

• There are two simple ways in C to define constants:

• Using #define pre-processor

• Using const keyword

• Note that it is a good programming practice to define constants in capital letters

Declaring Constants using #define:

• #define can be placed anywhere in a C program

• No blank space are permitted in between the # and define

• #define is a pre-processor compiler directive

Syntax: #define identifier value

Example: #define PI 3.14159 #define tax 0.12

#include <stdio.h> //Program4.c

#define LENGTH 10

#define WIDTH 5 int main() { int area;

area = LENGTH * WIDTH;

printf("value of area : %d", area);

return 0;

} //Output: value of area: 50

Declaring Constants using const keyword:

• Precede the normal variable declaration with const keyword and assign it a value

Syntax: const type variable = value;

Example: const float pi = 3.14;

(13)

#include <stdio.h>

int main() {

const int LENGTH = 10;

const int WIDTH = 5;

int area;

area = LENGTH * WIDTH;

printf("value of area : %d", area);

return 0;

} // Output: value of area : 50

Programming Examples

#include <stdio.h> //Program1.c int main()

{

const int a = 0;

printf("%d\n", a);

return 0;

} //Output: 0

#include <stdio.h> //Program2.c int main()

{

const char ch = ‘B';

ch = ‘A’

printf("%c\n", ch);

return 0;

} //Output : B

#include <stdio.h> //Program3.c int main()

{

const int x = 45, x = 90;

printf("%d\n", x);

printf("%i\n", x);

return 0;

} Output:

45 45

Expressions:

• An expression is a formula in which operands are linked to each other by the use of operators to compute a value

• An operand can be a function reference, a variable, an array element or a constant

Ex: a-b; In this expression, minus character (-) is an operator, and a, and b are the two operands

There are four types of expressions exist in C:

• Arithmetic expressions

• Relational expressions

• Logical expressions

• Conditional expressions Types of Expressions:

• Each type of expression takes certain types of operands and uses a specific set of operators

• Evaluation of a particular expression produces a specific value

(14)

Arithmetic Expression:

• An arithmetic expression is an expression that consists of operands and arithmetic operators

• It computes a value of type int, float or double

• When an expression contains only integral operands, then it is known as pure integer expression

• when it contains only real operands, it is known as pure real expression, and

• when it contains both integral and real operands, it is known as mixed mode expression

• Expressions are evaluated by performing one operation at a time

• The precedence and associativity of operators decide the order of the evaluation of individual operations

Ex: 6*2/ (2+1 * 2/3 + 6) + 8 * (8/4) Relational Expression:

• A relational expression is an expression used to compare two operands

• It is a condition which is used to decide whether the action should be taken or not

• In relational expressions, a numeric value cannot be compared with the string value

• The result of the relational expression can be either zero or non-zero value

• Here, the zero value is equivalent to a false and non-zero value is equivalent to true

Ex: 2>3, 3.5==4.0, 7<=7 etc..

Logical and Conditional Expressions:

• A logical expression is an expression that computes either a zero or non-zero value

• It is a complex test condition to take a decision

• Logical operators is associated with a logical expression

Ex: 2<3 && 4>3, 3.5>4.0 || 5.5 < 6.2

• A conditional expression is an expression that returns 1 if the condition is true otherwise 0

• A conditional operator is also known as a ternary operator

Syntax: Suppose exp1, exp2 and exp3 are three expressions

• exp1 ? exp2 : exp3

• The above expression is a conditional expression which is evaluated on the basis of the value of the exp1 expression

• If the condition of the expression exp1 holds true, then the final conditional expression is represented by exp2

• otherwise represented by exp3

(15)

C Statements:

• A statement is a command given to the computer that instructs the computer to take a specific action,

• such as display to the screen, or collect input

• A computer program is made up of a series of statements

• Following types of statements exist in C:

• Simple statements

• Control statements

• Conditional statements

• Un-conditional statements

• Loop statements Description of Statements:

• Most statements in a C program are simple statements

• Ex: c = a + b; z = x * y

• Other examples of simple statements are the jump, return, break, continue, and goto

• Following are the control statements in C: Decision making statements, Selection statements, Iteration statements, and Jump statements

• A conditional is a statement that instructs the computer to execute a certain block of code or

• alter certain data only if a specific condition has been met

• Un-conditional statements directs the program's flow to another part of program without evaluating conditions

• Looping is the key concepts on any programming language

• It executes a block of statements number of times until the condition becomes false

Program (statements) Examples

#include <stdio.h> //Program1.c int main()

{

int a ; //simple statement printf("%d\n", sizeof(a));

return 0;

} //Output: 2 or vary

#include <stdio.h> //Program2.c int main()

{

char ch; //simple statement float f;

printf("%d\t%d\n", sizeof(ch), sizeof(f));

return 0;

} //Output : 1 4

#include <stdio.h> //Program3.c int main()

{

long int x;

double d;

printf("%d and", sizeof(x));

printf("%d\n", sizeof(d));

return 0;

}

Output: 4 and 8

(16)

Operators:

• C language supports a rich set of built-in operators

• An operator is a symbol that tells the compiler to perform a certain mathematical, logical or relational manipulation

• Operators are used in programs to manipulate data and variables

• C operators can be classified into following types:

• Arithmetic operators

• Relational operators & Equality operators

• Logical operators

• Bitwise operators

• Assignment operators

• Other operators (Unary, Conditional, Sizeof, Comma) Arithmetic operators:

• Consider three variables declared as:

int a = 9, b = 3, result;

Operations Operators Syntax Expression/

Statement

Result

Multiple * a * b result=a*b 27

Divide / a / b result=a/b 3

Addition + a + b result=a+b 12

Subtraction – a – b result=a – b 6

Modulus % a % b result=a%b 0

Program #1

Write a program to perform all arithmetic operations on two integers as well as on two floating point numbers

Relational & Equality operators:

• Compares two values and return true or false if int x = 1, y = 2, z = 3, result;

Operations Operators Syntax Expression/

Statement

Result

Less than < x < y result= x < y True/1 Greater than > x > y result= x > y False/0 Less than or equal to <= x <= z result= x <= z True/1 Greater than or equal to >= y >= z result= y >= z False/0

Equal to == x == y result= x == y False/0

Not equal to != x != z result=x != z True/1

(17)

Program #2

Write a program to show the use of relational and equality operators.

Logical operators:

• C language supports three logical operators:

• Logical AND (&&), Logical OR (| |), Logical NOT (!)

• Logical AND operator is used to simultaneously evaluate two conditions or expressions with relational operators

• If expressions on both sides are true than the whole is true

• In logical OR operator, if any one or both sides expression is true than the whole is true

• Logical NOT operator takes a single expression and negates the value of the expression int x = 1, y = 2, z = 3

Operations Operators Meaning Result Logical AND && x < y && x < z True Logical OR | | x > y || y < z True

Logical NOT ! !x, !z False, False

Bitwise Operators:

• Bitwise operators perform manipulations of data at bit level

• These operators also perform shifting of bits from R to L & L to R

• Bitwise operators are not applied to float or double

• Bitwise operator works on bits and perform bit-by-bit operation int a = 10, b = 20, c = 0

Operations Operators Meaning Result

AND & c = a & b 0

OR | c = a | b 30

XOR ^ c = a ^ b 30

Complement ~ c = ~a or c = ~b 245, 235 Left-Shift << c = a << 2 40 Right-Shift >> c = b >> 1 10

a= 0000 1010 (=10) b= 0001 0100 (=20) c = 0000 0000 (a & b) c = 0001 1110 (a | b) c = 0001 1110 (a ^ b) c = 1111 0101 (~a) c = 1110 1011 (~b) c = 0010 1000 (a<<2) c = 0000 1010 (b>>1)

(18)

Assignment Operators:

• The assignment operator is responsible for assigning values to the variables, ‘=‘ is the fundamental assignment operator

int a = 2, c = 20;

Operator Meaning Result += c += a c = c + a // 22 –= c –= a c = c – a //18

*= c *= a c = c * a //40 /= c /= a c = c / a //10

%= c %= a c = c % a //0

&= c &= a c = c & a //0

|= c |= a c = c | a //22

^= c ^= a c = c ^ a //22

<<= c <<= a c = c << a //80

>>= c >>= a c = c >> a //5

Progam#3:

Write a program to demonstrate the use of assignment operators

Program Examples

#include <stdio.h> //Test1.c int main()

{

int n1 = 3, n2 = 5 ; n1 += n2 * 4;

n2 *= n1 % 4;

printf(“N1 =%d\n", n1);

printf(“N2 =%d\n", n2);

return 0;

} //Output: N1 = ???

N2= ???

#include <stdio.h> //Test2.c int main()

{

int x = 4, y = 9;

y %= x * 3 – y;

x – = y * 4 + x

printf(“ y = %d\n“ y);

printf(“ x = %d" x));

return 0;

}

Output: y = ????

x = ????

c= 0001 0100 (=20) a= 0000 0010 (=2) c = 0000 0000 (c & a) c = 0001 0110 (c | a) c = 0001 0110 (c ^ a) c = 0101 0000 (c<<a) c = 0000 0111 (c>>a)

(19)

Increment and Decrement operators:

• The increment operator is a unary operator that increases the value of its operand by 1

• ‘++’ is the symbol for increment operator

• Similarly, the decrement operator decreases the value of its operand by 1

• ‘– –’ is the symbol for decrement operator

• The increment/decrement operators have two variants

prefix and postfix (known as pre-increment/decrement) and (post-increment/decrement) operators

Ex: in prefix, ++x or – –x in postfix, x++, x– –

y = ++x; (means it is two statement)

x= x + 1; y = x;

Similarly postfix:

y = x++;

y = x;

x= x + 1;

Examples:

Ex1: int x = 1, y = – 1;

y = ++x ; x = ? and y = ? Ex2: int x = –1, y = 1;

y = x++;

x = ? and y = ?

Conditional Operator:

• Conditional operator is also known as ternary operator

• Such operator is useful in situations in which there are two or more alternatives for an expression

Syntax: Exp1 ? Exp2 : Exp3

Exp1 is evaluated first, if it is true, then Exp2 is evaluated and becomes the result of the expression

• Otherwise Exp3 is evaluated and becomes the result of the expression

Ex:

int a = 5, b =7, large;

large = (a > b) ? a : b;

printf(“%d is the large” large);

Operator Precedence & Associativity:

• Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated

• Certain operators have higher precedence than others

• For example, the multiplication operator has a higher precedence than the addition operator

• Operators Associativity is used when two operators of same precedence appear in an expression

y = – –x;

x = x – 1;

y = x;

y = x – –;

y = x;

x = x – 1;

Ex3: int x = –1, y = 1, z;

z = ++x + y – –;

x = ? y = ? z= ?

(20)

• Associativity can be either Left to Right or Right to Left

For example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right

• So the expression “100 / 10 * 10” is treated as:

“(100 / 10) * 10”

Operator Precedence Table:

Category Operators Associativity

Brackets ( ), [ ]. { } left-to-right

Unary +, –, !, ~, ++, – – (type)*, sizeof right-to-left

Arithmetic *, /, %, +, – left-to-right

Shift <<, >> left-to-right

Relational & Equality <, <=, >, >=, ==, != left-to-right

Bitwise &, ^, | left-to-right

Logical &&, || left-to-right

Conditional ?: right-to-left

Assignment = ,+=, –=, *=, /=, %=, >>=,

<<=, &=, ^=, |=

right-to-left

Comma , left-to-right

Program Examples

#include <stdio.h> //Test3.c int main()

{

int n1 = 3, n2 = 5 ; n1 += n2 ;

n2 = n1 – n2;

n1 = n2 ;

printf(“N1 =%d\n", n1);

printf(“N2 =%d\n", n2);

return 0;

} //Output: N1 = ???

N2= ???

#include <stdio.h> //Test4.c int main()

{

int x = 4, y = 9;

x *= y;

y = x / y;

x /= y;

printf(“ y = %d\n“ y);

printf(“ x = %d" x));

return 0;

}

Output: y = ????

x = ????

(21)

Increment and Decrement operators:

• ‘++’ is the symbol for increment operator, operand is incremented by 1

• Similarly, ‘– –’ is the symbol for decrement operator, the operand is decremented by 1

• pre-increment ++x, pre-decrement – –x and

• post-increment x++, post-decrement x– –

y = ++x;

x = x + 1;

y = x;

Ex1: int x = 1, y = – 1, z;

z = ++x – ++y;

x = ? y = ? z = ?

Ex2: int x = –1, y = 1, z;

z = x++ – y++ ; x = ?

y = ? z = ?

Conditional Operator Example:

Syntax: Exp1 ? Exp2 : Exp3:

Ex:

int a = 5, b =7, large, small;

large = (a > b) ? a : b;

printf(“%d is the large” large);

small = (a < b) ? a : b;

printf(“%d is the small” small);

#include <stdio.h> //largersmaller.c int main()

{

int x = 4, y = 9, res;

res = (x > y) ? printf(“ %d is large” x) : printf(“ %d is large” y);

res = (x < y) ? printf(“ %d is small” x) : printf(“ %d is small” y);

return 0;

}

Output: ???

y = – –x;

x = x – 1;

y = x;

y = x++;

y = x;

x = x +1;

y = x – –;

y = x;

x = x – 1;

Ex3: int x = –1, y = – 1, z;

z = x++ + ++y;

x = ? y = ? z= ?

Ex4: int x = 1, y = 1, z;

z = x – – – – –y;

x = ? y = ? z= ?

(22)

Find Output for following Programs?

#include <stdio.h> //Test3.c int main()

{

int x = 3, y = 5, z = 7;

int a, b;

a = x * 2 + y / 5 – z * y;

b = ++x * (y – 3) / 2 – z++ * y;

printf(“ \na = %d“ a);

printf(“ \nb = %d", b));

return 0;

}

Output: a = ????

b = ????

#include <stdio.h> //Test1.c int main()

{

int a = 2, b = 3;

printf(“ \n%d” ++(a – b));

return 0;

} Output:

#include <stdio.h> //Test2.c int main()

{

int a = 2, b = 3;

printf(“ \n%d” ++a – b);

return 0;

} Output:

(23)

Assignment-I

1. Differentiate between programming language and natural language.

2. Write the history, features and characteristics of C programming language.

3. Give definition of the following terms: Keywords, Identifiers, Constants, Variables, Data Types, Pre-processor Directives, Built-in Functions, Expression, Statement, Source file, Object file and Header file

4. Discuss the different types of operators used in C programming language with an example for each.

5. Write the meaning of the following special operators/characters/symbols:

“ ” (double quotes), ‘ ’ (single quote), & (ampersand use in scanf() function), # (use in pre- processor directive), and % (use in format specifier)

6. Write a program for the following:

(i) To convert the temperature from oF to oC and vice versa.

(ii) To print the ASCII value of a character.

(iii) To swap two numbers with and without using third variable.

(iv) To find the largest and smallest of three numbers using ternary operator.

(v) To read a character in upper case and then print it in lower case.

How and When to Submit Assignment?

• The assignment should be in hand written

• All questions should be completed in your notebook (paper)

• The assignment should be completed by 22.09.2020

• I may ask either the complete assignment or any part of the assignment at random after due date to any student

• You have to send the snaps of any question or any part of your assignment as per demand

References

Related documents

● Data abstractions – examples: primitive types, structured types?. ● Control abstractions – examples: functions, control

Error Detection Language Safety Verification Abstraction Documentation. karkare, CSE, IITK/B

– Keywords: Logic expression defining output, logic function, and input variable.. – Let’s use two switches to control the lightbulb by connecting them in series

Definition of Data Structure, Types of Data Structures, Abstract Data Type (ADT), Algorithms: Algorithm Concepts, Definition of Algorithm, Objectives of Algorithms,

Unit-I Definition of Data Structure, Types of Data Structures, Abstract Data Type (ADT), Algorithms: Algorithm Concepts, Definition of Algorithm, Objectives of

Introduction to Data Structure : Definition of Data Structure, Types &amp; Characteristics of Data Structures, Abstract Data Type (ADT), Algorithms: Algorithm Concepts, Definition

 The students would be able to write, debug and run a simple Python program  The students would learn how to input character, variables /keywords, evaluate expressions  The

• True division is where the result is always the real floating-point quotient, regardless of operand type.. • This is the default division operation in any Python