Thursday, November 29, 2012

Exercises (arrays, pointers, functions).

Exercises (arrays, pointers, functions).


1. Write a program to update the value of the double variable flt_num from 123.45 to 543.21 by
using a double pointer.

2. Given a character variable ch and ch = ‘A’, write a program to update the value of ch to
character 'a' by using a pointer.

3. Given an integer array initialized as (int niceArray[]={23,4,4,56,45,5,6,1,34,787};), write a
program to increase each array element by 1000 using a nother pointer.

4. Write a function to calculate a factorial value. Then use that function to calculate 6C2 (possible
combinations in selecting 2 out of 6) and display the value.
(Hint: int factorial(int f1); combinations=factorial(6)/(factorial(2)*factorial(4)); )

5. Write seperate functions,
1. to read an integer value from the keyboard, (int readNumber(); )
2. to display two integer values, (void display(int a,int b); )
3. to swap two integer values, (void swap(int *c,int *d); )
Write a program to read two integer values to two variables, display them
before their values are swaped between them then swap those values and
finally display the two variables. (Hint: Use above functions)

Thursday, November 22, 2012

Loop Assignment Answers

Loop Assignment Answers


1) Write a program to display numbers from 1 to 250.

2) Write a program to calculate the sum of all the numbers less than a given number n.
ex: output
Enter number : 3
6
Enter number : 5
15




3) Write a program to display “hello world” for every time we enter the character 'y' and stop the
program when we enter the character 'n'. For any other character program should not stop or
display anything.

4) Write a program to calculate the factorial value for a given number N.

5) Write a program to calculate number of possible combinations that we can have when we
selecting r number of elements from n number of different elements. This can be calculated by
calculating the value n!/(r!*(n-r)!).

Thursday, November 15, 2012

Assignment Answers

Assignment Answers

1) Write a program to check the given number is positive or negative.


2) Write a program to Add two numbers if the first one is greater than the second number if not
display an error message.


3) Write a program to display the grade (A, B, C or D) according to the given mark.
hint: A(between 100 and 75)/ B(between 74 and 65)/ C(between 64 and 55)/ D(between 54 and
0)

4) Write a program to read a two characters and display them if both are not equal.
5) Write a program to input a temperature reading in either Celsius (c) or Fahrenheit (f)scale and
convert it to the other scale. The temperature reading consists of a decimal integer followed by
letter “F” or “f” if the temperature is in Fahrenheit scale or letter “C” or “c” if it is in Celsius
scale. You may use a similar format for the output of the program.








Thursday, August 16, 2012

Pointers


Pointers. 


A pointer is a variable whose value is an address.

                  int thing;            /* define a thing */
int *thing_ptr;   /* define a pointer to a thing */ 


There are things and pointers to things. Knowing the difference between the two is very important.
The address of thing is 0x1000. Addresses are automatically assigned by the C compiler to every variable. Normally, you don't have to worry about the addresses of variables, but you should understand that they're there.
Our pointer (thing_ptr) points to the variable thing. Pointers are also called address variables because they contain the addresses of other variables. In this case, our pointer contains the address 0x1000.




Pointer Operator Syntax. 


The operator ampersand (&) returns the address of a thing which is a pointer. The operator asterisk (*) returns the object to which a pointer points. These operators can easily cause confusion. 













Monday, July 30, 2012

Assignment 01-cmis1223


Assignment 01-cmis1223


1). School Teacher of a Primary School want a software program to calculate the average marks for
Maths, English, Science and Art for a Student.
1. Use the first three steps of the Development Cycle(Define the
problem:input/output/processing, Outline the solution:main Computation/input
variables/intermediate results, Develop an algorithm) to come up with an algorithm.


Inputs : Maths mark , Englsh mark , Science mark
Process :  Calculate average marks
Output  :   Average mark

  calAverage
1.sum <-  (math_mark + English_mark+Science_marrk)
2.average <- sum / 3


2. Write a C program for the Problem.

#include<stdio.h>

main(){

float M_marks , E_marks , Sc_marks;
float Average;

printf("Please enter Maths marks \n");
scanf("%f \n"&M_marks);
printf("Please enter English marks \n");
scanf("%f \n"&E_marks);
printf("Please enter English marks \n");
scanf("%f \n"&Sc_marks);

Average = (M_marks+E_marks+Sc_marks)/3;

printf("Average marks for three subject is %f \n", Average);
}



2). This program is developed to calculate the Age of a living person.

#include <stdio.h>
main() {
int day,month,year;
int bday,bmonth,byear;
printf("\n********Quiz01!********\n");
printf("\nEnter the Todays Date:\f");
scanf("%d/%d/%d",&day,&month,&year);
printf("\nEnter your Birth Day:\f");
scanf("%d/%d/%d",&bday,&bmonth,&byear);
printf("Your Age for Today: %d\n",year-byear);
}


1. Explain the Execution of this program.

#include <stdio.h>

