Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,151,326 members, 7,811,961 topics. Date: Monday, 29 April 2024 at 02:04 AM

Lets Learn C - Programming (4) - Nairaland

Nairaland Forum / Science/Technology / Programming / Lets Learn C (9201 Views)

Is It Possible To Learn C++ In A Year? / Learn C++ Programming Language In Few Days / Lets Learn Programming From Bignners To Expert Through Tutorials (2) (3) (4)

(1) (2) (3) (4) (5) (Reply) (Go Down)

Re: Lets Learn C by stack1(m): 9:01am On Jul 30, 2016
lets see some basic examples


//this are incomplete code examples try-out completing them and make sure they run

ex 1
int index = 1;
while (index < 5)
printf("Good morning!\n" );

ex 2
index = 1;
while (--index < 5)
printf("Good morning!\n" );



in the first example we declare a variable index and set its value to 1, then the control-expression index < 5 is evaluated, so far as this expression returns a positive/truthful result the loops body i.e. the printf statement is executed.

in the second example the variables are the same the only difference is the control-expression --index < 5, this statement uses a pre-decrement to decrease the value of the variable index by one each time the loop is run, however this example prints a never ending line
of Good morning's, this is termed infinite looping and is usually an error condition, before i explain while the loop runs infinitely can any one take a stab at the explanation smiley

And also the second example shows a crucial point, whenever you craft loops, make sure there's some condition that would cause the loop to terminate and not just run endlessly, except you actually wanted it to (this could be valid ins some kind of programs)
Re: Lets Learn C by stack1(m): 9:06am On Jul 30, 2016
while and for loops are termed entry condition loops, this is due to the fact that their condition(s) for looping is checked each time before the loop is executed, the examples seen so far are quite basic, as we proceed we would encounter more complex (and sometime strange) usages of loops.

so lets see some more while loops
Re: Lets Learn C by stack1(m): 9:55am On Jul 30, 2016
// Program to find factorial of a number
// For a positive integer n, factorial = 1*2*3...n

Ok, not too get too mathematical (no be say me sef sabi math like dat), but this example calculates factorial, in summary lets say we have a number 5 the factorial would simply be 1*2*3*4*5, and if w have a number 55 the factorial would be 1*2*3*4*5*....55, ok they are other better ways to calculate factorials and we would still revisit more proper factorial programs later on




#include <stdio.h>
int main()
{
int number = 8; //we would calculate the factorial of 8
int factorial = 1 ;

// loop terminates when number is less than or equal to 0
while (number > 0)
{
factorial = factorial * number;
--number;
}

printf("Factorial= %d", factorial);

getchar();
return 0;
}




This example calculates the factorial of 8, the loop's control-condition simply checks to make sure the value of the number variable is greater than 0 (initially its 8 ).
In the body of the loop we calculate the factorial as thus

on the first run factorial is 1 and number is 8

so
  factorial = factorial * number;  
, evaluates as 1 = 1* 8 which is still 8 and so the number 8 is stored in the factorial
variable, i.e. factorial = 8

The next statement --number, decreases the value of number by one making it 7

On the next run of the loop the control-condition (number > 0) still holds true as number is 7 and thus > 0
so the loop is executed again and
-
  factorial = factorial * number;  
, evaluates as 8 = 8* 7, given 56, and this is stored in factorial.
The statement --number, decreases the value of number by one (again) making it 6.

This process runs again and again updating the factorial variable and decreasing the number on each successfull run until
the condition (number > 0) isn't true any more and the looping stops.

The final value stored in variable factorial is our answer and is printed to the output
Re: Lets Learn C by stack1(m): 10:03am On Jul 30, 2016
The while and for loops as stated earlier are entry-controlled loops as their conditions for looping is checked once before each run, however there exists another similar looping construct do..while which runs at least once before its looping condition is checked and it is termed an exit-controlled loop

[size=16pt]do while{}[/size]

The do while{} loop executes its statement(s) once before checking its loop-condition, if the loop-condition then still holds true it executes again and again till the condition is no longer true

Form of do-while loop –


do
{
//C- statements

}while(condition test);

Re: Lets Learn C by stack1(m): 10:15am On Jul 30, 2016


int main()
{
int j=0
do
{
printf("Value of variable j is: %d", j);
j++;
}while (j <= 8 );

getchar();
return 0;
}



Output:

Value of variable j is: 0
Value of variable j is: 1
Value of variable j is: 2
Value of variable j is: 3
Value of variable j is: 4
Value of variable j is: 5
Value of variable j is: 6
Value of variable j is: 7
Value of variable j is: 8
Value of variable j is: 9


Ok so what is happening here, we have an integer variable j that is initialized to zero, in the do while loop, the statement which prints the value of our integer variable is printed first (in the do section), then the variable is incremented. all this happens before the looping condition
 j <= 8
