0% found this document useful (0 votes)
11 views33 pages

Module 1-1

The document provides an overview of the C programming language, detailing its history, features, applications, advantages, and disadvantages. It explains the structure of C programs, including functions, variables, constants, and data types, while also highlighting the importance of C in various domains such as operating systems and embedded systems. Additionally, it covers basic programming concepts like variable declaration, initialization, and the use of trigraphs and escape sequences.

Uploaded by

antony09141
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views33 pages

Module 1-1

The document provides an overview of the C programming language, detailing its history, features, applications, advantages, and disadvantages. It explains the structure of C programs, including functions, variables, constants, and data types, while also highlighting the importance of C in various domains such as operating systems and embedded systems. Additionally, it covers basic programming concepts like variable declaration, initialization, and the use of trigraphs and escape sequences.

Uploaded by

antony09141
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

1 CSC3C03- PROBLEM SOLVING USING C

C is a procedural programming language initially developed by Dennis Ritchie at Bell


Laboratories in 1972. It was developed along with the UNIX operating system. The syntax of
many programming languages including Java, PHP, JavaScript is primarily based on the C
language.

Features of C Programming Language


The growing popularity of C is most likely due to its many desirable characteristics. The
following are the important features of the C programming language.

Robust language – Well suitable for writing any complex programs.


Fast and efficient programs – Because of variety of data types and operators.
Rich set of inbuilt functions.
Highly portable.
Well suited for structured programming.
Ability to extend itself. Application of C Programming Language
C programming language finds its application in various domains, including:

Operating systems: C is extensively used in developing operating systems like Windows, Linux,
and macOS.
Embedded systems: C is the language of choice for developing firmware and software for
various embedded systems, such as microcontrollers and IoT devices.
System Utilities: Many system utilities, such as text editors, compilers, and interpreters, are
written in C.
Game development: C is used to develop games due to its ability to handle complex calculations
and graphics.
Database systems: The core components of databases and their management systems are often
built using C.
Networking: C is used for developing network protocols and applications.
Importance of C programming language over other languages
C programming language offers several advantages over other programming languages,
including:

MODULE 1
2 CSC3C03- PROBLEM SOLVING USING C

Efficiency: C allows for direct memory manipulation and low-level access to system resources.
This results in highly efficient code execution.
Portability: C code can be easily ported to different platforms without major modifications,
thanks to its wide availability of compilers and libraries.
Speed: C is known for its fast execution speed, making it suitable for developing performance-
critical applications.
Control: C gives programmers fine-grained control over memory management and system
resources.
Compatibility: C code can be easily integrated with code written in other languages like C++,
Java, and Python.
Advantages of C Programming Language
Apart from the benefits mentioned above, there are several advantages of using C programming
language, including:

Modularity: C supports modular programming, allowing developers to break down complex


programs into smaller, manageable modules for easier development and maintenance.
Wide community support: C has a large and active development community, making it easy to
find resources, libraries, and support online.
Skill transferability: Once you learn C, it becomes easier to learn other programming languages
since many languages, including C++, are based on C.
Disadvantages of C Programming Language
While C programming language offers many advantages, it also has some disadvantages,
including:

Complexity: C can be difficult to learn for beginners due to its low-level nature and the need to
understand concepts like pointers and memory management.
Lack of safety features: C does not have built-in features like garbage collection, which can lead
to memory leaks and other runtime errors if not managed properly.
Vulnerabilities: The low-level nature of C makes it prone to security vulnerabilities like buffer
overflows if not correctly handled by the programmer.
What Function Does the C Language Play in Everyday Life?

MODULE 1
3 CSC3C03- PROBLEM SOLVING USING C

Even though most people may not directly interact with C programming language in their daily
lives, its impact is widespread. Many everyday devices and technologies rely on software
developed using C, including:

Operating systems: All modern operating systems, such as Windows, Linux, and macOS, have a
significant portion of their codebase written in C.
Embedded systems: Devices like washing machines, smart TVs, and medical equipment often
run on embedded systems programmed using C.
Mobile applications: Some parts of mobile applications, including high-performance tasks and
system-level operations, may be implemented in C for efficiency.
Gaming consoles: Popular gaming consoles’ core software and engines are often developed using
C.
Network infrastructure: Routers and networking devices rely on software written in C to handle
complex networking protocols.

