Bubble sort Program by amclogon.in
#include
#include
void main()
{
int a[10],n,i,j,temp;
clrscr();
printf("enter the number of ele");
scanf("%d",&n);
printf("enter the number of ele");
for (i=0;ia[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("sorted array is \n");
for (i=0;i
Menu
Conditional and Logical Operators
Conditional Operator (?:) is ternary operator (demands 3 operands), and is used in certain situations, replacing if-else condition phrases. Conditional operator’s shape is:
Condition_phrase ? phrase1 : phrase2;
If conditional_phrase is true, phrase1 is executed and whole phrase is assigned with value of this phrase1. If the conditional phrase is false, thenphrase2 is executed, and whole phrase is assigned with phrase2 value.
Example:
int a, b, c;
...
c = a > b ? a : b; // if a>b "execute" a, else b
PRE-PROCESSOR’S COMMANDS
Before source code is translated (compiled), to a language “machine” understands, pre-processor is started. Depending on pre-processor’s commands, pre-processor changes the source code, and this changed code is now ready to be translated. Changes pre-processor made are saved into temp file, and the source code file is left untouched. Some of pre-processors commands are:
#include includes other files and links it with program
#define defines symbolic constant or so called macro
#include <stdio.h>
#include "MyFunctions.h"
#define PI 3.14159
#define PROGRAM NAME "Program"
With little help of pre-processor’s "define" command, macros can be produced (they remind of function but they aren’t one).
Example:
What’s the value assigned to b variable after following commands?
int a, b;
#define MAX(x,y) ((x) > (y)) ? (x) : (y)
a = 3;
b = MAX (3, a++);
/* Pre-processor physically changes this line with following:
b = ((3) > (a++)) ? (3) : (a++);
In the end values are
a = 5, b = 4 */
a = 3;
b = MAX (a++, 3);
/* Pre-processor physically changes this line with following:
b = ((a++) > (3)) ? (a++) : (3);
In the end values are
a = 4, b = 3 (3++ > 3) ? 3++ : 3*/
LOGIC OPERATORS
Simple relation phrases can be combined into more complex ones with help of logic operators. C language includes 3 logic operators.
Pay attention to difference between logic operators and logic operators above bits!
Example:
if ((x>20) && (x<100)) printf("x is inside open interval 20-100");
if ((x<5) || (x>20)) printf("x is not inside closed interval 5-20");
if (!(x>20)) printf("x is smaller or equal to 20");
Example:
What does following program block do?
int a, b, c, d;
a = 0;
b = 4;
c = (a++) + b; /*(a++) +b 0+4 4*/
printf ("a = %d, b = %d,c = %d " , a, b, c); /* 1, 4, 4 */
d = c && b + 3 * a;
printf ("d = %d", d);
Because priority of arithmetic operators is bigger then priority of logical operators:
d = c && b + 3 * a /* this is the same as expression in next row */
d = c && (b + (3 * a))
d = 4 && (4+ (3 * 1))
d = 4 && 7
d = 1
Complex phrases are often wrongly stated because people tend to “literally rewrite” stated conditions:
Statement “if x is higher than 20 and lower than 100” (pay attention that “lower than 100” reefers to x smaller than 100), is often wrongly (literally) written:
If (x>20 && <100) instead of correct one: If (x>20 && x<100)
This produces error translation. Another thing, people often mistake putting “,” instead of operator “AND”, so previous statement is again wrongly interpreted:
if(x>20 , x<100)
which produces “logic” error (which is much harder to notice, since compiler - translator program, can’t find it and report as error) .
Phrase "x>20,x<100" only matches the statement "x<100".
OPERATORS PRIORITY AND ASSIGNMENT
Term “assignment” reefers to assigning two operators of the same priority, one after another (from left to right and sideways). Table of priorities and assignment of all previously mentioned operators:
Pay attention that all comparing operators don’t use same priority!
Example:
Write your own program which calculates results (roots) of square equation(image placeholder).
Additional Info:
First #include <stdio.h> command "includes" header file with functions and constants description which reefer to work with input/output (inputting from keyboard/printing on screen).
Second #include <math.h> command "includes" header file with description of mathematical functions and constants.
When translating the code (linking), MS Visual C++ 6.0 includes data files with implementation of mathematical functions, by definition. When translating it isn’t necessary to give any additional parameters. When working with some Unix OS programming tools, C translator doesn’t include that data file by definition, so you have to add "-lm" parameter (option) manually (when starting translation).
#include <stdio.h>
#include <math.h>
main() {
float a, b, c, x1, x2, q, d, x1r, x2r, x1i, x2i;
printf("Input coefficients of square equation a,b,c:");
scanf("%f %f %f", &a, &b, &c);
d=b*b -4.0*a*c;
if (d > 0) {
/* results are real numbers */
q = pow (d, 1./2);
x1 = (-b + q)/(2*a);
x2 = (-b - q)/(2*a);
printf ("X1=%f X2=%f\n", x1, x2);
} else if (d == 0) {
/* there’s only one result */
x1 = -b/(2*a);
printf ("X1=X2=%f\n", x1);
} else {
/* results are conjugated complex numbers */
q = pow(-d, 1./2);
x1r = -b/(2*a) ;
x2r = x1r;
x1i = q/(2*a);
x2i = -x1i;
printf ("X1 = (%f,%f)\n", x1r, x1i);
printf ("X2 = (%f,%f)\n", x2r, x2i);
}
}
#include ALL HEADER FILES
math.h
#include <math.h>, syntax at the beginning of our code, means we automatically included these (pre-defined) functions in our program:
int abs (int x); IxIlong labs (long x); double fabs (double x); double sin (double x); double cos (double x); double tan (double x); double asin (double x); double acos (double x); double atan (double x); double sinh (double x); double cosh (double x); double tanh (double x); double exp (double x); exdouble log (double x); ln xdouble log10 (double x); log x double pow (double x,double y); xydouble sqrt(double x); sqare root of xdouble fmod(double x, double y); x mod y double ceil (double x); double floor(double x);
stdlib.h
#include <stdlib.h>, syntax at the beginning of our code, means we automatically included these (pre-defined) functions in our program: void exit (int status); void randomize (void); or void srand (unsigned int seed); int rand (void);
string.h
#include <string.h>, syntax at the beginning of our code, means we automatically included these (pre-defined) functions in our program: char *strcpy(char *dest, const char *src); char *strncpy(char *dest, const char *src, size_t maxlen); char *strcat(char *dest, const char *src); size_t strlen(const char *s); char *strlwr(char *s); char *strupr(char *s); int strcmp(const char *s1, const char *s2); int strcmpi(const char *s1, const char *s2); int stricmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t maxlen); int strncmpi(const char *s1, const char *s2, size_t maxlen); int strnicmp(const char *s1, const char *s2, size_t maxlen); char *strchr(const char *s, int c); char *strstr(const char *string, const char *substring);
ctype.h
#include <ctype.h>, syntax at the beginning of our code, means we automatically included these (pre-defined) functions in our program:
int toupper(int ch); int tolower(int ch); int isdigit(int c); figure (0-9) int isalpha(int c); letter (A-Z or a-z) int isalnum(int c); letter (A-Z or a-z) or figure (0-9) int isprint(int c); character which can be printed (0x20-0x7E) int iscntrl(int c); control char (0x7F or 0x00-0x1F) int isspace(int c); empty space int islower(int c); letter (a-z) int isupper(int c); letter (A-Z)
alloc.h
#include <alloc.h>, syntax at the beginning of our code, means we automatically included these (pre-defined) functions in our program: void *malloc (size_t size); NULL error void free (void *block); void *realloc(void *block, size_t size); NULL error
Write a C Program to Print the Multiplication of Two Matrices

Statement of C Program: This Program accepts two Matrices of different or same order and Find the product of these Matrices and prints the Product Matrix:
Condition: The Column of First Matrix must be Equal to the Row of the Second Matrix.

#include<stdio.h>
#include<conio.h>
void main()
{
int Matrix A[9][9] , MatrixB[9][9] , Matrixsproduct [9][9] ;
int n , i , j , k; /* 'i' used for rows and 'j' used for columns */
int Row1 , Row2 , Column1 , Column2;
clrscr();
printf(" Enter the order of Matrix A\n");
scanf("%d * %d " , &Row1 , &Column1);
printf(" Enter the order of Matrix B\n");
scanf("%d * %d " , &Row2 , &Column2);
if(Column1 == Row2)
{
printf(" Enter the elements of Matrix A\n");
for(i=0 ; i<Row1 ; i++)
{
for(j=0 ; j<Column1 ; j++)
{
scanf("%d" , &Matrix A[i][j] );
}
}
printf(" Enter the elements of Matrix B\n");
for(i=0 ; i<Row2 ; i++)
{
for(j=0 ; j<Column2 ; j++)
{
scanf("%d" , &Matrix B[i][j] );
}
}
/* Product of two Matrices */
for(i=0 ; i<Row1 ; i++)
{
for(j=0 ; j<Column2 ; j++)
{
Matrixproduct[i][j] = 0 ;
for(k=0 ; k<Row2 ; k++)
{
Matrixproduct[i][j] = Matrixproduct[i][j] + ( Matrix A[i][k] * Matrix B[k][j] );
}
}
}
printf(" Product Matrix\n");
for(i=0 ; i< Row1 ; i++)
{
for(j=0 ;j< Column2;j++)
{
printf("%d" , Matrixproduct[i][j] );
}
printf("\n");
}
} /* End of if */
else
{
printf(" Invalid order so Multiplication not possible\n");
} /* End of main() */
Output:
Enter the order of Matrix A
2 * 2
Enter the order of MatrixB
2 * 2
Enter the elements of Matrix A
1
2
3
4
Enter the elements of Matrix B
5
6
7
8
Product Matrix
19 22
43 50
Notes on C language
Notes on C language
From: Prof Saroj KaushikCSE dept, IIT DelhiStructure of C program
#include <stdio.h>
/* Include files for input/output functions*/
#define const_name value
/* constant declaration if required */
main() /* Main function */
{ /* each declarations and statements are
separated by semi colon */
declarations
/* variables; arrays; records;
function declarations etc */
statements
}
function definitionsCompiler Directives
#include statements
– used to include the header file for
input/output stdio.h, the standard
mathematics library math.h etc.
– These files are enclosed within < >
#define
– helps in defining constant symbol. Example
#include <stdio.h>
#define i 6
main()
{ /* integer declaration */
int x, y;
/* Assignment statements */
x=7;
y= i + x;
/* output statement */
printf("%d\n", y);}Data Types
• Standard:
– int, float, char, double
• User defined datatypes:
– arrays,
– structures, pointers,
– enumerated datatype etc.Declaration
Form of Declaration:
type list of variables;
/* each separated by , and finally terminated by ; */
Examples:
• int x, y, z;
• float p, q[3][4];
array
• char name[20];
• char ch = ‘A’; /* character is enclosed within ‘ ’*/Arithmetic Expression
• An expression is a combination of variables,
constants and operators written according to the
syntax of C language.
• Every expression evaluates to a value of a
certain type that can be assigned to a variable.
Precedence in Arithmetic Operators
• An arithmetic expression without parenthesis will
be evaluated from left to right using the rules of
precedence of operators.
• There are two distinct priority levels of arithmetic
operators in C.
High priority * / %
Low priority + -Rules for evaluation of an expression
• When Parenthesis are used, the expressions
within parenthesis assume highest priority.
• Parenthesized sub expression left to right are
evaluated.
• If parenthesis are nested, the evaluation begins
with the innermost sub expression.
• The precedence rule is applied in determining
the order of application of operators in evaluating
sub expressions.
• The associability rule is applied when two or
more operators of the same precedence level
appear in the sub expression. Operator precedence and associativity
• Each operator in C has a precedence associated
with it.
• The precedence is used to determine how an
expression involving more than one operator is
evaluated.
• There are distinct levels of precedence and an
operator may belong to one of these levels.
• The operators of higher precedence are evaluated
first.
• The operators of same precedence are evaluated
from right to left or from left to right depending on
the level.
• This is known as associativity property of an
operator. Examples
x + y * z / 2 + p
x + (y * z) / 2 + p
x + ((y * z) / 2) + p
(x + ((y * z) / 2)) + p
((x + ((y * z) / 2)) + p)
x + y - z / 2 * p
(x + y) - z / 2 * p
(x + y) – (z / 2)* p
(x + y) – ((z / 2) * p)
((x + y) – ((z / 2) * p))Type conversions in expressions
Implicit type conversion
• C permits mixing of constants and variables of different
types in an expression.
• C automatically converts any intermediate values to the
proper type so that the expression can be evaluated
without loosing any significance.
• This automatic type conversion is know as implicit type
conversion
• During evaluation it adheres to very strict rules and type
conversion.
• If the operands are of different types the lower type is
automatically converted to the higher type before the
operation proceeds. The result is of higher type. Conversion rules
1. If one operand is long double, the other will be
converted to long double and result will be long
double.
2. If one operand is double, the other will be convertedto double and result will be double.
3. If one operand is float, the other will be converted to
float and result will be float.
4. If one of the operand is unsigned long int, the other
will be converted into unsigned long int and result
will be unsigned long int.
5. If one of the operand is long int, the other will be
converted to long int and the result will be long int.
6. If one operand is unsigned int the other will be
converted to unsigned int and the result will be
unsigned int. Explicit Conversion
• Many times there may arise a situation where
we want to force a type conversion in a way that
is different from automatic conversion.
• Consider for example the calculation of number
of female and male students in a class
female_students
Ratio = -------------------
male_students
• Since if female_students and male_students are
declared as integers, the decimal part will be
rounded off and its ratio will represent a wrong
figure. • This problem can be solved by converting locally
one of the variables to the floating point as
shown below.
Ratio = (float) female_students /
male_students
• The operator float converts the female_students
to floating point for the purpose of evaluation of
the expression.
• Then using the rule of automatic conversion, the
division is performed by floating point mode,
thus retaining the fractional part of the result.
• The process of such a local conversion is known
as explicit conversion or casting a value.
• The general form is (type_name) expression Arithmetic Expression
• x = x + 2 x += 2
• i = i +1 i++ or ++i
// the value of x is added with the value of i
after incrementing it by 1 then i is incremented by 1
x +(++i); x + (i++);
after decreasing it by 1 then i is decreased by 1.
x +(--i ); x = x +(i-- );Conditional Expression
exp ? exp1 : exp2
• An expression exp is evaluated and
– if the value is nonzero (or true -
represented by 1) then expression exp1
is the final value
– otherwise exp2 is the final value of
entire expression.Logical Operators
&& → AND
|| → OR
! → NOT
Relational Operators
== → equality
!= → Not equal to
< → less than
<= → less than equal to
> → greater than
>= → greater than equal to Bitwise operations
& → bitwise AND
| → bitwise inclusive OR
^ → bitwise exclusive OR
<< → left shift
>> → right shift
~ → One's complementBasic Statements
• Assignment statement
x = expression;
• Compound statement
{s1; s2;…. };
– Collection of statements, each separated
by semi colon and enclosed in brackets
• Multiple lines comments are enclosed within
/* comments */
• Single line comment can be preceded by //Conditional statements
• if (cond) statement;
• if (cond) s1 else s2;
– Here cond is a boolean condition
which can have non zero value
representing true and 0 representing
false.
– Statement may be simple or compund.For statement
for (i = m1; i <= m2; i+=m3)
{ body };
– Here m1 : initial value;
m2 : maximum value of I
m3 : increment (positive or negative)
• body Æ sequence of statements.Loop statements
• While statement
while (cond)
{ body };
• Do-while statement
do
{body }
while cond;Switch statement
switch (exp)
{ case v1 : s1 ; break;
case v2 : s2 ; break;
case vn : sn ; break;
default : s optional
}
– If the value of exp is vj then sj is executed and
switch statement is exited using break
statement.
– Execution always starts from 1 to last.Input/Output statement
/* reads single character and stores in
character variable x */
x = getchar();
/* prints single character stored in x*/
putchar(x);
/* the following functions are in standard file
named stdio.h */
scanf(control, v1, v2, ..);
printf(control, e1,e2,...);
• Control in input/output
control = "seq of format descriptor“Format descriptor
Description Meaning
%d a decimal integer
%o a octal integer
%x a hexadecimal integer
%c a single character
%s a character string
%f a decimal number (float
or double)
\n skip to new lineExamples:
• printf("%4d%7.2f\n%c\n", x, y, z)
• printf(“%c %d %f”, ch, i, x);
• scanf("%4d%8.2f \n", &x, &y)
• scanf(“%c %d %f”, &ch, &i, &x);
– Here & represents memory addressesArrays
• Single dimensional Array
– Arrays in C are defined as:
int numbers[50];
– In C Array subscripts start at 0 and end
one less than the array size whereas in
other languages like fortran, pascal it
starts from 1.
– For example, in the above case valid
subscripts range from 0 to 49.
– Elements can be accessed in the
following ways:-
numbers[2] = 100; x = numbers[2];• Multi-dimensional arrays can be
defined as follows:
int x[50][50]; // for two dimensions
• X is an array with 50 rows and 50
columns
• Elements can be accessed in the
following ways:
y=x[2][3];
• For further dimensions simply add
more [ ]:
int x[50][50][40][30]......[50];Strings
• In C, Strings are defined as arrays of
characters.
– For example, the following defines a
string of 50 characters: char name[50];
• C has no string handling facilities built
in and so the following assignments
are illegal:
char fn[10],ln[10],fulln[20];
fn= "Arnold";
ln= "Schwarznegger";
fulln= "Mr"+fn +ln;• However, there is a special library of
string handling routines <string.h>
which may be included in header file
and then various string operations can
be used.
• String is enclosed in “ “.
– Printf(“Well done”);’
• To print a string we use printf with a
special %s control character:
printf(``%s'',name);
– NOTE: We just need to give the name of the
string. • In order to allow variable length
strings the 0 character is used to
indicate the end of a string.
• So if we have a following declaration
char name[50];
• Initialization can be done at the
declaration time as follows:
char name[50] = “DAVE”;
• The contents will look like: String Handling Functions
• Include <string.h> as a header file. The
following functions are available for use.
• Concatenate two strings: strcat(s1, s2)
• Compare two strings : strcmp(s1, s2)
• Length of string : strlen(s)
• Copy one string over other: strcpy(s1, s2)
– Here contents of s2 are copied to s1
• Locating substring: strstr(s1,s2)
– Gives the position of s1 in s2Structure in C
• A structure in C is a collection of items
of different types.
• The main use of structures is to
conveniently treat such collection as a
unit.
• For example:
struct employee
{ char name[50];
char sex;
float salary;
};• The following declaration defines a
variable xyz of struct type.
struct empolyee xyz;
• Variables can also be declared
between } and ; of a struct
declaration, i.e.:
struct employee
{ char name[50];
char sex;
float salary;
} xyz;• struct variable can be pre-initialized at
declaration:
struct employee
{ char name[50];
char sex;
float salary;
} xyz = {"john", ’m’, 20000.50};
• To access a member (or field) of a
struct, C provides dot (.) operator.
• For example,
– xyz . sex ; xyz . salary; xyz . name User Defined Data Types
• Enumerated Types
– It contains a list of constants that can be
addressed in integer values.
• We can declare types as follows.
enum days {MONDAY, TUESDAY, ...,
SUNDAY};
• Variables of enumerated type are defined
as follows:
enum days week1, week2;
where week1 and week2 are variablesPossible uses of enumerated constants
• Enumerated constants can be assigned
to variable of that type
week1 = MONDAY;
• Conditional expression can be formed
If (week1 == week2) ….
if (week1 != TUESDAY) …
• Can be used in switch or for statement.• Similar to arrays, first enumerated name
has index value 0.
– So MONDAY has value 0,
– TUESDAY value1, and so on.
• We can also override the 0 start value as
follows:
enum months {JAN = 1, FEB, MAR, ..., DEC};
– Here it is implied that FEB = 2 and so on
enum colors {RED, BLUE, GREEN=5, WHITE,
PINK=9};
– Here RED=1, BLUE=2, GREEN=5, WHITE=6,
PINK=9#include <stdio.h>main()
{
enum Color {RED=5, YELLOW, GREEN=4,
BLUE};
printf("RED = %d\n", RED);
printf("YELLOW = %d\n", YELLOW);
printf("GREEN = %d\n", GREEN);
printf("BLUE = %d\n", BLUE);
}
Output:
RED = 5
YELLOW = 6
GREEN = 4
BLUE = 5 Type Definitions
• We can give a name to enum colors as COLOR
by using typedef as follows:
typedef enum colors COLOR;
COLOR x, y, z;
x = RED;
y = BLUE;
• Now, every time the compiler sees COLOR, it'll
know that you mean enum colors.
• We can also define user named data type for
even existing primitive types:
typedef int integer;
typedef bool boolean; • typedef can also be used with structures to
creates a new type.
• Example:
typedef struct employee
{ char name[50];
char sex;
float salary;
} emp_type xyz ={"john", ’m’, 2000.50};
• emp_type is new data type of struct employee
type and can be initialized as usual:
• It can be now used for declaring variables similar
to primitive data types are used.• Examples:
emp_type x, y, z
– Here x, y and z are variables of type
emp_type which are structures themselves.
emp_type emp[100];
– Here emp is an array of 100 elements with
each element of type emp_type.
• Both declarations given below are same.
struct employee x, y, z;
emp_type x, y, z;Unions
• A union is an object similar to a structure except
that all of its members start at the same location
in memory.
• A union variable can represent the value of only
one of its members at a time.
• So an union is a variable which may hold (at
different times) objects of different sizes and
types.
• Example:
union number
{ short shortnumber;
long longnumber;
double floatnumber;
} anumber• It defines a union called number and an
instance of it called anumber.
• Members can be accessed in the following
way:
printf("%d\n",anumber.longnumber);
• This clearly displays the value of
longnumber.
• When C compiler is allocating memory for
unions, it will always reserve enough room
for the largest member
– (in the above example this is 8 bytes for the
double). • Example:
union u_t
{ char a;
short b;
int c;
};
union u_t x;
x.a = ‘B’;
printf("%c\n", x.a);
Output is: B • In order that the program can keep track of
the type of union variable being used, it is
embedded in a structure and a variable
which flags the union type.
• For example:
typedef struct { int maxpassengers; } jet;
typedef struct { int liftcapacity;} helicopter;
typedef struct { int maxpayload; } cargoplane;
typedef union
{ jet j; helicopter h; cargoplane c; } aircraft;
typedef struct
{ aircrafttype kind; int speed;
aircraft description; } an_aircraft;Function
• C provides functions which are again
similar in most languages.
• One difference is that C regards main()
as a function.
• The form of a C function is as follows:
type fun_name(parameter along with type)
{ local declarations;
body;
}
• type : is the type of value returned by the
function and can be basic type or user
defined. • return statement is used in the body of a
function to pass the result back to the
calling program.
• Example: Write function to find the
average of two integers:
float findaverage(float a, float b)
{ float average;
average=(a+b)/2;
return(average);
}
• We would call the function as follows:
result=findaverage(6,23);#include <stdio.h>
main()
{ int i, x;
int power (x, n); function declaration
for (i =0; i < 10; ++i)
{ x = power(2, i);
printf("%d%d\n", i, x); }
}
int power(int x, n) function definition
{ int i, p;
p = 1;
for (i =1; i <=n; i++) p = p*x;
return (p); }void functions
• The void function provides a way of not
returning any value through function name
• Here return statement is not used:
void squares()
{ int i;
for (i=1;i<10;i++);
printf("%d\n",i*i);
}
• In the main function we call it as follows:
main( )
{ squares( ); }Parameter Passing
• Default parameter passing is by value.
– The values of actual parameters are copied in
formal parameters.
– The change is not visible in the calling program.
main()
{ int i, x, y,s;
int sqsum (a,b);
x = 5; y = 7;
s = sqsum(x,y);
printf("%d%d%d\n“
, x,y,s); }
int sqsum(int a, b)
{ int sum;
a=a*a; b= b*b;
sum = a + b;
return(sum);
}• Another mechanism is to call by reference.
• It can be achieved by passing addresses of
actual parameters to formal parameters.
• For such case variables in formal parameter list
are represented as pointers.
• For writing functions where call by reference is
to be achieved then Void type is used.
• In this case the function will not returning any
value.
• Note that return statement is not.
• Changes to formal parameters will be visible in
actual parameters of calling program.Example:
void swap (int *p,*q) call by reference
{ int t;
t = *p;
*p = *q;
*q = t;
}
• Corresponding call statement
x = 4;
y = 5;
swap(&x, &y); addresses are passedFunctions and Arrays
• Single dimensional arrays can be passed to
functions as follows:
float findaverage(int size,float list[])
{ int i;
float sum=0.0;
for (i=0; i<size; i++) sum+=list[i];
return(sum/size);
}
• Here the declaration float list[] tells C compiler
that list is an array of float type.
• It should be noted that dimension of array is not
specified when it is a parameter of a function. • Multi-dimensional arrays can be passed to
functions as follows:
void printtable(int xsize,int ysize, float table[][5])
{ int x,y;
for (x=0; x<xsize; x++)
{ for (y=0; y<ysize;y++)
printf(“\t%f”,table[x][y]);
printf(“\n”);
}
}
• Here float table[][5] tells C compiler that table is
an array of dimension N X 5 of float.
• Note we must specify the second (and
subsequent) dimension of the array BUT not the
first dimension.
C-LANGUAGE NOTES
C-LANGUAGE NOTES
Some words about Computer Programming languages
Naturally a language is the source of communication between two persons, and also between person to machine like computer. The languages we can use to communicatewith the computer are known as Computer programming languages.Generally there are two major types of languages are available are as follows:1.
Low level languages
2.The set of commands available in low level is complex and not easy tounderstandable. In this category " Assembly " and " machine codes " areavailable. Assembly programs are faster than other high-level language programs.3.High level languages
The set of commands available in high level language is very simple and easy
to understandable.High level languages are further divided into two major categories.
1.Procedure Oriented language
2.In this category we are able to create our project or programs using proceduralapproach means in this type we can able to divide our big project/program intosmall subroutines or procedures. After making procedures we can able to call a‘procedure’ one or more places.The lists of procedural languages are as follows:C languageC++ (Object Oriented)Java (Objected Oriented)Smalltalk (Objected Oriented)Pascal language3.Non-Procedural Languages:
This category also known as ‘Problem Orientedlanguages’. In this type of languages we can able to make program only atspecific range like database. The followings are the examples of Non procedural languages
1.SQL (Structured Query Language)
2.SNOBOL (String processor)
C LanguageHistory
- Developed at Bell Laboratories. first standard version release in 1972.
Developed by Dennis Richee.
Before c a Programming language is very popular in those days the name of thelanguage is B-Language so the developers decided the name of ‘C’ language because C is next to B.
The Integrated Development Environment (IDE):
Turbo c features as integrated Development environment, or IDE,. It is also referred to asthe programmer’s platform.) in IDE you can able to write/save/open your programs or code, compile using short cut keys, and also perform code debugging very easily.
IDE
Common Short cut Keys DescriptionF2 press to Save current work
F3 press to open an existing file
ALT-F3 press to close current
ALT-F9 press to compile only
ALT-F5 press to view the desired output of the program.
CTRL-F9 press to compile+run
ALT-X or ALT-F-X press to exit from TC IDE
C Programs Skeleton (General) <Preprocessor Directives (some time necessary)>
<Macros Definition (optional)>
<function declaration>
< Global Variable (on your demand)>
main () (Necessary)
{ statements }
< function definition>
{ }
- Remember Some common rules for writing C program
Use all commands or statements in lower or small case.
- After completion of a statement excluding main() or loops must insert
(semicolon) as a statement terminator.
Don’t use/declare identifier or variable name same as statement name suppose
int include; this is a wrong statement because include has a special meaning in thelanguage.
Header Files or Preprocessor Directives contains references or links of library functions. That is built-in in the C language.
Suppose if you want to use a function clrscr() ; in the main function so must bedeclared on top # include <conio.h> other wise you could have an prototype error.
Some header files are as followsStdio.h
Conio.h
Dos.h
String.h
Stdlib.h
And many more header files are available in C…
void main(void)
Every C programs consists of one or more functions. No matter how manyfunctions there are in a C program , main is the one to which control is passedfrom the operating system when the program is run ; it is the first function
executed. The word "void" preceding "main" specifies that the function main()will not return a value. The second "void," in parenthesis , specifies that thefunction takes no arguments.
Studying effectively
12 Steps for Effective Studying
Studying effectively is a process, not an event. The process leads to success.
Studying effectively is a process, not an event. The process leads to success.
- Plan a definite time for studying every day. This will discourage procrastination and prevent a pile-up of work. Studying every day, even for a short period of time, keeps you from falling behind. Prioritize your list and begin completing the most difficult material first.
- Know the purpose of and understand each assignment before leaving class. If you understand what to do and how to do it, your study time will be shortened. Keep a record of all assignments in a special section of your notebook or on a separate calendar.
- Predicting the amount of time you need for each assignment causes you to work smarter as well as harder and more productively. By keeping track of the actual amount of time you spend on your assignments, you are more likely to concentrate and less likely to become bored.
- Time yourself to see how long it takes you to read five pages of your textbook. This will help you determine the amount of time needed to complete a reading assignment. Because a textbook is loaded with information, you may have to read some sections more than once. Even instructors have to reread material. Allow time for reflecting and thinking about what you have read.
- Reading assignments are usually completed and due prior to the instructor lecturing on the material. Take a little time before class to review the material so you are ready to participate in class discussions and are prepared for any quizzes.
- Adopt a textbook reading strategy, (like SQ4R), or whatever works for you. Pay attention to charts, diagrams, and special "boxed text" areas. They are definite aids to understanding the material.
- Every time you study, spend at least ten minutes reviewing the material from your previous study session. These "refresher shots" are part of the secret for long-term memory retention. This habit of frequent review also results in less time needed for studying prior to a major exam.
Know the percentages! We retain:
- 10% of what we read
- 20% of what you hear
- 30% of what we see
- 50% of what we see and hear
- 70% of what we talk about with others
- 80% of what we experience personally
- 95% of what we teach to others
- Study during the day. You are probably less efficient at night.
- Study for 30 to 40 minutes and then take a 5-minute break, or if your concentration and discipline will allow, study for 50 minutes and take a 10-minute break. Get up walk around, stretch, drink some water, or eat a light snack. Taking regular breaks refreshes your mind so you can concentrate better, finish faster, and retain more.
- If you do study at night set a "stopping time" for yourself. This "time frame" will encourage hard work in anticipation of the clock going off. You may even set a goal for yourself to complete an assignment before the time limit. This increased impetus may help you to concentrate.
- Do not cram the night before a test. Distribute your review in half-hour segments over a period of days. If you do not adopt a structured study schedule, you will not master required course material and you will set yourself up to fail.
- Learning is accumulative. New ideas must be incorporated with previous material from lectures, readings, and any other assignments such as labs. You have to continuously make the connection in your mind from new material to previously learned material and/or experiences. Putting it all together is easier if you schedule time daily to read, to think, to write, to reflect, and to review.
Improved learning is the natural result of this 12 Step approach to studying and effectively using your time.
Not having enough time to study means you lack organization, so by managing your time, you have control over your life and a chance to do more of what you want to do.
Fundamental concept of problem solving
![]() |
Firstly we will discuss here Fundamental concept of Problem solving. Then This chapter gives the viewer/reader an overview of C language and tells about the structure of C program and various component of a C program. C language allows us to create custom data types. Problems are the undesirable situations that prevent any software from fully achieving its objectives. When we wish to transform the existing situation into a more desired one, problem occurs, and a need for solving the problem arises. Defining a problem clearly in terms of goals and objectives helps largely in problem solving. There are three related terms that need to be well understood to successfully solve the problem: 1. Mission: It is the broad statement of the purpose of the organization. 2. Goals: It is the general statement of what is to be accomplished. 3. Objectives: It is the statement of measurable results to be achieved in a specified time frame. | |
Problem solving strategiesThe most popular method of problem solving is to divide and conquer. This means that the problem has to be divided into smaller problems, each of which must be solved to get the complete solution. For instance, if it is required to find the second smallest element in an array, the problem could be divided into two parts viz. Arranging the elements in the array in ascending or descending order and then getting the second smallest element form the sorted array. This strategy is called divide and conquer. If you want to find the sum of the digits in a number, it can be divided into 3 parts: 1. Finding modulus of 10 i.e. finding the remainder when the number is divided by 10. 2. Adding the remainder to a sum whose initial value is zero. 3. Dividing the number by 10 and then repeating the process from (1) again till the quotient is zero. |
Subscribe to:
Posts (Atom)