is checked

This loop continues to run (increasing the value of the integer variable j on each run till the test-condition fails, that's basically the story of the do-while loop
Re: Lets Learn C by stack1(m): 10:20am On Jul 30, 2016
//carefully study the following code, would discuss it a bit later, its nothing complex just a lumped up example of what we have been looking at



#include <stdio.h>
int main(void)
{
int n, m;
n = 30;

while (++n <= 33)
printf("%d|",n );
n = 30;

do{
printf("%d|",n);
}
while (++n <= 33);

printf("\n***\n" );

for (n = 1; n*n < 200; n += 4)
printf("%d\n", n);

printf("\n***\n" );

for (n = 2, m = 6; n < m; n *= 2, m+= 2){
printf("%d %d\n", n, m);
}

printf("\n***\n" );

for (n = 5; n > 0; n--)
{
for (m = 0; m <= n; m++)
printf("=" );
printf("\n" );
}

getchar();
return 0;
}



Please make sure you type and run this code, and yeah i'm sure they'll be questions and some attacks for this grin wink
Re: Lets Learn C by stack1(m): 1:29am On Aug 01, 2016
very tired tonight so i'll just run down a few C operators and their usage, most would be understood from their mathematical usage anyway,
then gain
forgive me I'm so stressed up right now, lemme leave you with this page that rounds up the C operators pretty well
http://www.tutorialspoint.com/cprogramming/c_operators.htm

Their usage would still be explained further in examples to come..

..Serious sleep-mode things embarassed
Re: Lets Learn C by stack1(m): 1:32am On Aug 01, 2016
and also make una ask questions oo..
Re: Lets Learn C by romme2u: 6:08am On Aug 02, 2016
stack1:
and also make una ask questions oo..

hey bro nice job

my problems are in union, bit manipulations and dynamic structures.

maybe when u get there we will tangle.
Re: Lets Learn C by stack1(m): 7:46am On Aug 02, 2016
thanks @romme2u, no p, looking forward to tangle
Re: Lets Learn C by shobam1410(m): 7:38am On Aug 03, 2016
➡ *COMPUTER PROGRAMMING*


1. Hello World! Computer Programming for Kids and Other Beginners by Warren Sande,Carter Sande
2. The Specification of Computer Programs (International Computer Science Series) by Thomas S. E. Maibaum
3. Writing Your First Computer Program (CliffsNotes) by Allen Wyatt
4. Agent-Oriented Software Engineering V: (Lecture Notes in Computer ... Programming and Software Engineering) (v. 5) by James Odell,Paolo Giorgini
5. Turbulence Models and Their Application:Efficient Numerical Methods With Computer Programs by Tuncer Cebeci
6. The Art of Computer Programming, Volume 1: Fundamental Algorithms (3rd Edition) by Donald E. Knuth
7. Writing Your First Computer Program by Allen Wyatt
8. Learn to Program Using Python: A Tutorial for Hobbyists, Self-Starters, and All Who Want to Learn the Art of Computer Programming by Alan Gauld
9. Concepts, Techniques, and Models of Computer Programming by Peter Van Roy,Seif Haridi
10. Structure and Interpretation of Computer Programs - 2nd Edition (MIT Electrical Engineering and Computer Science) by Harold Abelson
11. The Art of Computer Programming, Volume 2: Seminumerical Algorithms (3rdEdition) by Donald E. Knuth
12. Automatic Quantum Computer Programming: A Genetic Programming Approach (Genetic Programming) by Lee
Spector
13. Programming Languages and Systems: 8th Asian Symposium, APLAS 2010, Shanghai, China, November 28 - December 1, 2010 Proceedings (Lecture Notes in Computer ... Programming and Software Engineering) by Kazunori Ueda
14. Formal Methods for Quantitative Aspects of Programming Languages: 10th International School on Formal Methods for the Design of Computer, ... Programming and Software Engineering)
15. The mystery of knots: Computer programming for knot tabulation by Aneziris C.N.
16. The Specification of Computer Programs by Maibaum T.S.E.
17. Computer Programming for Teens by Mary E. Farrell
18. The Art of Computer Programming, Volume 1, Fascicle 1: MMIX -- A RISC Computer for the New Millennium by Donald E. Knuth
19. The Art of Computer Programming, Volume 4, Fascicle 2: Generating All Tuples and Permutations by Donald E. Knuth
20. 101 Apple Computer Programming Tips and Tricks by Fred White
21. The Art of Computer Programming, Volume 4A: Combinatorial Algorithms, Part 1 by Donald E. Knuth
22. Concepts and techniques of computer programming by Peter Van Roy
23. Career Development Programs: Preparation for Lifelong Career Decision Making by Wendy Patton
24. A.I.M.: The Powerful 10-Step Personal and career Success Program by Jim Carlisle,Alex Gill
25. Computers and Programming (Ferguson Career Launcher) by Lisa McCoy
26. Modern C++ design: generic programming and design patterns applied by Andrei Alexandrescu
27.Principles of constraint programming by Krzysztof Apt
28. Programming with POSIX threads by David R. Butenhof
29. An Introduction to Object-Oriented Programming in C++: with Applications in Computer Graphics by Graham M. Seed BEng,MPhil,PhD,MIAP (auth.)
30. Interdisciplinary Computing in Java Programming by Sun-Chong Wang
31. 101 Atari computer programming tips & tricks by Alan North
32. Advanced computer programming : a casestudy of a classroom assembly program by F J Corbató,J W Poduska
33. Great ideas in computer science with Java by Alan W Biermann