Basic Structure of C Programs


A C program can be thought of as a collection of blocks known as functions. A function can be
defined as a subroutine that contains one or more statements that perform a specific task. A C
program may contain one or more sections as follows.

MODULE 1
4 CSC3C03- PROBLEM SOLVING USING C

The document section of the program is made up of a set of comment lines containing details
like the name of the program, author, etc.

The link section contains instructions to the compiler on how to link functions from the system
library.

All symbolic constants are defined in the definition section.

Variables that are used in multiple functions are known as global variables. These variables are
declared in the global variables section.
Every C program should have a main() function section. It is a special function used by the C to
tell the computer where the program starts. The main() section is divided into two parts: the
declaration part and the executable part. The declaration section declares all variables. The
executable section contains at least one statement. These two parts must be written inside the
opening and closing braces. All statements in the declaration and executable sections are
followed by a semicolon (;).

All user-defined functions that are called in the main function are written in the subprogram
section.

Except for the main function section, all sections may be skipped when they are not required.

Hello World Program in C


The following program in C prints the message “Hello World !” on the screen as below:

#include<stdio.h>
main()
{
printf("Hello World!");
}
Executing a C Program

MODULE 1
5 CSC3C03- PROBLEM SOLVING USING C

Executing a program written in C involves the following steps:

Creating the program.


Compiling the program.
Linking the program with functions that are needed from the C library.
Executing the program.
In this tutorial, you will learn character set in C, C tokens, C keywords and identifiers in C.

Character Set
The set of alphabets, digits and special characters that are valid in the C language is called the
character set.

Alphabets
Both lowercase(a – z) and uppercase(A – Z) alphabets are accepted by C.

Digits
C accepts all digits from 0 to 9.

Special Characters
C supports the usage of the following special characters.

White spaces
Blank spaces, horizontal tab, carriage return, newline and form feed characters are allowed in C.
White spaces may be used to separate words, but they are not permitted between keywords and
identifiers.

MODULE 1
6 CSC3C03- PROBLEM SOLVING USING C

C tokens
The smallest individual units in a C program is known as C tokens. C has six types of tokens as
shown in the figure.

Keywords
Predefined reserved words with fixed meanings are called keywords. Since keywords are the
building blocks for program statements, they cannot be used as identifiers. Since C is case
sensitive, all keywords must be written in lowercase. The list of all keywords available in C is
given below:
auto extern sizeof
break for signed
case float struct
char if switch
const goto typedef
continue int union
default long void
do register unsigned
double return volatile
else short while
enum static
Identifiers
The names of variables, functions, and arrays are referred to as identifiers. These are user-
defined names consisting of a sequence of letters and digits. Identifiers must be unique.

The rules for naming identifiers in C

MODULE 1
7 CSC3C03- PROBLEM SOLVING USING C

Must consist of only letters, digits or underscore.


Both uppercase and lowercase letters are permitted.
The first character must be a letter of the alphabet or underscore.
Only first 31 characters are significant.
Cannot use a keyword.
Must not contain white space.
For example:

int age;
float mark;
Here age and mark are identifiers.

Variables

A variable is a data name that can be used to store data. A variable may take different values at
different times during the execution of a program. A variable name can be meaningfully chosen
by the programmer, subject to the conditions listed below:

 Variable names can be made up of alphabets, digits, and the underscore character.
 They must begin with an alphabet. Some systems allow underscore as the initial
character.
 Uppercase and lowercase letters are significant. That is, the variable Mark is not the same
as mark or MARK.
 It should not be a keyword.
 White space is not allowed.
Some examples of valid variable names include

Value
,
score
,
mark1
,
phone_number
,
Counter_1
, etc.
Invalid examples include

MODULE 1
8 CSC3C03- PROBLEM SOLVING USING C

123
,
(area)
,
22nd
,
char
, etc.
Declaration of Variables

Declaration tells the compiler what the variable name is and what type of data the variable will
hold. In C, variables can be declared using the following syntax:

datatype variable1;
Multiple variables can be declared by separating them with commas as follows.

datatype variable1, variable2, variable3;


For example,

int x;
float a, b, c;
Here

