Sunday, 14 October 2012

ARRAYS-IKHWAN AND NAZERUL


Arrays
 
Array is data structure used to share multiple data elements under a single name declaration. 
It's important that every single element of data, we wish to assign to array, belongs to the same data type. 
Arrayâ's elements are easily accessed - 
we use index; a number that must be nonnegative integer (constant, variable, integer expression). 
Element's index is a number between 0 and the number of elements minus one, including. In short: Index ( [0, NrOfElements-1].
 
 
Declaration of an array:
 
data_type array_name[index];
 
 
 
Array's definition in C:
 
int x[20] - array consisted of 20 integer numbers
char symbols[2] - array consisted of 2 characters
float sequence[MAX] - MAX is constant
 
 
 
Assigning element's values definition:
 
int array[ ] = {1, 2, 3};
array[0] = 1
array[1] = 2
array[2] = 3
 
int array [4] = {1, 2};
array[0] = 1
array[1] = 2
array[2] = 0
array[3] = 0
 
 
 
Accessing array's elements:
 
x[0] - first element of an array
sequence[i] -i. element of an array, 0 <= i <= NrOfElements-1
sequence[MAX-1] last element of an array
 
 
 
Common Wrong access to array's elements:
 
int array[10] = {0};
int x = sequence[10];
 
float a = 1.;
int x = array[a];
int a = 1, b = 0, c = 1;
int x = array[(a && b) - c];
 
 
 
 
Example:
 
Write your own program that asks user to input sequence of numbers, afterwards it calculates arithmetic middle of the given sequence. 
Program also prints numbers smaller than arithmetic middle, and afterwards prints numbers bigger than arithmetic middle.
 
 
 
#include <stdio.h>
#define DIMENSION 10
 
int main(void) {
 
int i;
  float sum = 0., arit_midd = 0., sequence[DIMENSION]={0};
  
  for (i = 0; i < DIMENSION; i++) {
 
    printf("Input number: ");
    scanf("%f",&sequence[i]);
    sum += sequence[i];
 
  } 
 
  arit_midd = sum / DIMENSION;
  printf("Arithmetic middle of the sequence is %6.2f.\n", arit_midd);
  for (i = 0; i < DIMENSION; i++) {
 
    if (sequence[i] < arit_midd) {
 
      printf("%6.2f is smaller than arithmetic middle.\n", sequence[i]);
 
    }
  }
 
  for (i = 0; i < DIMENSION; i++) {
 
    if (sequence[i] > arit_midd) {
 
      printf("%6.2f is bigger than arithmetic middle.\n", sequence[i]);
 
    }
  }
     
  // What happens if the number is equal to arithmetic middle?
 
}
 
 
 
 
 
 
Example:
 
Write your own program that asks for input of sequence of numbers. After the program reads given numbers, 
it divides every number with the biggest sequence element and shows them in a way relative to the biggest element.
 
 
#include <stdio.h>
#define DIMENSION 10
 
int main(void) {
 
  int i;
  float max, array[DIMENSION]; 
 
  for (i = 0; i < DIMENSION; i++) {
 
    printf("array[%d] = ", i);
    scanf("%f",& array[i]);    
    if (i == 0) {
 
      max = array[i];
 
    }
    if (max < array[i]) {
 
      max = array[i];
 
    }
  } 
 
  printf("Biggest element in array is %f.\n\n", max);
  for (i = 0; i < DIMENSION; i++) {
 
    array[i] /= max;
    printf("array[%d] = %f\n", i, array[i]);
 
  }
}
 
 
 
 
 
 
Example:
 
Compose your own program that reads given natural numbers that belong in [10, 99] interval and counts how many times each number showed up. 
Program stops reading numbers when element that doesn’t belong to interval is given. Af
afterwards, program prints each number from the interval that has showed at least once, and number of times it has really been given.
 
 
#include <stdio.h>
 
#define LL 10          /* lower limit of the interval */
#define UL 99          /* upper limit of the interval */
 