GOOD NEWS!!!

The Person you will be in 5 years from today is based on the books you read and the people you surround yourself with today.
LEADERS are always READERS.

You can now convert your mobile phones/tablets to a MOBILE LEARNING CENTRE.
You can receive ANY BOOK by ANY AUTHOR in ANY FIELD of LEARNING/LIFE in e-format into your mobile device in minutes ANYWHERE YOU ARE IN THE WORLD from our ONLINE BOOKSTORE.

A OUR RICH STOCK offers you e-books by ANY AUTHOR you think of in the following categories.

➡Education( Early years to Tertiary)
➡Marriage/Relationship
➡Motivational
➡Finance
➡Politics
➡Health
➡Dressmaking& Photography
➡Business & Management
➡Sales & Marketing
➡Customer Service/Relations
➡Parenting
➡Engineering
➡Accounting
➡Baking/Confectionery
➡Public Speaking
➡Creative Writing
➡Novels etc
➡ We mean ANYTHING!

All your ordered ebooks will be sent directly into your Phones/Tablets in minutes ANYWHERE you are in the World.

WHAT DOES IT COST ME?
The good news is that your first ordered book is FREE and any other costs from #300 per book ( payment thru bank transfer).

Connect with us on whatsapp with 07051505626 or Call 08189300870

TRY US TODAY AND YOU WILL BE SHOCKED WITH THE UNBELIEVABLE AUTHORS/TITLES OF BOOKS WE'VE GOT IN OUR OVER TWO HUNDRED THOUSAND eBOOK COLLECTION.
Re: Lets Learn C by stack1(m): 9:49am On Aug 03, 2016
shobam1410:
➡ *COMPUTER PROGRAMMING*


1. Hello World! Computer Programming for Kids and Other Beginners by Warren Sande,Carter Sande
2. The Specification of Computer Programs (International Computer Science Series) by Thomas S. E. Maibaum
3. Writing Your First Computer Program (CliffsNotes) by Allen Wyatt
4. Agent-Oriented Software Engineering V: (Lecture Notes in Computer ... Programming and Software Engineering) (v. 5) by James Odell,Paolo Giorgini
5. Turbulence Models and Their Application:Efficient Numerical Methods With Computer Programs by Tuncer Cebeci
6. The Art of Computer Programming, Volume 1: Fundamental Algorithms (3rd Edition) by Donald E. Knuth
7. Writing Your First Computer Program by Allen Wyatt
8. Learn to Program Using Python: A Tutorial for Hobbyists, Self-Starters, and All Who Want to Learn the Art of Computer Programming by Alan Gauld
9. Concepts, Techniques, and Models of Computer Programming by Peter Van Roy,Seif Haridi
10. Structure and Interpretation of Computer Programs - 2nd Edition (MIT Electrical Engineering and Computer Science) by Harold Abelson
11. The Art of Computer Programming, Volume 2: Seminumerical Algorithms (3rdEdition) by Donald E. Knuth
12. Automatic Quantum Computer Programming: A Genetic Programming Approach (Genetic Programming) by Lee
Spector
13. Programming Languages and Systems: 8th Asian Symposium, APLAS 2010, Shanghai, China, November 28 - December 1, 2010 Proceedings (Lecture Notes in Computer ... Programming and Software Engineering) by Kazunori Ueda
14. Formal Methods for Quantitative Aspects of Programming Languages: 10th International School on Formal Methods for the Design of Computer, ... Programming and Software Engineering)
15. The mystery of knots: Computer programming for knot tabulation by Aneziris C.N.
16. The Specification of Computer Programs by Maibaum T.S.E.
17. Computer Programming for Teens by Mary E. Farrell
18. The Art of Computer Programming, Volume 1, Fascicle 1: MMIX -- A RISC Computer for the New Millennium by Donald E. Knuth
19. The Art of Computer Programming, Volume 4, Fascicle 2: Generating All Tuples and Permutations by Donald E. Knuth
20. 101 Apple Computer Programming Tips and Tricks by Fred White
21. The Art of Computer Programming, Volume 4A: Combinatorial Algorithms, Part 1 by Donald E. Knuth
22. Concepts and techniques of computer programming by Peter Van Roy
23. Career Development Programs: Preparation for Lifelong Career Decision Making by Wendy Patton
24. A.I.M.: The Powerful 10-Step Personal and career Success Program by Jim Carlisle,Alex Gill
25. Computers and Programming (Ferguson Career Launcher) by Lisa McCoy
26. Modern C++ design: generic programming and design patterns applied by Andrei Alexandrescu
27.Principles of constraint programming by Krzysztof Apt
28. Programming with POSIX threads by David R. Butenhof
29. An Introduction to Object-Oriented Programming in C++: with Applications in Computer Graphics by Graham M. Seed BEng,MPhil,PhD,MIAP (auth.)
30. Interdisciplinary Computing in Java Programming by Sun-Chong Wang
31. 101 Atari computer programming tips & tricks by Alan North
32. Advanced computer programming : a casestudy of a classroom assembly program by F J Corbató,J W Poduska
33. Great ideas in computer science with Java by Alan W Biermann