int
and
float
are the keywords used to represent integer and real numbers respectively.
Initializing variables

Assigning value to a variable once declared is called initialization of a variable. In C, the


varibales declaration and initialization together takes the following form:

int x = 5;
The following ways are also acceptable.

int a, b=10, c = 5;
int x, y, z;
x = 10;

MODULE 1
9 CSC3C03- PROBLEM SOLVING USING C

y = z = 5;
Here

b = 10
,
c=5
,
x =10
,
y= 5
,
z=5
.
The symbols [ ] { } ^ \ | ~ # are frequently used in C programs, but in the late 1980s, there were
code sets in use (ISO 646 variants, for example, in Scandinavian countries) where the ASCII
character positions for these were used for national language variant characters (e.g. £ for # in
the UK; Æ Å æ å ø Ø for { } { } | \ in Denmark; there was no ~ in EBCDIC). This meant that it
was hard to write C code on machines that used these sets.

To solve this problem, the C standard suggested the use of combinations of three characters to
produce a single character called a trigraph. A trigraph is a sequence of three characters, the first
two of which are question marks.

The following is a simple example that uses trigraph sequences instead of #, { and }:

??=include <stdio.h>

int main()

??<

printf("Hello World!\n");

??>

MODULE 1
10 CSC3C03- PROBLEM SOLVING USING C

This will be changed by the C preprocessor by replacing the trigraphs with their single-character
equivalents as if the code had been written:

#include <stdio.h>

int main()

printf("Hello World!\n");

Trigraph Equivalent

??= #

??/ \

??' ^

??( [

??) ]

??! |

??< {

??> }

??- ~

Note that trigraphs are problematic because, for example, ??/ is a backslash and can affect the
meaning of continuation lines in comments, and have to be recognized inside strings and
character literals (e.g. '??/??/' is a single character, a backslash).

MODULE 1
11 CSC3C03- PROBLEM SOLVING USING C

Constants

Fixed values that do not change throughout program execution are called constants. The
keyword

const
can be used to define a constant as follows.
const datatype name = value;
For example

const double pi = 3.14;


will define a constant named ‘pi’ of type ‘double’ having the value ‘3.14’. The value of pi can
not be changed throughout the program.
Constants can also be defined using the

#define
preprocessor directive. You can learn about the symbolic constants in this tutorial.
C supports the following types of constants.

Integer Constants
A sequence of digits is referred to as an integer constant. Spaces, commas, and non-digit
characters are not permitted between digits. The integer constants are of three types.

Decimal integer – Consist of a series of digits from 0 to 9, followed by an optional – or +


symbol.
Octal integer – Made up of any combination of digits from 0 to 7, with a leading 0.

MODULE 1
12 CSC3C03- PROBLEM SOLVING USING C

Hexadecimal integer – Series of digits preceded by 0x or 0X.


Example:
Decimal Integer: 120 -450 1 654321 +56
Octal Integer: 031 0 0321 04320
Hexadecimal: 0x2F 0X1A2 0xD10 0x
Real Constants

Numbers containing fractional parts are called real constants. Examples of real constants include

452.5

-.74

+321.2
etc.
Single Character Constants

A single character enclosed within a pair of single quote marks is called a single character
constant. Examples of single character constants include

'F'

'c'

'3'
.
String Constants

A sequence of characters enclosed in double quotes is called a string constant. Letters, numerals,
special characters, and blank spaces can all be used as characters. Some examples are

"Hello"

"Good Morning"

"1996"

"what?"
etc.
Backslash Character Constants

MODULE 1
13 CSC3C03- PROBLEM SOLVING USING C

C includes various special backslash character constants that can be used in output functions.
They are known as escape sequences. The following table shows the list of backslash character
constants in C.

Constant Meaning
\a Bell
\b Back space
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\’ Single quote
\” Double quote
\? Question mark
\\ Back slash
\0 Null
Data types are used to determine the size and type of data stored in a variable. For example,

int mark;
Here mark is a variable of type int. That is mark can store integer values.

C supports the following classes of data types:

Primary data types.


Derived data types.
User-defined data types.
C supports five primary (fundamental) datatypes namely integer(int), character(char), floating-
point(float), double-precision floating-point(double) and void(void). Many of them also include
additional data types, such as long int and long double.