int main(void) {
 
  int number, i;
  int counter[UL – LL + 1] = { 0 };     
 
  do {
 
    printf("\nInput number from interval [%d, %d]: ", LL, UL);
    scanf("%d", &number);
    if (number >= LL && number <= UL) {
 
      counter[number - LL]++;
 
    }
 
  } while (number >= LL && number <= UL); 
 
  for (i = DG; i <= UL; i++) {
 
    if (counter[i - LL] > 0) {
 
      printf("\nNumber %d showed up %d times", i, counter [i - LL]);
 
    }
  }
}

 

 

 

 

 

 

 

 

 

Multi dimensional Arrays:

Often there is a need to store and manipulate two dimensional data structure such as matrices & tables. Here the array has two subscripts. One subscript denotes the row & the other the column.


The declaration of two dimension arrays is as follows:
data_type array_name[row_size][column_size];
int m[10][20]

Here m is declared as a matrix having 10 rows( numbered from 0 to 9) and 20 columns(numbered 0 through 19). The first element of the matrix is m[0][0] and the last row last column is m[9][19]

Elements of multi dimension arrays:

A 2 dimensional array marks [4][3] is shown below figure. The first element is given by marks [0][0] contains 35.5 & second element is marks [0][1] and contains 40.5 and so on.

marks [0][0]
35.5

marks [0][1]
40.5

marks [0][2]
45.5

marks [1][0]
50.5

marks [1][1]
55.5

marks [1][2]
60.5

marks [2][0]

marks [2][1]

marks [2][2]

marks [3][0]

marks [3][1]

marks [3][2]


Initialization of multidimensional arrays:

Like the one dimension arrays, 2 dimension arrays may be initialized by following their declaration with a list of initial values enclosed in braces
Example:
int table[2][3]={0,0,0,1,1,1};
Initializes the elements of first row to zero and second row to 1. The initialization is done row by row. The above statement can be equivalently written as
int table[2][3]={{0,0,0},{1,1,1}}
By surrounding the elements of each row by braces.
C allows arrays of three or more dimensions. The compiler determines the maximum number of dimension. The general form of a multidimensional array declaration is:

date_type array_name[s1][s2][s3]…..[sn];
Where s is the size of the ith dimension. Some examples are:
int survey[3][5][12];
float table[5][4][5][3];

Survey is a 3 dimensional array declared to contain 180 integer elements. Similarly table is a four dimensional array containing 300 elements of floating point type.

/* example program to add two matrices & store the results in the 3rd matrix */
#include< stdio.h >

