[go: up one dir, main page]

0% found this document useful (0 votes)
37 views28 pages

GR 6 C Programming Notes 2019-20

notes

Uploaded by

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

GR 6 C Programming Notes 2019-20

notes

Uploaded by

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

Programming in C

C is a general-purpose computer programming language developed in


1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to
develop the UNIX operating system. C is the most widely used
computer language.

C CHARACTER SET

Character set is a set of valid character that a language can recognise. A


character represents any letter, digit or any other sign.
C has the following character set:
ALPHABETS
Uppercase letters A-Z
Lowercase letters a-z

DIGITS
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
SPECIALCHARACTERS
~ tilde,% percent sign,| vertical bar, @ at symbol, + plus
sign,< less than, _ underscore,- minus sign,>greater than,^
caret , # number sign, = equal to, & ampersand , $ dollar sign,
/slash, ( left parenthesis, * asterisk, \ back slash,)right
parenthesis, ′ apostrophe,:colon,[left bracket," quotation
mark,; semicolon, ] right bracket, !exclamation mark,
, comma, { left flower brace, ? Question mark,. dot
operator,}rightflower brace
WHITESPACECHARACTERS

\b blank space, \t horizontal tab, \v vertical tab, \r carriage return,\f


form feed, \n new line,\\ Back slash, \’ Single quote, \" Double quote,
\?Question mark, \0 Null, \a Alarm (bell)

C TOKENS

C tokens are the basic buildings blocks in C language which are


constructed together to write a C program.Each and every smallest
individual units in a C program are known as C tokens.

C tokens are of six types. They are,


1. Keywords (eg: int, while),
2. Identifiers (eg: sum, answer)
3. Constants (eg: 10, 20),
4. Strings (eg: “total”, “hello”)
5. Special symbols (eg: (), {}),
6. Operators (eg: +, /,-,*)

KEYWORDS:
 Keywords are pre-defined words in a C compiler.
 Each keyword is meant to perform a specific function in a C
program.
 Since keywords are referred names for compiler, they can’t be used
as variable name.

C language supports 32 keywords which are given below.

auto double case enum

int struct register typedef


const float default goto

short unsigned sizeof volatile

break else char extern

long switch return union

continue for do if

signed void static while

IDENTIFIERS:

 Each program elements in a C program are given a name called


identifiers.
 Names given to identify variables, functions and arrays are
examples for identifiers.

RULES FOR CONSTRUCTING IDENTIFIER NAME IN C:

1. First character should be an alphabet or underscore.


2. Succeeding characters might be digits or letter.
3. Punctuation and special characters aren’t allowed except
underscore.
4. Identifiers should not be keywords.
5. Identifiers are case sensitive. (Upper and lower case letters must be
treated differently)
eg: age, name, address1
CONSTANTS

C constants refer to the data items that do not change their value
during the program execution. Constant can belong to any data type.

Eg: const int num=18;

STRINGS

String is a sequence of characters enclosed by double quotes.

eg: “Welcome2school”

Operators

An operator is a symbol that is used to perform specific mathematical


operations or logical functions.

eg: +,-,*,\

C PROGRAMMING BASICS: -

STEPS TO WRITE C PROGRAMS AND GET THE OUTPUT:

Below are the steps to be followed for creating and getting the output
for any C program. This is common to all C programs and there is no
exception whether it’s a very small C program or very large C program.

1. Creating the program:


First write the C program using any text editor. Some systems
provide with an Integrated Development Environment (IDE) for
developing programs. IDEs provide facilities for typing,
editing,saving, compiling etc. integrated in one package. Eg:
CodeBlocks, Borland Turbo C.
2. Saving the program:
Save the written program using the .C extension. eg: hello.C
The file save with the .C extension is called the source code.

3. Compiling the program:


Compiler is a system software that does 2 things
1. Analyze the source code for errors.
2. Translates corrected source code into machine language.

A compiler reports an error by flashing an error message. An error


message contains a line number and a brief description of the error.
Once an error is reported the program must be corrected and
recompiled. Once all the errors are rectified then only the compiler
translates the source code into machine language.

4. Execute or Run:
Once you execute or run the program you get the output.

Types of errors:-

Syntax errors:
Like English language having grammar, every programming language
has its own set of rules or syntax. Syntax error occurs if the rules of a
programming language are misused. Syntax errors are detected at
compile - time.

