You are on page 1of 47

Programming in C

CS 3090: Safety Critical Programming in C 1


About C
• C is a structured programming language
• C supports functions that enables easy maintainability of code, by
breaking large file into smaller modules
• Comments in C provides easy readability
• C is a powerful language.
• C programs built from
• Variable and type declarations
• Functions
• Statements
• Expressions
Case Sensitivity
• C is a case sensitive language.
• It matters whether an identifier, such as a variable name, is
uppercase or lowercase.
• Example:
area
Area
AREA
ArEa
are all seen as different variables by the compiler.
Structure of a C Program
Compiler
• Compiler converts human readable instructions into machine
readable instructions.
• Errors are displayed after entire program is checked
Difference between Compiler and Interpreter
• Compiler Takes Entire program as input.
• Interpreter Takes Single instruction as input .
• Compiler Generates Intermediate Object Code.
• Interpreter No Intermediate Object Code is Generated.
• Compiler Errors are displayed after entire program is checked.
• Interpreter Errors are displayed for every instruction interpreted (if
any)
Variables
• A Variable is a data name to store any data value.
• Variables are used to store values that can be changed during the
program execution.
• Variables in C have the same meaning as variables in algebra. That is,
they represent some unknown, or variable, value.
x = a + b z + 2 = 3(y - 5)
Variable Data Types
• Variable Storing Integer Data Type is called as “Integer Variable“.
• Variable Storing Character Data Type is called as “Character
Variable“.
• Variable Storing Float Data Type is called as “Float Variable“.
• Variable Storing Double Data Type is called as “Double Variable“.
More Data types
• Variable storing single value at a time of any data type is called as
“Normal or Ordinary” Variable.
• Variable Storing multiple values of same data type is called
as “Array“.
• Variable Storing multiple values of different data type is called as
“Structure” [ User defined data type]
Declaring Variables
• Before using a variable, you must give the compiler some information
about the variable; i.e., you must declare it.
• The declaration statement includes the data type of the variable.
• Examples of variable declarations:
int length ;
float area ;
• Variables are not automatically initialized.
• For example, after declaration int sum; the value of the variable sum can be
anything (garbage).
• Thus, it is good practice to initialize variables when they are declared.
• Once a value has been placed in a variable it stays there until the program alters it.
C assignment operator
• Assignment Operator is Used to assign value to an variable.
• Assignment Operator is denoted by equal to sign
Printf and Scanf
◻ printf (); //used to print to console(screen)
◻ scanf (); //used to take an input from console(user).
◻ example: printf(“%c”, ’a’); scanf(“%d”, &a);
◻ More format specifiers
%c The character format specifier.
%d The integer format specifier.
%i The integer format specifier (same as %d).
%f The floating-point format specifier.
%o The unsigned octal format specifier.
%s The string format specifier.
%u The unsigned integer format specifier.
%x The unsigned hexadecimal format specifier.
%% Outputs a percent sign.
More on Printf
printf( "Original input : %s\n", input );
• printf() is a library function declared in <stdio.h>
• Syntax: printf( FormatString, Expr, Expr...)
• FormatString: String of text to print
• Exprs: Values to print
• FormatString has placeholders to show where to put the values (note:
#placeholders should match #Exprs)
• Placeholders: %s (print as string), %c (print as char),
%d (print as integer),
%f (print as floating-point)
• \n indicates a newline character
More on Scanf
• & in scanf.
• It is used to access the address of the variable used.
• example:
• scanf(%d,&a);
• we are reading into the address of a.
C Arithmetic operators
• C Programming Supports 5 Arithmetic Operators.
Example
#include <stdio.h>
int main()
{
int num1,num2;
int sum,sub,mult,div,mod;
printf("\nEnter First Number :");
scanf("%d",&num1);
printf("\nEnter Second Number :");
scanf("%d",&num2);
….
sum = num1 + num2;
printf("\nAddition is : %d",sum);
sub = num1 - num2;
printf("\nSubtraction is : %d",sub);
mult = num1 * num2;
printf("\nMultiplication is : %d",mult);
div = num1 / num2;
printf("\nDivision is : %d",div);
mod = num1 % num2;
printf("\nModulus is : %d",mod);
return(0);
}
C Escape Sequence
Constant Meaning
‘a’ Audible Alert (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
‘\’ Backslash
‘\0’ Null
Tab : ‘\t’ Character
#include<stdio.h>
int main()
{
printf("Hello\t");
return(0);
}
Output:
Hello _
New Line Character : ‘\n’ Character
#include<stdio.h>
int main()
{
printf("Hello\n");
return(0);
}
Output:
Hello
-
Backslash : ‘\b’ Character
#include<stdio.h>
int main()
{
printf("Hello\b");
return(0);
}
Output:
Hell_
Carriage Return : ‘\r’ Character
#include<stdio.h>
int main()
{
printf("Hello\r");
return(0);
}
Output:
_ello
Audible Return : ‘\a’ Character
#include<stdio.h>
int main()
{
printf("Hello\a");
return(0);
}
Output:
Hello
<Hello will be followed by a beep sound>
My first C program!
#include <stdio.h>
// program prints hello world
int main() {
printf ("Hello world!");
return 0;
}

Output: Hello world!


Difference?
#include <stdio.h>
// program prints hello world
void main() {
printf ("Hello world!");
}

Output: Hello world!


Example 1
#include <stdio.h>
// program prints a number of type int
int main() {
int number = 4;
printf (“Number is %d”, number);
return 0;
}

Output: Number is 4
Example 2
#include <stdio.h>
// program reads and prints the same thing
int main() {
int number ;
printf (“ Enter a Number: ”);
scanf (“%d”, &number);
printf (“Number is %d\n”, number);
return 0;
}

Output : Enter a number: 4


Number is 4
Hands on!
#include <stdio.h>

int main() {
/* this program adds
all marks and prints the average */
Get int mark1; //first subject marks
Get int mark2; //second subject marks
Get int mark3; //third subject marks
calculate total ; //result
calculate average; //average
}
C increment operator
C has two special unary operators called
increment (++)
decrement (--)

operators increment and decrement value of a variable by 1.

++x is same as x = x + 1 or x += 1
--x is same as x = x - 1 or x -= 1
Increment/Decrement operators are of two types:

1. Prefix increment/decrement operator.


2. Postfix increment/decrement operator.
Prefix increment/decrement operator

The prefix increment/decrement operator immediately increases or decreases the


current value of the variable. This value is then used in the expression
y = ++x;

Here first, the current value of x is incremented by 1.


The new value of x is then assigned to y.
y = --x;

The current value of x is decremented by 1.


The new value of x is then assigned to y
Postfix Increment/Decrement operator

The postfix increment/decrement operator causes the current value of the variable
to be used in the expression, then the value is incremented or decremented.

y = x++;

Here first, the current value of x is assigned to y then x is incremented.


y = x--;

the current value of x is assigned to y then x is decremented.


Guess the output
x=10; a=12; z=5; s=3;

Y=++x; b=a++; m=--z; h=s--;


Pre Increment
#include<stdio.h>
int main()
{
int x = 12, y = 1;
printf("Initial value of x = %d\n", x); // print the initial value of x
printf("Initial value of y = %d\n", y); // print the initial value of y
y = ++x; // increment the value of x by 1 then assign this new value to y
printf("After incrementing by 1: x = %d\n", x);
printf("y = %d\n", y);
y = --x; // decrement the value of x by 1 then assign this new value to y
printf("After decrementing by 1: x = %d\n", x);
printf("y = %d\n", y);
// Signal to operating system everything works fine
return 0;
}
Post Increment
#include<stdio.h>
int main()
{
int x = 12, y = 1;
printf("Initial value of x = %d\n", x); // print the initial value of x
printf("Initial value of y = %d\n\n", y); // print the initial value of y
y = x++; // use the current value of x then increment it by 1
printf("After incrementing by 1: x = %d\n", x);
printf("y = %d\n\n", y);
y = x--; // use the current value of x then decrement it by 1
printf("After decrementing by 1: x = %d\n", x);
printf("y = %d\n\n", y);
// Signal to operating system everything works fine
return 0;
}
Operator Precedence

The increment and decrement operators have higher precedence than the
operators we have discussed so far (with the only exception being the
parentheses).

Further, Postfix increment/decrement operators have higher precedence than the


prefix increment/decrement operators.
Operators Description Associativity
() parentheses left to right

++, -- postfix increment operator, postfix decrement left to right


operator

++, --, +, - prefix increment operator, prefix decrement right to left


operator, unary plus, unary minus

*, /, % Multiplication, Division and Modulus left to right

+, - Addition and Subtraction left to right

=, +=, -=, *=, /=, %= Assignment Operator and Compound right to left
assignment operator
Example 1
int x, y, z;
x = 5;
y = 8;
z = ++x + y++;
Example 2
int a, b, c;
a = 10;
b = 20;
c = 1;
c += a++ * 5 - --b;
Relational Operators
• Relational operators are used to compare values of two
expressions.
• Relational operators are binary operators because they require two
operands to operate.
• If the relation is true then the result of the relational expression is 1,
if the relation is false then the result of the relational expression is
0.
Logical Operators
• Logical operators are used to evaluate two or more conditions.
Hands On

You might also like