main() {

int day,month,year;     // create memory locations in the main memory

int bday,bmonth,byear; // create memory locations in the main memory

printf("\n********Quiz01!********\n"); // print the text on screen  ********Quiz01!********

printf("\nEnter the Todays Date:\f"); // prin the text Enter the Todays Date

scanf("%d/%d/%d",&day,&month,&year); // blinking curser , values are assign to the relavant memory locations

printf("\nEnter your Birth Day:\f"); // print the text Enter your Birth Day

scanf("%d/%d/%d",&bday,&bmonth,&byear);  //blinking curser , values are assign to the relavant memory locations


printf("Your Age for Today: %d\n",year-byear); // your age for tody year-byear

}




2. Does this program correctly calculates the age of a person? If not explain why?

NO , there is unused variables in this program , day , bday , month , bmonth . Tocalulate the age precisely  have to use this variables as well .

right code to calulate the age precisely -
printf("Your Age for Today: %d  yaers %d  months %d days \n",year-byear , month - bmonth , day-bday);


Sunday, July 15, 2012

Arrays

Hi friends..... ,

We have already talk about simple data types, simple variable can hold only one value at any time during program execution ,although that value is change. We use data structures to save multiple values at the same time.The array is a one kind of data structure.

Lets see about Arrays.........


Arrays of any type can be formed in C. The syntax is simple:
type name[dim];
An array is a group of related data items that all have the same name and the same data type.
Arrays can be of any data type we choose.
An array’s data items are stored contiguously in memory.
Each of the data items is known as an element of the array.  Each element can be accessed individually.


In C, arrays starts at position 0. The elements of the array occupy adjacent locations in memory. C treats the name of the array as if it were a pointer to the first element--this is important in understanding how to do arithmetic with arrays. Thus, if v is an array, *v is the same thing as v[0], *(v+1) is the same thing as v[1], and so on:



int a[5];
An array as a whole has the following properties:
Its elements are contiguous in memory.


Friday, July 13, 2012

Repetition and Looping (for loop , while loop)


Repetition means performing the same set of statements over and over.
The most common way to perform repetition is via looping.
A loop is a sequence of statements to be executed, in order, over and over, as long as some condition continues to be true.
while Loop
C has a loop construct known as a while loop:
        while (condition) {
            statement1;
            statement2;
            ...
        }
The condition of a while loop is a Boolean expression completely enclosed in parentheses – just like in an if block.
The sequence of statements between the while statement’s block open and block close is known as the loop body.



while Loop Behavior

while (condition) {
            statement1;
            statement2;
            ...
        }
A while loop has to the following behavior:
The condition is evaluated, resulting in a value of either true (1) or false (0).
If the condition evaluates to false (0), then the statements inside the loop body are skipped, and control is passed to the statement that is immediately after the while loop’s block close.
If the condition evaluates to true (1), then:
the statements inside the loop body are executed in sequence.
When the while loop’s block close is encountered, the program jumps back up to the associated while statement and starts over with Step 1.

while Loop Flowchart



               statement_before;
                      while (condition) {
                              statement_inside1;
                              statement_inside2;
                                  ...
                       }
               statement_after;









for Loop




                        for (counter = initial_value; counter <= final value; counter++) {
                                 statement1;
                                 statement2;
                                  ...
                        } /* for counter */
                        statement_after

Variables and Arithmetic Expressions.


Variables in C have the same meaning as variables in algebra.  That is, they represent some unknown, or variable, value.
x = a + b
Variables in C may be given representations containing multiple characters.  But there are rules for these representations.
Variable names (identifiers) in C
May only consist of letters, digits, and  underscores
May be as long as you like, but only the first 31 characters are significant
May not begin with a digit
May not be a C reserved word (keyword)

Reserved Words (Keywords) in C

auto     break        float     for                        sizeof                 static
case     char          goto        if
const                continue           int      long            struct                 switch
Default                 do                     register      return
double                else               short                 signed            typedef      union
enum                   extern            unsigned      void                     volatile      while

C Simple program further

stdio.h and int main ()


When we write our programs, there are libraries of functions to help us so that we do not have to write the same code over and over.
Some of the functions are very complex and long.  Not having to write them ourselves make it easier and faster to write programs.
Using the functions will also make it easier to learn to program.
Every program must have a function called main.  This is where program execution begins.
main() is placed in the source code file as the first function for readability.  There must be a function with this name or gcc can not successful compile and link your program.
The reserved word “int” indicates that main() returns an integer value.
The parentheses following the reserved word “main” indicate that it is a function.


The Function Body


A left brace (curly bracket) --  {  -- begins the body of every function.  A corresponding right brace --  }  -- ends the function body.

printf (“Hello, World!\n”) ;

This line is a C statement.
It is a call to the function printf ( ) with a single argument (parameter), namely the string “Hello, World!\n”.
Even though a string may contain many characters, the string itself should be thought of as a single quantity.  
Notice that this line ends with a semicolon.  All statements in C end with a semicolon.