MODULE 1
14 CSC3C03- PROBLEM SOLVING USING C

The following table contains various data types along with their size, range of values and format
specifier.

Integer

Integers are whole numbers having a range of values that are supported by a certain computer. In
C, there are three types of integer storage:

short int
,
int
, and
long int
, which are available in both
signed
and
unsigned
forms. That is integers can store both zero, positive and negative values but no decimal values.
int roll;

int roll, mark;

short int id;

signed int x;

MODULE 1
15 CSC3C03- PROBLEM SOLVING USING C

short int
represents relatively small integer values and takes half the storage space of a typical int
number.

unsigned int
employ all of the bits for the magnitude of the number and are always positive. Because the
default declaration implies a signed number, the use of the qualifier

signed
on integers is optional.
Floating point

Floating-point variables are used to store real numbers with 6 digits of precision. In C, floating-
point numbers are defined by the keyword

float
. To define a number with 14 numbers of precision, the type

double
can be used. These are referred to as double-precision numbers.

long double
can be used to increase precision even further.

float rate;

double price;
Character

The

char
data type can be used to define a single character.

char demo = 'x';


Void

The

void

MODULE 1
16 CSC3C03- PROBLEM SOLVING USING C

type has no values. This is typically used to specify the type of function that returns no value to
the caller function.
Derived Data Types and User-Defined Data Types

Derived types are data types that are derived from fundamental data types. Arrays, pointers,
function types, structures, and so on are examples.

int roll;
int roll, mark;
short int id;
signed int x;
short int represents relatively small integer values and takes half the storage space of a typical int
number. unsigned int employ all of the bits for the magnitude of the number and are always
positive. Because the default declaration implies a signed number, the use of the qualifier signed
on integers is optional.

Floating point
Floating-point variables are used to store real numbers with 6 digits of precision. In C, floating-
point numbers are defined by the keyword float. To define a number with 14 numbers of
precision, the type double can be used. These are referred to as double-precision numbers. long
double can be used to increase precision even further.

float rate;
double price;
Character
The char data type can be used to define a single character.

char demo = 'x';


Void
The void type has no values. This is typically used to specify the type of function that returns no
value to the caller function.

Derived Data Types and User-Defined Data Types

MODULE 1
17 CSC3C03- PROBLEM SOLVING USING C

Derived types are data types that are derived from fundamental data types. Arrays, pointers,
function types, structures, and so on are examples.
The typedef is a keyword that is used to provide existing data types with a new name. The C
typedef keyword is used to redefine the name of already existing data types.
When names of datatypes become difficult to use in programs, typedef is used with user-
defined datatypes, which behave similarly to defining an alias for commands.
C typedef Syntax
typedef existing_name alias_name;
After this declaration, we can use the alias_name as if it were the real existing_name in out C
program.
Example of typedef in C
typedef long long ll;
// C program to implement typedef
#include <stdio.h>
// defining an alias using typedef
typedef long long ll;
// Driver code
int main()
{
// using typedef name to declare variable
ll var = 20;
printf("%ld", var);

return 0;
}
Enum

MODULE 1
18 CSC3C03- PROBLEM SOLVING USING C

enum State {Working = 1, Failed = 0};


The keyword ‘enum’ is used to declare new enumeration types in C and C++. Following is an
example of enum declaration.

// The name of enumeration is "flag" and the constant


// are the values of the flag. By default, the values
// of the constants are as follows:
// constant1 = 0, constant2 = 1, constant3 = 2 and
// so on.
enum flag{constant1, constant2, constant3, ....... };
Variables of type enum can also be defined. They can be defined in two ways:
// In both of the below cases, "day" is
// defined as the variable of type week.

enum week{Mon, Tue, Wed};


enum week day;

// Or

enum week{Mon, Tue, Wed}day;

MODULE 1
19 CSC3C03- PROBLEM SOLVING USING C

// An example program to demonstrate working


// of enum in C
#include<stdio.h>

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}
Output:
2
A symbolic constant is a name given to any constant. In C, the preprocessor directive

#define
is used for defining symbolic constants.
#define
instructions are usually placed at the beginning of the program. By convention, the names of
symbolic constants are written in uppercase, but this is not compulsory. The syntax for creating a
symbolic constant is as follows:
#define constant_name value
For example:

#define PI 3.14
It will define a symbolic constant

PI
having value
3.14
. When we use

MODULE 1
20 CSC3C03- PROBLEM SOLVING USING C

PI
in our program, it will be replaced with 3.14 by the compiler automatically.
The rules below apply to a

#define
statement that defines a symbolic constant.
 No blank space is allowed between the
#
symbol and the word
define
.
 The character in the line should be
#
.
 A blank space is required between the constant name and #define and between the
constant name and the value.
 A semicolon must not be used at the end of a
#define
statement.
 Within the program, the symbolic constant should not be assigned any other value.
Example

#include <stdio.h>
#define PI 3.1415
int main()
{
float radius=10, area;
area = PI*radius*radius;
printf("Area=%.2f",area);
return 0;
}
Operators in C
n this tutorial, you will learn about different operators in C programming.

An operator is a symbol that instructs a computer to perform certain operations. Operators are
typically used as part of mathematical or logical expressions. C supports a rich set of operators to
perform various operations.

MODULE 1
21 CSC3C03- PROBLEM SOLVING USING C

C Arithmetic Operators
An arithmetic operator performs mathematical operators such as addition, subtraction etc. C
supports all basic arithmetic operators. The list of all arithmetic operators in C is listed in the
following table.

Operator Meaning Example


+ Addition or Unary plus 8 + 2 = 10
– Subtraction or Unary minus 8 – 2 =6
* Multiplication 8 * 2 = 16
/ Division 8/2=4
% Modulo division 13 % 2 = 1
The unary plus and unary minus operators are used to specify the sign of a number. The modulo
division (%) operator produces the remainder of an integer division. For example 10 % 3 = 1.

The variables in which the operation is performed is called operand. That is, in a + b, a and b are
operands and + is the operator.

When the operands in a single arithmetic expression are both integers, then the operation is
known as integer arithmetic. Integer arithmetic always produces an integer value as output. All
the examples in the above table are integer arithmetic. For example: 12 / 10 = 1

Real arithmetic refers to arithmetic operations that will use only real operands. The operator %
cannot be used with real operands. For example: 3.0 / 2.0 = 1.5
Mixed-mode arithmetic expressions are those in which one of the operands is real and the other
is an integer. Since one of the operands is of real type, then the result is always a real number.
For example: 12 / 10.0 = 1.2

MODULE 1
22 CSC3C03- PROBLEM SOLVING USING C

Example: Arithmetic operators


#include <stdio.h>
int main()
{
int a = 8,b = 2, c;

c = a+b;
printf("Sum = %d \n",c);
c = a-b;
printf("Difference = %d \n",c);
c = a*b;
printf("Product = %d \n",c);
c = a/b;
printf("Quotient = %d \n",c);
c = a%b;
printf("Remainder after division = %d \n",c);

return 0;
}
Output

Sum = 10
Difference = 6
Product = 16
Quotient = 4
Remainder after division = 0
C Relational Operators

MODULE 1
23 CSC3C03- PROBLEM SOLVING USING C

The relationship operators are used to check the relationship between two operands. The value of
a relational operator is either 1 (true) or 0 (false). The list of relational operators supported in C is
given in the table. Suppose a = 6 and b = 2.

Operator Meaning Example


< is less than a < b is true.
<= is less than or equal toa <= b is true
> is greater a > b is false
>= is grater than an equal to a >= b is false
== is equal to a == b is false
!- is not equal to a != b is true
Note that the arithmetic operators have a higher priority over relational operators. For example,
in the expression 10 < 7 + 5 , 7 + 5 is evaluated first and the result 12 is compared with 10.

Relational statements are generally used in decision-making statements and loops.

Example: Relational operators


#include <stdio.h>
int main()
{
int a = 5, b = 4;
printf("%d == %d is %d \n", a, b, a == b);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d <= %d is %d \n", a, b, a <= b);
return 0;
}

MODULE 1
24 CSC3C03- PROBLEM SOLVING USING C

Output