Run-time errors:
Run-time errors occur during the execution of a program. It is mainly
caused because of some illegal operation or unavailability of desired
conditions for the execution of the program.
eg: Trying to divide a number by zero, insufficient memory, infinitive
loop etc.

Working with CodeBlocks


CodeBlocks is a free and open source, cross platform IDe downloadable
from www.codeblocks.org

After installing the CodeBlocks you can type and execute your C
program as described below.

1. Start CodeBlocks: You’ll see a window as shown below when you


open CodeBlocks.

2. To type a new program click File-> New-> Empty File


(Ctrl+Shift+N)

3. In Untitled1 start typing your program.


4. To save your code, click File->Save File (Ctrl+S ). The file extension
for a C program is .C
5. Once saved, the next step is to compile the program. To compile click
Build ->Compile current file(Ctrl+Shift+F9)
6. If any errors are generated correct them, resave your program and
re-compile it.
7. To execute the program Build -> Run (Ctrl+F10).

A SIMPLE C PROGRAM:

Below C program is a very simple and basic program in C programming


language. This C program displays “Hello World!” in the output
window.

All syntax and commands in C programming are case sensitive.


Each statement should be ended with semicolon (;) which is a
statement terminator.
#include <stdio.h>
int main ()
{
/* Our first simple C basic program */
printf("Hello World! ");
return 0;
}

C Basic commands Explanation


This is a preprocessor
command that includes
standard input output
header file(stdio.h) from
the C library before
#include <stdio.h> compiling a C program
This is the main function
from where execution of
int main() any C program begins.
This indicates the
beginning of the main
{ function.
whatever is given inside
the command “/* */” in
any C program, won’t be
considered for
compilation and
/*_some_comments_*/ execution.
printf command prints the
printf(“Hello_World! “); output onto the screen.
getch(); This command waits for
any character input from
keyboard.
This command terminates
C program (main function)
return 0; and returns 0.
This indicates the end of
} the main function.

printf() and scanf()


Two commonly used functions for Input and Output tasks in C is printf()
and scanf().To use these functions, we must include the stdio library in
the source code. To do this just type the following code at the
beginning of your program.
#include <stdio.h>

printf()
printf() is used to display your messages to the user. These messages
can be used to request input from a user or to display the result.
Syntax for printing a simple message: printf(“Text to be
displayed”);Whatever we type within the double quotes will be
displayed as such on the screen.
eg: printf(“Enter your age”);
Syntax for printing the values stored inside a variable:
printf(“format specifier”,variable1,variable 2);
Matching format specifier must be specified for printing values inside a
variable. (Referthe list of format specifier giver below) printf() can print
any number of variable in a single statement but every variable should
be separated by comma.
eg. int a=10;
float b=11.5;
printf(“%d%f”, a,b);
Here the value stored inside the variables a and b will be displayed.
List of Format specifier:

Format specifier Type of value

%d Integer

%f Float

%lf Double

%c Single character

%s String

Escape sequences in C:
An escape sequence is a series of characters that represents certain
special action. It begins with a backslash character (\). The following is a
list of escape sequences.

Escape sequence Action

\n prints a new line

\b backs up one character


\t moves the output position to the next tab
stop

\\ prints a backslash

\" prints a double quote

\' prints a single quote

scanf()
scanf() is used to read the input value from the keyword.
Syntax: scanf(“format specifier”, &variable1, &variable2);
eg:int a;
float b;
scanf(“%d %f”, &a, &b);

Note:
C language is case sensitive. For example, printf() and scanf() are
different from Printf() and Scanf(). All characters in printf() and
scanf() functions must be in lower case.

DATA TYPES
Data types in C programming language enables the programmers to
appropriately select the data as per requirements of the program and
the associated operations of handling it.
C provides 5 fundamental data types- int, float, double,char and void.
1. int (integer data type)

Integer data type is used to declare a variable that can store numbers
without a decimal.

Syntax: int variable_name;

eg: int a;

int x,y;

2. float (Float data type)

Float data type declares a variable that can store numbers containing a
decimal number.

Syntax: float variable_name;

eg: float c;

3. double (Double data type)

Double data type also declares variable that can store floating point
numbers. But it is treated as a distinct data type because it occupies
twice as much memory as float and can store floating point numbers
with much larger range and double precision. Thus, double data type is
also referred to as double precision data type.

Syntax: double variable_name;

eg: double z;

4. char (Character data type)

Character data type allows a variable to store only one character.


