28
Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Embed Size (px)

Citation preview

Page 1: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Introduction to Computer Algorithmics and Programming

Ceng 113

Variables and Operators in C

Page 2: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

C Language

C was developed at Bell Laboratories.

(Brian Kernighan and Dennis Richie)-1972

C is known as a high low-level language.

Page 3: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Reference Book

In Library:

C The Complete Reference, Covers C++ & ANSI C

Author; Herbert Schildt

Press; Osborne, McGraw-Hill

ISBN 0-07-881538-X

E-book:

The C Programming Language (ANSI C)

Authors: Brian W. Kernighan,

Dennis M. Ritchie

Page 4: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Program Definitions

• Variable: a named location in memory for storing data.

• Constant: a variable whose value is determined when a

program description is written and doesn’t change from

that value during program execution.

• Label: a named location in memory for storing a

program instruction.

Page 5: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

General Form of a C Program

global declarationsreturn-type main(parameter list){

statement sequence}return-type f1(parameter list){

statement sequence}return-type f2(parameter list){

statement sequence}....

• Consist of one or more

functions.

• “main(..)”, which is the first

function called, when

program execution begins.

Page 6: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

A Sample C Program

/* Letter guessing game */

#include <stdio.h>

#include <time.h>

#include <stdlib.h>

main()

{ int tries = 0;

char compAns, userGuess;

/* Save the computer's letter */

srand(time(NULL)); /* Randomize the number generator */

compAns = (rand() %26) +65; /* generate a random letter */

printf("I am thinking of a letter...");

...

Page 7: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

A Sample C Programdo {

printf("What is your guess? ");scanf(" %c", &userGuess);tries++; /* Add 1 to the guess counter */

if (userGuess > compAns){ printf(" Your guess was too high \n"); printf(" \n Try again ...");}if (userGuess < compAns){ printf(" Your guess was too low \n"); printf(" \n Try again ...");}

} while (userGuess != compAns); /* Quit when a match is found */

/* User got it right, announce it */

printf("*** Congratulations! You got it right! \n");printf("It took you only %d tries to guess.", tries);return 0;

}

Page 8: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

The Library and Linking

All C compilers come with a standard C library of functions

that perform most commonly needed tasks.

When you call a function that is not parf of your program,

the C compiler “remembers” its name. Later, the “linker”

combines the code you wrote with the object code

already found in the standard library. This process is

called linking.

Page 9: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Separate Compilation

C allows a program to be contained in many files and lets

you compile each file separately.

The advantage of separate compilation is that if you

change the code of one file, you don’t need to recompile

the entire program.

Page 10: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

The Terms

• Source Code; The text of a program that a user can read. The source code is input in to the C compiler.

• Object Code; Translation of the source code of a program into machine code, which the computer can read and execute directly. Object code is the input to the linker.

• Linker; A program links separately-compiled functions into one program.The output of the linker is an executable program.

• Library; The file containing the standard functions that your program may use. (all I/O operations, useful routins..)

SourceCode Compiler Object

Code LinkerExecutable

program

Page 11: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Basic Data Types

Data types;• char• int• float• double

Type ApproximateSize in Bits Minimal Range

char 8 -127 to 127

unsigned char 8 0 to 255

int 16 -32767 to 32767

unsigned int 16 0 to 65535

signed int 16 same as int

short int 16 same as int

long int 32 -2,147,483,647 to 2,147,483,647

unsigned long int. 32 0 to 4,294,967,295

float 32 Six digits of precision

double 64 Ten digits of precision

long double 128 Ten digits of precision

Modifiers;• signed• unsigned• long• short

(long float has the same meaning as double).

Page 12: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Variables

• A variable is a named location in memory that is used to

hold a value that may be modified by the program.

• All variables must be declared before they can be used.

• General declaration form is;

type variable_list;

Example;

int i, j, l;

unsigned int u;

double balance, profit, loss;

Page 13: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Declaration of Variables

Variables will be declared in three basic places;

1. inside functions local variables

2. in the definition of function parameters formal

parameters

3. outside of all functions global variables

Page 14: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Sample – local variables

/* Addition */

#include <stdio.h>

#include <stdlib.h>

main()

{ int a, b, c;

printf(“\n insert a = %d”);

scanf(" %d", &a);

printf(“\n insert b = %d”);

scanf(" %d", &b);

c = a + b;

printf(“\n a + b = %d”, c);

}

Page 15: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Sample – formal parameters/* Addition */#include <stdio.h>#include <stdlib.h>int addition(int x, int y);main(){ int a, b, c;