GOOD NEWS!!!

The Person you will be in 5 years from today is based on the books you read and the people you surround yourself with today.
LEADERS are always READERS.

You can now convert your mobile phones/tablets to a MOBILE LEARNING CENTRE.
You can receive ANY BOOK by ANY AUTHOR in ANY FIELD of LEARNING/LIFE in e-format into your mobile device in minutes ANYWHERE YOU ARE IN THE WORLD from our ONLINE BOOKSTORE.

A OUR RICH STOCK offers you e-books by ANY AUTHOR you think of in the following categories.

➡Education( Early years to Tertiary)
➡Marriage/Relationship
➡Motivational
➡Finance
➡Politics
➡Health
➡Dressmaking& Photography
➡Business & Management
➡Sales & Marketing
➡Customer Service/Relations
➡Parenting
➡Engineering
➡Accounting
➡Baking/Confectionery
➡Public Speaking
➡Creative Writing
➡Novels etc
➡ We mean ANYTHING!

All your ordered ebooks will be sent directly into your Phones/Tablets in minutes ANYWHERE you are in the World.

WHAT DOES IT COST ME?
The good news is that your first ordered book is FREE and any other costs from #300 per book ( payment thru bank transfer).

Connect with us on whatsapp with 07051505626 or Call 08189300870

TRY US TODAY AND YOU WILL BE SHOCKED WITH THE UNBELIEVABLE AUTHORS/TITLES OF BOOKS WE'VE GOT IN OUR OVER TWO HUNDRED THOUSAND eBOOK COLLECTION.


while i must agree this is really a nice collection of books (i actually have a few of them) this thread isn't for advertisements, if you are going to post please post on relevant topics being discussed, thank you
Re: Lets Learn C by stack1(m): 12:10pm On Aug 03, 2016
The C language includes a wide variety of powerful and flexible control statements, we have already seen the "loop-control" statements, now we look at the decision making statements. The most useful of these are described in the following.

The if-else statement is used to carry out a logical test and then take one of two possible actions, depending on whether the outcome of the test is true or false. The else portion of the statement is optional. Thus, the simplest possible if-else statement takes the form::

if (expression) statement

The expression must be placed in parenthesis, as shown. In this form, the statement will only be executed if the expression has a nonzero value i.e if expression if true, If the expression has a value of zero / if expression is false) then the statement will be ignored. The statement can be either simple or compound.



Examples:


if (expression_is_non_zero) {
do_something();

} else {
do_something_else();
}



An else statement matches the nearest previous if statement in the same scope or block:

The else in this code:

if (a == b)
if (b > c)
do_this();
else
do_that();

matches the if (b > c), even if it was written as:

if (a == b)
if (b > c)
do_this();
else
do_that();

Re: Lets Learn C by stack1(m): 12:42pm On Aug 03, 2016
The ternary operator ( ?: ) is another powerful and useful conditional expression used in C and C++. It's effects are similar to the if statement but with some major advantages.

The basic syntax of using the ternary operator is thus:
(condition) ? (if_true ) : (if_false )

which is basically the same as


if (condition)
if_true;
else
if_false;




Therefore if "condition" is true, the second expression is executed ("if_true" ), if not, the third is executed ("if_false" ).

as an example, assuming we have two int variables, and we wanted to compare them


if (a > b) {
largest = a;
} else if (b > a) {
largest = b;
} else /* a == b */ {
printf("a and b are equal" );
}


This could be re-written as

largest = (a > b) ? a : b ;



A notable difference here is that the result of a Tenary expression can be stored or assigned to a variable, while an if-else statement doesn't return a result, though the assignment can be done within its execution block/scope
Re: Lets Learn C by stack1(m): 2:01pm On Aug 07, 2016
Lets look at some more Loop/Control structures examples