Character is enclosed by single quotes in C.

Syntax: char variable_name;


eg: char c= ‘Y’;

5. void

Unlike other primitive data types in c, void data type does not create
any variable but returns an empty set of values. Thus, we can say that it
stores null.

Syntax: void variable_name;

VARIABLES
A variable is a name given to the memory location which holds the
value of the variable for later use. Each variable in C has a specific data
type, which determines the size of the variable's memory; the range of
values that can be stored within that memory; and the set of
operations that can be applied to the variable. The value of a variable
can be changed later in the program.
RULES FOR NAMING C VARIABLE:

1. Variable name must begin with letter or underscore.


2. Variables are case sensitive
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than underscore.

total, sum, address1, age_value are some examples for variable name.

VARIABLE DECLARATION & INITIALIZATION:

All variables must be declared before they are used. More than one
variable of the same data type can be declared in a single statement.
Syntax: data_type variable _name;
Example: int x; float y; char a,b;

Variable initialization means assigning a value to the variable.


Syntax: variable _name=value;
Example: x=5; y=3.14; a=’y’,b=’n’;

Both declaration and initialization can be done in a single statement


also.
Syntax: data _ type variable _name=value;

Example: int x=5; float y=3.14; char a=’y’,b=’n’;

OPERATOR

An operator is a symbol that is used to perform specific mathematical


operations or logical functions. C language provides different types of
operators. Let us have a look at the following operators

1. Arithmetic Operators
2. Relational Operators
3. Assignment Operators
4. Increment/Decrement Operators

Arithmetic Operators: -
These are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus.
The following table shows all the arithmetic operators supported by the
C language.

Operator Name Description


+ Addition Adds two operands.

− Subtraction Subtracts second operand from the


first.

* Multiplication Multiplies both operands.

/ Division Divides numerator by denominator.

% Modulus Gives the remainder after an integer


division.

Relational Operators: -

Relational operators are used to compare the values of two variables in


a C program.
The following table shows all the relational operators supported by C.

Operator Name Description

== Is equal to x==y; Checks if the values of two operands


are equal or not. If yes, then the condition
becomes true.

!= Is not equal x!=y; Checks if the values of two operands


to are equal or not. If the values are not equal,
then the condition becomes true.

> Is greater x>y; Checks if the value of left operand is


than greater than the value of right operand. If
yes, then the condition becomes true.

< Is less than x<y; Checks if the value of left operand is less
than the value of right operand. If yes, then
the condition becomes true.

>= Is greater x>=y; Checks if the value of left operand is


than or greater than or equal to the value of right
equal to operand. If yes, then the condition becomes
true.

<= Is less than r x<=y; Checks if the value of left operand is


equal to less than or equal to the value of right
operand. If yes, then the condition becomes
true.

Logical Operators: -

The following table shows all the logical operators supported by C.

Operator Description
&& Called Logical AND operator. If both the
expressions evaluate to True, result is True. If
either expression is False, result is False.

|| Called Logical OR Operator. If any one of the


two expressions or both expression is True,
then the result is True.

! Called Logical NOT Operator. It is used to


reverse the logical state of its operand. If a
condition is true, then Logical NOT operator
will make it false.

Logical AND (&&)

false && false: false


false && true: false
true && false: false
true && true: true

Logical OR (||)

false || false: false


false || true: true
true || false: true
true || true: true

Logical NOT (!)

!false: true
!true: false
Assignment Operators: -

Assignment Operators are used to assign values for the variables in C


programs. The following table shows all the assignment operators
supported by C.

Operator Description

= x=y; Simple assignment operator. Assigns


values from right side operands to left side
operand

+= x+=y; {meaning x=x+y} Add AND assignment


operator. It adds the right operand to the left
operand and assign the result to the left
operand.

-= x-=y; {meaning x=x-y} Subtract AND


assignment operator. It subtracts the right
operand from the left operand and assigns
the result to the left operand.

*= x*=y; {meaning x=x*y} Multiply AND


assignment operator. It multiplies the right
operand with the left operand and assigns the
result to the left operand.
/= x/=y; {meaning x=x/y} Divide AND assignment
operator. It divides the left operand with the
right operand and assigns the result to the left
operand.

%= x%=y; {meaning x=x%y} Modulus AND


assignment operator. It takes modulus using
two operands and assigns the result to the
left operand.

Increment/Decrement Operators: -