void main()
{
      int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q;

      printf(“enter the order of the matrix\n”);
      scanf(“%d%d”,&p,&q);

      if(m==p && n==q)
      {
            printf(“matrix can be added\nn”);
            printf(“enter the elements of the matrix a”);
            for(i=0;i < m;i++)
                  for(j=0;j < n;j++)
                  scanf(“%d”,&a[i][j]);

            printf(“enter the elements of the matrix b”);

            for(i=0;i < p;i++)
                  for(j=0;j < q;j++)
                  scanf(“%d”,&b[i][j]);
     
printf(“the sum of the matrix a and b is”);
for(i=0;i < m;i++)
      for(j=0;j < n;j++)
            c[i][j]=a[i][j]+b[i][j];

for(i=0;i < m;i++)
{
      for(j=0;j < n;j++)
      printf(“%dt”,&a[i][j]);
      printf(“n”);
      }
}

STRINGS-IKHWAN AND NAZERUL


Strings

A string in C is simply an array of characters. The following line declares an array that can hold a string of up to 99 characters.
char str[100];
It holds characters as you would expect: str[0] is the first character of the string, str[1] is the second character, and so on. But why is a 100-element array unable to hold up to 100 characters? Because C uses null-terminated strings, which means that the end of any string is marked by the ASCII value 0 (the null character), which is also represented in C as '\0'.
The string I/0 operations (gets, puts, and so on) are implemented in <stdio.h>, and a set of fairly simple string manipulation functions are implemented in <string.h> (on some systems, <strings.h> ).
#include<stdio.h>
#include<string.h>
 
void main()
{
    char name[100];
 
    printf("Enter your name:");
    gets(name);
 
    printf("Assalamualikum mr/ms:");
    puts(name);
}
Hint : is same as :
#include<stdio.h>
#include<string.h>
 
void main()
{
    char name[100];
 
    printf("Enter your name:");
    scanf(%s,name);
 
    printf("Assalamualikum mr/ms:%s",name);
    
}

If you want to copy the contents of one string to another, the string library (<string.h> or <strings.h> ) contains a function called strcpy for this task.
char s[100];
strcpy(s, "yosof");
The following code shows how to use strcpy in C:
#include<stdio.h>
#include<string.h>
 
void main()
{
    char s1[100],s2[100];
 
    strcpy(s1,"yosof"); /* copy "yosof" into s1 */
    printf("s1 is %s\n",s1);
 
    strcpy(s2,s1);      /* copy s1 into s2 */
    printf("s2 is %s\n",s2);
}
strcpy is used whenever a string is initialized in C. You use the strcmp function in the string library to compare two strings. It returns an integer that indicates the result of the comparison. Zero means the two strings are equal, a negative value means that s1 is less than s2, and a positive value means s1 is greater than s2.
#include <stdio.h>
#include <string.h>

void  main()
{

      char s1[100],s2[100];

      printf("Enter value for s1:");
      gets(s1);

      printf("Enter value for s2");
      gets(s2);

      if (strcmp(s1,s2)==0)
      {
            printf("equal\n");
      }
      else if (strcmp(s1,s2)<0)
      {
            printf("s1 less than s2\n");
      }
      else
      {
            printf("s1 greater than s2\n");
      }
}

Other common functions in the string library include strlen, which returns the length of a string, and strcat which concatenates two strings.
#include<stdio.h>
#include <string.h>
void main()
{
    char stringOne[255];
    char stringTwo[255];

    stringOne[0]='\0';
    stringTwo[0]='\0';

    printf("Enter a string:");
    gets(stringOne);

    printf("Enter a second string:");
    gets(stringTwo);


    printf("String One: %s\n",stringOne);
    printf("String Two: %s\n",stringTwo);


    strcat(stringOne," ");
    printf("String One: %s\n",stringOne);
   
    strncat(stringOne,stringTwo,10);
    printf("String One: %s\n",stringOne);
    printf("String Two: %s\n",stringTwo);
}

#include<stdio.h>
#include <string.h>


void main()
{

      int length;
      char name[100];

      printf("Enter your name:");
      gets(name);

      length=strlen(name);

      printf("For %s no of character is %d\n",name,length);

}

VARIABLES-IKHWAN AND NAZERUL


VARIABLES,  DATA TYPES,  ASSIGNMENT OPERATOR


Variables

The definition of a variable specifies three things :
·         Its visibility, which indicates exactly where the variable can be used, e.g. for whole file or only in function
·         Its lifetime, which determine whether the variables exists temporarily or permanently, eg local and global
·         Its type and where allowed, its initial value

To define a variable,  you must understand the following characters :
·         Each variables has a name
·         Each variables has a type
·         Each variables holds a value that you assign to the variables

Naming variables

Variable names can be short as a single letter or as long as 31 characters. The  name must begin with a letter of the alphabet but after the first letter they can contain a letters, numbers and underscore (_)  character. 
The following variables are all valid:
                                sales       Aug91_sales         i               indexAge               Amt    jejari      luas
The following variables are all invalid:
                                81-sales Aug91+sales         my age                   printf   scanf main include define


?  Uppercase letter in variable names  are different from lowercase letter.
Give your names that help describe the value they are holding.

               
Define a variable

                There are two places where you can define a variable:
                Þ after the brace of a block of code (usually at the top of a function)
                Þ before a function name ( such as before main() in the program)
                Example:

main()
{
                int i,j;                                      /* These three lines define 4 variables */
                char c;
                float k;

                /* Rest of program follows */
                                .
}

Explanations:
int i,j;                                                      /* Define the variables i and j as integers. */
char c;                                                    /* Define the variable c as a character. */
float k;                                                   /* Define the variable k as a floating point. */


          Basic Data type

Variables can hold different types of data. C  supports seven built-in data types and it identifiers them by keywords. 
Data type
C keyword
Bits
Range
Integer
Long integer
Short integer
unsigned integer
int
long
short
unsigned
16
32
8
16
-32768 to 32767
-4294967296 to 4294967295
-128 to 127
0 to 65535
Character
char
8
0 to 255
Floating point
double floating point
float
double
32
64

approximately 6 digits of precision
approximately 12 digits of precision
                                                   Table :   Basic Data Type

Assignment  statements and Assignment Operators

The  assignment operator (=) behave differently  from what you might be used to in other languages. The operator used for simple assignment of values to variables, which is consistent with its use  in most other programming languages. 

                FORMAT
                                variable = expression   ;

The expression is any  variable , constant, expression or combination that produces a resulting data type that is the same as the variable’s data type.
                Examples:
                age=32;
                salary=25000.00;
                dependents=2;
However,  the assignment operator also can be used on other ways,  such as for multiple assignment statements and compound assignments .

Multiple Assignments
If two or more equal signs appear in an expression ,  each of them performs an assignments.
Examples:
                                                a=b=c=d=100;
                                                value = 5 + (r = 9 - c);
Assignment Operators
C++ provides several assignment operators for abbreviating assignment expressions.  For example the statement
                c = c+3;
can abbreviated with the addition assignment operators += as
                c += 3;
Any statement of the form
                                variable = variable operator expression;
                where operator is one of the binary operators +, -, *, /, or % can be written in the form
                                variable operator =  expression;










Operator         Example                               Equivalent
+=                      bonus+=500;                        bonus=bonus+500;
-=                       budget - = 50;                       budget=budget - 50;
*=                      salary *=1.2;                        salary=salary *1.2;
/=                       factor/=.5;                             factor=factor/.5;
%=                    daynum %=7                       daynum=daynum%7;       
               
Table : Display the arithmetic assignment operators in C


Console Input

Console input (scanf)
You already know about console output (printf function).  In this section we’re going to introduce an important input function, scanf or console input. scanf is an object of the istream class and is said to be “tied to” or connected to the standard input device, normally the keyboard.  The stream-extraction operator as used in the following statement causes a value for integer variable grade (assuming grade has been declared as int) to be input from scanf to memory.
                scanf ("%d", &grade);
Note that the stream-extraction operation is smart enough to know what type of the data is. Assuming the grade has been properly declared, no additional data type needs to be specified for use  with the stream-extraction operator.




                /* C program  that demonstrate the use of scanf to calculate the sum of two integer input from
                   the keyboard */

                #include <stdio.h>
               
                main()
                {
                                int x;
                             int y ;
                                int sum;

                                printf(“\nEnter an integer :“) ;
                                scanf("%d", &x) ;
                             printf(“\nEnter an integer :“) ;
                                scanf("%d", &y) ;

                                sum = x + y;

                                printf( “\nSum of  two integers is %d“,sum );
                                               
                                return 0;
                }












            /* C program  that demonstrate the use of scanf to calculate the sum of two integer input from
                   the keyboard */

                #include <stdio.h>
               
                main()
                {
                                int x, y ;

                                printf(“\nEnter two integers :“) ;
                                scanf("%d %d”, &x, &y) ;
                             printf( “\nSum of  two integers is %d“,  (x + y) );
                                               
                                return 0;
                }




Format identifier or Specifiers

The format specifier tells printf() where to put a value string and what format to use in printing the value, to match the format specifier to the type of variable that is desired :
%c
Single character
%s
String
%d
Signed decimal
%f
Floating point (decimal notation)
%e
Floating point (exponential notation)
%u
Unsigned decimal integer
%x
Unsigned hexadecimal integer (uses"abcdef")
%o
Unsigned octal integer
L or L ( %ld, %lu, % lx, %lo )
Long integer or long double floating point













Exercise

Write a c program to:

1. Calculate the area of a circle

2. Calculate the circumference of a circle

HINT: PI=3.14 ( ini adalah constant bukan variable )

                area=PI x r x r
                circumference = 2 x PI x r
  
                Where r is a radius

   The program will ask user to enter a value of the radius