The program below simply counts the number of lines in an input



/** line counting**/

#include <stdio.h>
int main()
{
int c, nl;
while ((c = getchar()) != EOF){

if(c == '\n') ++nl; //increase count on each new line

}
printf ("%d", nl);
getchar();
}



Here's how the program works
1. In the main function we declare two int variables c and nl

2.In the while loop we read in characters into variable c until we detect the END_OF_FILE character

3. now in the body of the while loop we check for the newline character \n and whenever it is detected it means the user entered text on a new line so we increment the nl variable ( variable nl here is our number-of-lines counter)

When entering input for this program enter as many number of lines of text as you wish then press Crtl+Z, this would send the EOF character to your program and the loop would exit

The next line containing the function printf, prints out the value of the[b] nl[/b] variable, which shows the number of lines in our input
Re: Lets Learn C by stack1(m): 6:07pm On Aug 08, 2016
nawa o, i was trying to post afew more tutorials yesterday when i got banned by the antispam bot for a full 24hrs, biko antispam bot wetin i do u
Re: Lets Learn C by Nobody: 6:32pm On Aug 08, 2016
That was what frustrated many people including me from posting tutorials on nairaland. I think the special characters we use in programming and hyperlinks somehow trigger this automatic ban.
Re: Lets Learn C by stack1(m): 7:03pm On Aug 08, 2016
dhtml18:
That was what frustrated many people including me from posting tutorials on nairaland. I think the special characters we use in programming and hyperlinks somehow trigger this automatic ban.

toh, taught as much, hope it doesn't occur frequently, don't know how much more of such frustrations i can take, but by the way sef i usually put program text between d code tag.., it is well sha
Re: Lets Learn C by stack1(m): 11:12pm On Aug 08, 2016
This next program remove's extra spaces between text, so to try it enter any amount of text with lot's of space between the text's and the program would detect and truncate such space(s) to just one space



int main(void)
{
int c,last_char_is_blank;

last_char_is_blank = 0;

while((c=getchar())!=EOF)
{

if(c==32) //a space was entered (ASCII) could have as well used c=' '
{
if(last_char_is_blank == 0) //flag hasn't been set, so the previous character wasn't a space
{

putchar(c);
last_char_is_blank=1; //set last char was a space flag
}
}
else
{
putchar(c);

last_char_is_blank=0; //regular char input, reset this
}
}

getchar();
return 0;
}



Now lets go through it.
Note that we start by declaring two integer variables in the main function c and last_char_is_blank,
we would use the last_char_is_blank variable, as a control variable to detect multiple spaces,

We read input characters into the variable c in the while loop

Next we have the if statement if(c==32) The number 32 is the ASCII value for SPACE and we could have equally done if(c== ' ') , and achieved the same result, if the character entered is a space, the if block is executed this shows that you can use any ASCII decimal value instead of an Actual character.

The next line if(last_char_is_blank == 0) checks to see if the control variable has not been set the variable last_char_is_blank is initially assigned a value of zero so this test would pass and the following statements

  putchar(c);
last_char_is_blank=1; //set last char was a space flag