C supports two unique operators: ++ and --.Both are unary operators

Operator Name Description

++ Increment operator x++; Increment operator add 1 to the value


of the operand.

-- Decrement x--; Decrement operator subtracts 1from


operator the value of the operand.

(meaning need only one operand).

eg: int m=5;


m++;{meaning m=m+1}
printf(“%d”, m);
Output: 6
eg: int m=5;
m--; {meaning m=m-1}
printf(“%d”, m);
Output: 4
Increment and decrement operators are further classified as prefix and
postfix.
The difference between prefix and postfix is observable when the
result is stored in a variable and then printed.
++var or --var are prefix operators. {Prefix operators does the operation
first and then passes the value}
var ++ or var -- postfix operators. {Postfix operators passes the value
first and then does the operation}

eg1:
#include <stdio.h>
int main()
{
int x=10, y=10, ans;
ans=++x;
printf("Prefix answer:%d",ans);
ans=y++;
printf("\nPostfix answer:%d",ans);
printf("\nValue of x:%d",x);
printf("\nValue of y:%d",y);
return (0);
}
Output:
Prefix answer:11
Postfix answer:10
Value of x:11
Value of y:11

eg2:
#include <stdio.h>
int main ()
{
int x=4, y=5, ans;
ans=++x + y++;
printf("Result: %d",ans);
return (0);
}
Output:
Result:11

C - Decision Making
Decision making is required when one or more conditions is to be
tested in a program. If the condition is true then a statement or group
of statements will be executed and if the condition is false then
another set of statement or statements will be executed.
Shown below is the general form of a typical decision making structure.
if Statement

if-else Statement
In C language, the if…. else statement is used for decision making.

Syntax:
if (expression)
{
statement(s);
}
else
{
statement(s);
}
The expression after the 'if' is called the condition of the if statement. If
the expression is evaluated to true, the statement(s) following 'if'
clause execute and if the expression evaluates to a false value, the
statement following the 'else' clause execute. See the following
pictorial presentation of if-else statement.

Examples:
1. A program to find the largest of 2 numbers: -
#include <stdio.h>
int main()
{
int x, y;
printf("Enter 2 different integers");
scanf("%d %d",&x,&y);
if(x>y)
printf("The largest of the 2 numbers is %d",x);
else
printf("The largest of the 2 numbers is %d",y);
return(0);
}

2. A program to check whether 2 numbers are equal: -


#include <stdio.h>
int main()
{
int x,y;
printf("Enter 2 integers");
scanf("%d %d",&x,&y);
if(x==y)
printf("The numbers are equal");
else
printf("The numbers are not equal");
return(0);
}
3. A program to find whether a person is eligible to vote:-
#include <stdio.h>
int main()
{
float age;
printf("Enter the age of the person:");
scanf("%f",&age);
if(age>=18)
printf("Eligible to vote");
else
printf("Not eligible to vote");
return(0);
}

Nested if...else statement (if...elseif....else Statement)


Syntax:
if (expression1)
{
statement(s);
}
else if (expression2)
{
statement(s);
}
.
.
.
else if (expression n)
{
statement(s);
}
else
{
statements;
}

At the time of execution, the compiler will check the expression


(condition) one after the other, if any expression (condition) is found to
be true, the corresponding statement will be executed. If none of the
expression (condition) is true then the statement after the last else will
be executed.
Examples:
1. A program to find the largest of 2 numbers or if they are equal: -
#include <stdio.h>
int main()
{
Int x,y;
printf("Enter 2 integers");
scanf("%d %d",&x,&y);
if(x==y)
printf("The numbers are equal");
else if(x>y)
printf("The largest of the 2 numbers is %d",x);
else
printf("The largest of the 2 numbers is %d",y);
return(0);
}

2. A program to find the grades obtained:


# include<stdio.h>
int main()
{
float mark;
printf ("Enter the marks out of 100: ");
scanf("%f",&mark);
if(mark>90)
printf("Grade A1");
else if (mark<=90 && mark > 80)
printf("Grade A2");
else if (mark<=80 && mark > 70)
printf("Grade B1");
else if (mark<=70 && mark > 60)
printf("Grade B2");
else if (mark<=60 && mark > 50)
printf("Grade C1");
else if (mark<=50 && mark > 40)
printf("Grade C2");
else if (mark<=40 && mark > 32)
printf("Grade D");
else
printf("Failed");
return 0;
}

You might also like