printf(“\n insert a =”);scanf(" %d", &a);printf(“\n insert b =”);scanf(" %d", &b);c = addition(a, b);printf(“\n a + b = %d”, c);

}int addition(int x, int y) {

int z;z = x + y;return(z);

}

Page 16: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Sample – global parameters/* Addition */

#include <stdio.h>

#include <stdlib.h>

int a, b, c;

void addition( );

main()

{ printf(“\n insert a = “);

scanf(" %d", &a);

printf(“\n insert b = ”);

scanf(" %d", &b);

addition();

printf(“\n x + b = %d”, c);

}

void addition( ) {

c = a + b;

}

Page 17: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Local Variables

void func1(void)

{

int x;

x = 10;

}

void func2(void)

{

int x;

x = -199;

}

void f(void)

{

int t;

scanf(“%d”, &t);

if (t==1) {

char s[80];

printf(“enter name:”);

gets(s);

.... /* do something */

}

}

#include “stdio.h”

void f(void)

void main(void)

{

int i;

for(i=0; i<10; i++) f();

}

void f(void)

{

int j = 10;

printf(“%d”, j);

}

Page 18: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Formal Parameters

• If a function is to use arguments, it must declare variables that will accept the values of the arguments. These variables are called the formal parameters of the function.

/* Return 1 if c is part of string s; 0 otherwise */

is_in(char *s, char c)

{

while (*s)

if (*s==c) return 1;

else s++;

return 0;

}

Page 19: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Global Variables

#include “stdio.h”

int count; /* count is global */

void func1(void);void func2(void);

void main(void){

count = 100;func1();

}void func1(void){

int temp;temp = count;func2();printf(“count is %d”, count);

}

Global variables are known throughout the program and may be used by any piece of code.

void func2(void){

int count;for (count=1; count<10; count++)

putchar(‘.’);}

Page 20: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

const• Variables of type const may not be changed by your program. • A const variable can be given an initial value.

const int a = 10;#include “stdio.h”void sp_to_dash(const char *str);

void main(void){ sp_to_dash(“this is a test”);}

void sp_to_dash(const char *str){ while (*str) {

if (*str==‘ ‘) printf(“%c”, ‘-’);else printf(“%c”, *str);str++;

}}

#include “stdio.h”void sp_to_dash(const char *str);

void main(void){ sp_to_dash(“this is a test”);}

void sp_to_dash(const char *str){ while (*str) {

if (*str==‘ ‘) *str=‘-’;printf(“%c”, *str);str++;

}}

Page 21: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Operators• The assignment operator;

variable_name = expression;

The target, or left part of the assignment must be a variable or a pointer, not a function or a constant.

• Multiple assignment ; x = y = z = 0;• The conversion assignment;

When variables of one type are mixed with variables of another type, a type conversion will occur.

int x; char ch; float f;

void func(void)

{ ch = x;

x = f;

f = ch;

f = x;

}

Page 22: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Common type conversion (Samples)

Target Type Expression Type Posssible info loss

char short int High order 8 bits

char int High order 8 bits

int long int High order 16 bits

int float Fractional part

float double Precision, result rounded

Page 23: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Arithmetic Operators

Operator Action

- Subtraction

+ Addition

* Multiplication

/ Division

% Modulus

-- Decrement

++ Increment

Page 24: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Relational or Logical OperatorsRelational Operators

Operator Action

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

== Equal

!= Not Equal

Logical Operators

Operator Action

&& AND

|| OR

! NOT

In C, true is any value other than zero. False is zero.

Page 25: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Logical Operators

AND

p q p&&q

0 0 0

0 1 0

1 0 0

1 1 1

OR

p q p || q

0 0 0

0 1 1

1 0 1

1 1 1

NOT

p !p

0 1

1 0

Page 26: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Sample for Logical Operations

#include “stdio.h”

int xor(int a, int b);

void main(void)

{ printf(“%d”, xor(1, 0));

printf(“%d”, xor(1, 1));

printf(“%d”, xor(0, 1));

printf(“%d”, xor(0, 0));

}

/*perform logical XOR operation using the two argumants. */

int xor(int a, int b);

{

return (a||b)&& !(a&&b);

}

a b a XOR b

0 0 0

1 0 1

0 1 1

1 1 0

Page 27: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Lab. Exercise #1

• Write a program that implements SWAP

operation for two integer variables

– with using a temp space,

– without using a temp space.

Page 28: Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C

Next Course

Program Control Statements• Selection

– if and switch

• Iteration

– while, for, do-while

• Jump

– break, continue, goto, return

• Label

• Expression

• Block

– A block begins with a { and ends with a }.