5 == 4 is 0
5 > 4 is 1
5 < 4 is 0
5 != 4 is 1
5 >= 4 is 1
5 <= 4 is 0
C Logical Operators
The logical operators are used to make a decision by testing one or more conditions. The three
logical operators supported in C are:
&& – logical AND – True only if all operands are true.
|| – logical OR – True only if either one operand is true.
! – logical NOT – True only if the operand is 0
The value of a logical operator is also one or zero according to the truth table given below:

A B A && B A || B !A
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0
C Assignment Operator
Assignment operators are used to assigning values to a variable. The assignment operator in c is
=. C also has a set of shorthand assignment operators as shown in the table:

Operator Example Same as


+= a += b a = a + b
-= a -= b a = a – b
*= a *= b a = a * b

MODULE 1
25 CSC3C03- PROBLEM SOLVING USING C

/= a /= b a = a / b
%= a %= b a = a % b
C Increment and Decrement Operator
In C, the operators ++ and -- are called the increment and decrement operators and are used to
change the value of an operand by 1.

The increment operator ++ increases the value of an operand by 1 and the decrement operator --
decreases the value of an operand by 1. They both are unary operators.

These operators can be used as prefixes like ++a and can be used as postfixes like a++. You can
learn the difference in increment and decrement operators when used as prefix and postfix here.
Example
#include <stdio.h>