would be executed, the first statement outputs the space character ( remember we're still inside the if statement that detected a space)
then the next statement sets our control variable last_char_is_blank to one

On the next run of the loop if the imputed character is again a space, the if statement detects it, and so when the check if(last_char_is_blank == 0) is executed, the test fails since last_char_is_blank would now set to 1 (provided the previous character was a space)

If the imputed character is however not a SPACE character, the first if statement fails and the else block is executed, so the non-space character gets printed. and the last_char_is_blank variable is reset to ZERO

This way multiple spaces within the text is prevented. Enter the code and run-it to fully understand
Re: Lets Learn C by stack1(m): 11:17pm On Aug 08, 2016
This program count the characters, lines, and words in an input


#include<stdio.h>

#define IN_WORD 1 //define a constant IN_WORD to monitor when we are within a word
#define OUT_WORD 2 //define a constant OUT_WORD to monitor when we are outside a word

int main(void)
{
int c, nc, nw, nl, state; // nc = number of character, nw = number of words, nl = number of lines

state = OUT_WORD;//we are initially not in a word

nc = nw = nl =0; //default all these to ZERO

while((c=getchar())!=EOF)
{
++nc; //keep increasing the number of character's as far we are reading input

if(c == 10) ++nl; // 10 is the ASCII value for new line/line feed. so increase new line counter if a line is detected

//ASCII values for space, new line and tab
if(c == 32 || c == 10 || c == 9)
state = OUT_WORD;

else if(state == OUT_WORD){//if none of the above SPACE characters matched, check if were previously outside a word
state = IN_WORD; //we must now be in a word then

++nw; //so increase the new word counter
}

}
printf("number of lines is : %d\n number of words is : %d\n number of characters is : %d\n", nl , nw, nc); //print the values for number of lines, words and characters

getchar();
return 0;
}


The code is pretty self explanatory as it has been heavily commented so try to study it
A new construct #define seen in the code is a pre-processor directive (similar to #include)
#define is used to introduce constants (values not expected to change) into the program.

As an example if you where writing a program calculating radius instead of creating an integer variable for PI like int PI = 3.142
its more appropriate to do
#define PI 3.142...,
so anywhere you use PI, the value 3.142 would be substituted
Re: Lets Learn C by stack1(m): 11:33pm On Aug 08, 2016
PRINT HISTOGRAM OF THE LENGTH OF EACH WORD.

This next program extends the last one, we detect wen we are in a word and print a horizontal Histogram representing the length of each word

//print histogram of length of each word


#include<stdio.h>
//print histogram of length of each word using | to represents characters
#define IN_WORD 1
#define OUT_WORD 2

int main(void)
{
int c, state;

state = OUT_WORD;//initially not in a word


while((c=getchar())!=EOF)
{

if(c == 32 || c == '\t') //space, tabs
{

//see if current state is in a word
if(state == IN_WORD)
{
printf("\n" );//moving outside a word so add a line feed, so the next word is outputted on its own line
}
state = OUT_WORD;

}

else if(state == OUT_WORD) //if space did not match above, check if were previously outside a word
{
state = IN_WORD; //we must now be in a word then,
putchar('|');//just entering a word, print first bar
}
else//we are in a word, output all bars completing the histogram for this word
{
putchar('|');
}
}

getchar();
return 0;
}



If you tried out the last example you'll notice the similarities, the major difference is that when we are in a word we print a horizontal bar |
for each character thereby printing an Histogram for each word... more explanation in a bit, however do try it out and make sure it works
Re: Lets Learn C by stack1(m): 11:39pm On Aug 08, 2016
[size=14pt]Formatted Input/Output[/size]

Now we'll learn a bit about the printf and scanf input/output functions

We have been previously using the getchar and putchar functions for character input and output, while this functions work well for single character input and output many programs usually require much more complex and detailed way to get program input and output values
Re: Lets Learn C by timtoday: 6:06am On Aug 09, 2016
stack1:
This next program remove's extra spaces between text, so to try it enter any amount of text with lot's of space between the text's and the program would detect and truncate such space(s) to just one space



int main(void)
{
int c,last_char_is_blank;

last_char_is_blank = 0;

while((c=getchar())!=EOF)
{

if(c==32) //a space was entered (ASCII) could have as well used c=' '
{
if(last_char_is_blank == 0) //flag hasn't been set, so the previous character wasn't a space
{

putchar(c);
last_char_is_blank=1; //set last char was a space flag
}
}
else
{
putchar(c);

last_char_is_blank=0; //regular char input, reset this
}
}

getchar();
return 0;
}



Now lets go through it.
Note that we start by declaring two integer variables in the main function c and last_char_is_blank,
we would use the last_char_is_blank variable, as a control variable to detect multiple spaces,

We read input characters into the variable c in the while loop

Next we have the if statement if(c==32) The number 32 is the ASCII value for SPACE and we could have equally done if(c== ' ') [\b], and achieved the same result, if the character entered is a space, the if block is executed this shows that you can use any ASCII decimal value instead of an Actual character.

The next line [b] if(last_char_is_blank == 0)
checks to see if the control variable has not been set the variable last_char_is_blank is initially assigned a value of zero so this test would pass and the following statements

  putchar(c);
last_char_is_blank=1; //set last char was a space flag


would be executed, the first statement outputs the space character ( remember we're still inside the if statement that detected a space)
then the next statement sets our control variable last_char_is_blank to one

On the next run of the loop if the imputed character is again a space, the if statement detects it, and so when the check if(last_char_is_blank == 0) is executed, the test fails since last_char_is_blank would now set to 1 (provided the previous character was a space)

If the imputed character is however not a SPACE character, the first if statement fails and the else block is executed, so the non-space character gets printed. and the last_char_is_blank variable is reset to ZERO

This way multiple spaces within the text is prevented. Enter the code and run-it to fully understand

Hi Stack,
Let me first say nice work. It is not easy to put up tutorials and as such in C programming language. The language of the gods! Lol.. I know plenty talk go start from here now!

All the same, there are one or two things in my opinion that i felt is NOT sitting well as regard some of the examples you posted. At least, from this one and those that followed. Of course, there are "some-what" in the previous ones like using a char datatype to get the return value of "macro" getchar which obviously returns an integer. Of course it works because intrinsically char are "integer". And you indeed use a correct return afterwards.

That been said, checking your example above, it will only take care of "spaces" whose ASCII value is 32. "Space-like" tab and others will NOT be taken care of.
Secondly, using a "raw" value i.e the ASCII value will defeat clarity of codes. Yes, you commented the line, but plain integer 32 could also be used for other things IF the code is extended or for other reasons. Somehow or somewhere portability will be defeated.

More so, why must I cram or have to lookup ASCII values to be able to write codes? It will further drive potential C programmer's away.

Lastly, there are other difficult concepts in C already why add this to it. It is like trying to know the IP address of google instead of just using www.google.com.

What do I think?
Since, C, already gave us a header file
<ctype.h>
Let us use that to our advantage and write a more portable codes, instead of "hand-picking" values.

Using such header, allows us to test more conveniently the value we are getting from standard input or file, however the case maybe.
Below is rewrite of some sort...



#include <stdio.h>
#include <ctype.h> // isspace(int)

#define putchar(c) \
if ((c) == '\b' || (c) == '\t' || (c) == ' ' || (c) == '\v')\
putchar(' ')


int main(void) {

int c;

// we could have use bool value instead
// from the header stdbool.h
// instead of integer
int is_blanck = 0;

while((c = getchar()) != EOF) {
if (isspace(c)) {
++is_blanck;
if (is_blanck == 1)
putchar(c); /// self defined macro above
} else {
is_blanck = 0;
// note the bracket around the macro
(putchar)(c); // macro from stdio.h
}
}

return 0;
}



Really, there is (might be) NO *need* for the self defined macro included but to show that allowing the language to do it work. It a lot painless some of the time.
Just a note.
Re: Lets Learn C by timtoday: 6:23am On Aug 09, 2016
stack1:

As an example if you where writing a program calculating radius instead of creating an integer variable for PI like int PI = 3.142
its more appropriate to do
#define PI = 3.142...,
so anywhere you use PI, the value 3.142 would be substituted

While the issues of ASCII value and others in my previous post still apply to this. I will like to draw your attention to this
#define PI = 3.142....


Contrary to this statement
so anywhere you use PI, the value 3.142 would be substituted
.

No your program will NOT compile! WHY? an expression is needed before the token "=". In fact, the substitute value of PI is seen from the space that follows afterwards...

Probably is a typo! smiley You are doing great boss...
Re: Lets Learn C by stack1(m): 8:06am On Aug 09, 2016
timtoday:


While the issues of ASCII value and others in my previous post still apply to this. I will like to draw your attention to this

Contrary to this statement .

No your program will NOT compile! WHY? an expression is needed before the token "=". In fact, the substitute value of PI is seen from the space that follows afterwards...

Probably is a typo! smiley You are doing great boss...

Jesus LOL how silly of me would modify that right away, thanks
Re: Lets Learn C by stack1(m): 8:12am On Aug 09, 2016
timtoday:


Hi Stack,
Let me first say nice work. It is not easy to put up tutorials and as such in C programming language. The language of the gods! Lol.. I know plenty talk go start from here now!

All the same, there are one or two things in my opinion that i felt is NOT sitting well as regard some of the examples you posted. At least, from this one and those that followed. Of course, there are "some-what" in the previous ones like using a char datatype to get the return value of "macro" getchar which obviously returns an integer. Of course it works because intrinsically char are "integer". And you indeed use a correct return afterwards.

That been said, checking your example above, it will only take care of "spaces" whose ASCII value is 32. "Space-like" tab and others will NOT be taken care of.
Secondly, using a "raw" value i.e the ASCII value will defeat clarity of codes. Yes, you commented the line, but plain integer 32 could also be used for other things IF the code is extended or for other reasons. Somehow or somewhere portability will be defeated.

More so, why must I cram or have to lookup ASCII values to be able to write codes? It will further drive potential C programmer's away.

Lastly, there are other difficult concepts in C already why add this to it. It is like trying to know the IP address of google instead of just using www.google.com.

What do I think?
Since, C, already gave us a header file
<ctype.h>
Let us use that to our advantage and write a more portable codes, instead of "hand-picking" values.

Using such header, allows us to test more conveniently the value we are getting from standard input or file, however the case maybe.
Below is rewrite of some sort...



#include <stdio.h>
#include <ctype.h> // isspace(int)

#define putchar(c) \
if ((c) == '\b' || (c) == '\t' || (c) == ' ' || (c) == '\v')\
putchar(' ')


int main(void) {

int c;

// we could have use bool value instead
// from the header stdbool.h
// instead of integer
int is_blanck = 0;

while((c = getchar()) != EOF) {
if (isspace(c)) {
++is_blanck;
if (is_blanck == 1)
putchar(c); /// self defined macro above
} else {
is_blanck = 0;
// note the bracket around the macro
(putchar)(c); // macro from stdio.h
}
}

return 0;
}



Really, there is (might be) NO *need* for the self defined macro included but to show that allowing the language to do it work. It a lot painless some of the time.
Just a note.

True and Yes was just trying to poiny out that ASCII values can also be used in plaxe of the characters them selves and as for the putchar MACRO, dats a bit too complex a statement in this stage, i actually confuse myself a lot just trying to structure the tutorial, but its good to know i have folks watching my back, and yeah C provides us several functions to do stuff i've bn trying to do manually, but i fell that would give the beginer a good hands on approach in cases they need to implement their own functions,i learnt C from Books such as K&R e.t.c so 4gv my Old school style
Re: Lets Learn C by stack1(m): 1:36am On Aug 16, 2016
Hi guyz, been a while. Sorry for the long break but i've been so busy with stuff.. Initially i thought about going into Formatted input and Output tonight, however we have covered quite some basics, so i felt why not throw in a relatively ambitious example and lets tackle it, before going into more advanced stuff

Languages belonging to the C family like C (itself), C++, Java, Go, JavaScript e.t.c, have certain similar features, like they all use both
single line comments

// coment goes here ..this are also known as C++ style comments


and multi-line comments


/*
* Lotta comments here. blah blah
*/


Generally comments are meant for human readers to better understand your code or to provide a means to generate documentation using various tools, so the compiler/interpreter generally ignores and discarded all comments..
The code below is an attempt at writing a Program that would remove all Single and multi-line comments from a program source code, so try it by feeding it various commented programs (not just C programs, also Java e.t.c) that you can find anywhere and lets see if it works for you..
Also try going through the code to see if you can get a hang of it, I'll be back in a few hours to go through it thoroughly.

Also when testing the program after posting your code press Ctrl+Z to send the End-Of-File character as the program would keep reading input till it reaches EOF, then it processes the input and spits back your code with all comments removed..




/*
Program to remove comments from a C Program.
removes both C and C++ style comments
*/

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>


static unsigned char input_buffer[200000];

int main(void) {


int c,d,
in_char_count = 0;

bool m_cmt = false; //multi-line comment detected, initially false
bool s_cmt = false; //single-line comment detected, initially false



printf(" Enter Source Code Below \n\n" );


while((c = getchar()) != EOF ) {


if(m_cmt) {

c = getchar();
d = getchar();

while(c != '*' && d != '/') {
c = d;
d = getchar();
}

m_cmt = false;

c = getchar();
c = getchar();
}

if(s_cmt) {
c = getchar();
while(c != '\n') c = getchar();

s_cmt = false;

}

if(c == '/' ) {

d = getchar();

if(d == '*') m_cmt = true;

else if(d=='/') s_cmt = true;

else {
input_buffer[in_char_count++] =c;
input_buffer[in_char_count++] = d;

continue;
}
}

if(m_cmt || s_cmt) continue;
else
input_buffer[in_char_count++] = c;

}




system("clear" ); /* CLEAR SCREEN ON UNIX/LINUX */
system("cls" ); /* CLEAR SCREEN ON DOS (..ooh windows i mean ) */



printf("\n\n\nProcessed source code...\n\n" );

input_buffer[in_char_count] = '\0';

printf("%s", input_buffer);

getchar();

return EXIT_SUCCESS;


}



In this example we included a new library header file you may have not seen before, stdbool.h , this header file simply introduces the Boolean types into our program, The Boolean type is a type that can hold two values either true or false, Boolean's can be used to represent state, like an [b]on [/b]or [b]off [/b]state, or 0 and 1, Yes and No, in the example we simply use it to track when we are in single and multi-line comments and when we are out of them... so please run the example and lets discuss it. The boolean type wasn't originally part of C, and was introduced in the C99 version of the language
Re: Lets Learn C by Nobody: 10:52am On Aug 16, 2016
uhm uhm, e be like say i don miss some classes, need to scroll back to previous page, it is beginning to become like magic. . .
Re: Lets Learn C by olarid01: 5:28pm On Aug 16, 2016
good job OP. I started with this language and it paid off a lot (God bless Deitel). How I wish newbies learn this language first instead of jumping to all those ready made languages full of libraries........
Re: Lets Learn C by stack1(m): 5:36pm On Aug 16, 2016
olarid01:
good job OP. I started with this language and it paid off a lot (God bless Deitel). How I wish newbies learn this language first instead of jumping to all those ready made languages full of libraries........
Quite right man, they really miss the depth, intuitive prowess C and C++ can "bestow" on a programmer, Interestingly i also had the Deitel series in hard-back (both C&C++) really good books, though i really can't remember how i misplaced them cheesy

1 Like

Re: Lets Learn C by stack1(m): 5:38pm On Aug 16, 2016
..so has anyone been able to run the comment removal program... feedback please before i dive into how it works..

(1) (2) (3) (4) (5) (Reply)

An Introduction To Programming Using C / How Do You Get A CEH / Pentesting Job In Nigeria? / Android Quiz Application With Json Parser, Php And Mysql Database

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 126
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.