return 0 ;

Because function main() returns an integer value, there must be a statement that indicates what this value is.
The statement
return 0 ;

indicates that main() returns a value of zero to
the operating system.
A value of 0 indicates that the program successfully terminated execution.
Do not worry about this concept now.  Just remember to use the statement


Simple C Program


#include  <stdio.h>
int main ()
{
     printf ( “Hello, World!\n” ) ;
     return 0 ;
}



Program Header Comment and Preprocessor Directives

A comment is descriptive text used to help a reader of the program understand its content.
All comments must begin with the characters  /*  and end with the characters  */
These are called comment delimiters
The program header comment always comes first.

Lines that begin with a # in column 1 are called preprocessor directives (commands).
Example:  the #include <stdio.h> directive causes the preprocessor to include a copy of the standard input/output header file stdio.h at this point in the code.
This header file was included because it contains information about the printf ( ) function that is used in this 
program.

Thursday, July 12, 2012

Stages of Compilation


1. Preprocessing 

Performed by a program called the preprocessor.
Modifies the source code (in RAM) according to preprocessor directives (preprocessor commands) embedded in the source code.
Strips comments and  white space from the code.
The source code as stored on disk is not modified.





2.Compilation


Performed by a program called compiler.
Translate the source code in to machine code (binary code).

Checks for syntax errors and warnings

Saves the object code to a disk file, if instructed to do so (we will not do this).

If any compiler errors are received, no object code file will be generated.

An object code file will be generated if only warnings, not errors, are received.


3.Linking

Combines the program object code with other object code to produce the executable file.
The other object code can come from the Run-Time Library, other libraries, or object files that you have created.
Saves the executable code to a disk file.  On the Linux system, that file is called a.out.
If any linker errors are received, no executable file will be generated.





Writting C programms



A programmer use text editor to write codes.
Code is also known as source code.
A file containing source code is called a source file.
After a C source file has been created, the programmer must invoke the C compiler before the program can be executed (run).
we will use the gcc compiler or cc  as it is the compiler available on the Linux system.
All grading is down on Linux. If you use any other compiler, run it first on the system where the grading is being done.
there are many compilers we can find , but gcc compiler is good in UNIX environment.

If you are using WINDOWS don't worry , I have already published how to  program C in windows.
read the post here


C Language




Currently, the most commonly-used language for embedded systems
“High-level assembly”
Very portable: compilers exist for virtually every processor
Easy-to-understand compilation
Produces efficient code
Designed for systems programming
           Operating systems
           Utility programs
           Compilers
           Filters

Standardized in 1989 by ANSI (American National Standards Institute) known as ANSI C
International standard (ISO) in 1990  which was adopted by ANSI and is known as C89
As part of the normal evolution process the standard was updated in 1995 (C95) and 1999 (C99)
C++ and C
C++ extends C to include support for Object Oriented Programming and other features that facilitate large software development projects.

C History






The C language was first developed in 1972 by Dennis Ritchie at AT&T Bell Labs. Ritchie called his newly developed language C simply because there was a B programming language already. (As a matter of fact, the B language led to the development of C.)

C is a high-level programming language. In fact, C is one of the most popular general-purpose programming languages.

The first version of Unix was written in the low-level PDP-7 assembler language.

Ken Thompson developed a compiler for a new high-level language called B, based on the earlier BCPL language developed by Martin Richard.


BCPL is a simple typeless language .

BCPL (Basic Combined Programming Language) is a computer programming language designed by Martin Richards of the University of Cambridge in 1966.

Originally intended for writing compilers for other languages, BCPL is no longer in common use. However, its influence is still felt due to its role in inspiring Dennis Ritchie's widely-used C programming language.
BCPL was the first curly bracket programming language.

The language is unusual in having only one data type: a word, a fixed number of bits, 
B was used for further development of the Unix system, which made the work much faster and more convenient. 

When the PDP-11 computer arrived at Bell Labs, Dennis Ritchie built on B to create a new language called C which inherited Ken Thompson's taste for concise syntax, and had a powerful mix of high-level functionality and the detailed features required to program an operating system. Most of the components of Unix were eventually rewritten in C.

Tuesday, June 26, 2012

CMIS Practicle Tute 2 Answers

1) A Program is required to display the square and cube of a number input by a user .




Friday, June 22, 2012

Let's program C in windows

How to program C while  in windows platform. 

There are few ways i used to do C programming, these are not the only ways , so please give a feedback if u know any other way to do C while in windows platform.

Microsoft Visual Studio.
Turbo C
Using desktop virtualization software , install UNIX.

Microsoft Visual Studio.


This is a powerful IDE ( Integrated Development Environment) which gives tools to do C , C++ , C#
.NET Frame work managed windows applications.
This is not a opensource software so we have to buy it  , but i heard some higher educational institutes and universities offers student license for this software.

You can download free trial version of Visual Studio from following links.