int main() {
// Write C code here
printf("Postfix Operators");
int a,b;
a=4;
b=a++ + a++;
printf("%d",b);
printf("\nPrefix Operators");
a=4;
b=++a + ++a;
printf("%d",b);
return 0;
Output

Postfix Operators9
Prefix Operators12

MODULE 1
26 CSC3C03- PROBLEM SOLVING USING C

C Bitwise Operator
For manipulation of data at bit level, C supports special operators known as bitwise operators.
Bit wise operators and their meaning is given in the following table:

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
` Bitwise complement
<< Shift left
>> Shift right
C Conditional Operator
C has a special ternary operator ?: called conditional operator. The conditional operator behaves
similarly to the ‘if-else’ statement. The syntax of a conditional operator is as follows:

condition ? true-statement : false-statement;


Here expression1 is a boolean condition that can be either true or false. The conditional operator
will return expression2, if the value of expression1 is true. Similarly, if the value of expression1
is false, then the operator will return expression3. For example, consider the following example:

max = (a > b) ? a : b ;
First, the expression a > b is evaluated. If it is true, the statement will be equivalent to

max = a;
. If

a>b
is false, then the statement will be equivalent to

max = b
.

MODULE 1
27 CSC3C03- PROBLEM SOLVING USING C

Special Operators

C also support some special operators such as comma operator, sizeof operator, pointer
operators, etc.

The Comma Operator

The comma operator is used to link the related expression together. For example:

float a, b, c;
The sizeof Operator

The sizeof operator return the number of bytes a operand occupies. It can be used to know the
size of variables, constants, arrays, structures etc. For example:

x = sizeof(mark);
Other operators

The reference operator

&
and deference operator

*
is used in pointer operations. The member selection operator

.
and

->
are used to select members of a structure.

Arithmetic Expressions and Operator Precedence in C


An arithmetic expression is a combination of variables, constants, and arithmetic operators.
Arithmetic operators supported in C are +, -, *, / and %. The operands include integer and
floating-type numbers. Some algebraic expressions and their corresponding C expressions are
given in the following table.

MODULE 1
28 CSC3C03- PROBLEM SOLVING USING C

Algebraic Expression C Expression


\[(a+b)(a-b)\]

(a + b) * (a-b)
\[\frac{ab}{c}\]

(a * b) / c
\[2x^2+3x\]

2*x*x+3*x
Arithmetic expressions are evaluated using an assignment statement of the form variable =
expression. The expression is evaluated first and the value is assigned to the variable. An
example of an evaluation statement is, c = a - b / d + e
Precedence of Arithmetic Operators in C
To determine the meaning and value of an expression in an unambiguous manner, we apply the
operator precedence and associativity rules. Arithmetic expressions without parentheses are
evaluated from left to right using the rules of operator precedence. In C, arithmetic operators
have two different priority levels.

Hight priority * / %]
Low priority + -
The basic procedure for evaluating an expression includes two passes from left to right. The high
priority operators are applied during the first pass and the low priority operators are applied in
the second pass.
C language has standard libraries that allow input and output in a program. The stdio.h or
standard input output library in C that has methods for input and output.

scanf()
The scanf() method, in C, reads the value from the console as per the type specified. Syntax:

MODULE 1
29 CSC3C03- PROBLEM SOLVING USING C

scanf(“%X”, &variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a
variable and & is the address operator in C, which tells the compiler to change the real value of
this variable, stored at this address in the memory.

printf()
The printf() method, in C, prints the value passed as the parameter to it, on the console screen.
Syntax:
printf(“%X”, variableOfXType);
where %X is the format specifier in C . It is a way to tell the compiler what type of data is in a
variable and & is the address operator in C, which tells the compiler to change the real value
of this variable, stored at this address in the memory.

How to take input and output of basic types in C?

The basic type in C includes types like int, float, char, etc. Inorder to input or output the
specific type, the X in the above syntax is changed with the specific format specifier of that
type. The Syntax for input and output for these are:
 Integer:
Input: scanf("%d", &intVariable);
Output: printf("%d", intVariable);
 Float:
Input: scanf("%f", &floatVariable);
Output: printf("%f", floatVariable);
 Character:
Input: scanf("%c", &charVariable);
Output: printf("%c", charVariable);

Non formatted functions


getchar():
The difference between getc() and getchar() is getc() can read from any input stream, but
getchar() reads from standard input. So getchar() is equivalent to getc(stdin).

Syntax:

int getchar(void);
Example:

MODULE 1
30 CSC3C03- PROBLEM SOLVING USING C

// Example for getchar() in C


#include <stdio.h>
int main()
{
printf("%c", getchar());
return 0;
}
Input: g(press enter key)
Output: g
getch():
getch() is a nonstandard function and is present in conio.h header file which is mostly used by
MS-DOS compilers like Turbo C. It is not part of the C standard library or ISO C, nor is it
defined by POSIX (Source: http://en.wikipedia.org/wiki/Conio.h)
Like above functions, it reads also a single character from keyboard. But it does not use any
buffer, so the entered character is immediately returned without waiting for the enter key.
Syntax:

int getch();
Example:

// Example for getch() in C


#include <stdio.h>
#include <conio.h>
int main()
{
printf("%c", getch());

MODULE 1
31 CSC3C03- PROBLEM SOLVING USING C

return 0;
}
Input: g (Without enter key)
Output: Program terminates immediately.
But when you use DOS shell in Turbo C,
it shows a single g, i.e., 'g'
getche()
Like getch(), this is also a non-standard function present in conio.h. It reads a single character
from the keyboard and displays immediately on output screen without waiting for enter key.

Syntax:

int getche(void);
Example:

#include <stdio.h>
#include <conio.h>
// Example for getche() in C
int main()
{
printf("%c", getche());
return 0;
}
putchar() function is a file handling function in C programming language which is used to write a
character on standard output/screen. getchar() function is used to get/read a character from
keyboard input. Please find below the description and syntax for above file handling function.

putchar() Declaration: int putchar(int char)


putchar() function is used to write a character on standard output/screen. In a
C program, we can use putchar function as below.

MODULE 1
32 CSC3C03- PROBLEM SOLVING USING C

putchar(char);
where, char is a character variable/value.

EXAMPLE PROGRAM FOR PUTCHAR(), GETCHAR() FUNCTIONS IN C


PROGRAMMING LANGUAGE:
C
#include <stdio.h>
#include <ctype.h>
int main()
{
char c;
printf("Enter some character. Enter $ to exit...\n");
while (c != '$');
{
c = getchar();
printf("\n Entered character is: ");
putchar(c);
printf("\n")
}
return 0;
}
OUTPUT:
Enter some character. Enter $ to exit…
A
Entered character is: A
B
Entered character is: B
$
Entered character is: $

MODULE 1
33 CSC3C03- PROBLEM SOLVING USING C

puts() can be preferred for printing a string because it is generally less expensive
(implementation of puts() is generally simpler than printf()), and if the string has formatting
characters like ‘%s’, then printf() would give unexpected results. Also, if str is a user input string,
then use of printf() might cause security issues (see this for details).
Also note that puts() moves the cursor to next line. If you do not want the cursor to be moved to
next line, then you can use following variation of puts().

MODULE 1

You might also like