This commit is contained in:
bigheadbh 2021-03-03 12:10:04 -03:00 committed by Felipe
parent f19601aedf
commit 5554ab7587
259 changed files with 195481 additions and 195481 deletions

8
.gitignore vendored
View File

@ -1,4 +1,4 @@
*.exe
*.class
*.o
*.exe
*.class
*.o

View File

@ -1,16 +1,16 @@
# AEDII
Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II
## Ajuda
[Readme.md com os principais comandos.](ajuda/)
## fonte
## labs
Ativdades dos laboratórios.
## tps
# AEDII
Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II
## Ajuda
[Readme.md com os principais comandos.](ajuda/)
## fonte
## labs
Ativdades dos laboratórios.
## tps

View File

@ -1,91 +1,91 @@
## ALGUNS ARQUIVOS INTERESSANTES
* ~/.bash_history - Lista de comandos executados
* ~/.vimrc - Configuracoes do VIM
* ~/.profile - Configuracoes do seu Usuario
## PRINCIPAIS COMANDOS NO VIM
* i - Abre o modo de insercao
* ESC - Fecha o modo de insercao
* :w - Salvar
* :q - Sair
* :q! - Forcar saida
* :wq! - Salvar e forcar a saida
* ? PALAVRA - Procurar as ocorrencias de PALAVRA
* :%s/STRING_OLD/STRING_NEW/gc - Substrituir a STRING_OLD pela STRING_NEW
* yy - Copiar linha
* NUMEROyy - Copiar NUMERO linhas
* dd - Excluir linha
* NUMEROdd - Excluir NUMERO linhas
* dw - Excluir palavra
* NUMEROdw - Excluir NUMERO palavras
* p - Colar
* :sp ARQUIVO - Abre o arquivo ARQUIVO
* ww - Alternar entre os arquivos abertos
* CTRL+V - Abre o modo de visualizacao
## ALGUNS COMANDOS PARA O MODO SHELL DO LINUX
* man
* exit
* cd
* ls
* ls -l -t -h
* rm
* cp
* mkdir
* clear
* grep
* grep "PALAVRA" ARQUIVO
* diff
* diff ARQUIVO1 ARQUIVO2
* ssh
* sftp
* wget
* chmod
* javac
* java
* tar -zcvf arquivo.tar.gz pasta
* tar -zxvf arquivo.tar.gz
## COMPILAR E EXECUTAR PROGRAMA JAVA EM LINHA DE COMANDO
1) Compilar:
> javac Programa.java
2) Executar:
> java Programa
3) Executar alterando entrada padrao:
> java Programa < entrada.in
4) Executar alterando saida padrao:
> java Programa > saida.in
5) Executar alterando entrada/saida padrao:
> java Programa < entrada.in > saida.in
## COMPILAR E EXECUTAR PROGRAMA C++ EM LINHA DE COMANDO
1) Compilar:
> g++ fonte.cc -o objeto
2) Executar:
> ./objeto
3) Executar alterando entrada padrao:
> ./objeto < entrada.in
4) Executar alterando saida padrao:
> ./objeto > saida.in
5) Executar alterando entrada/saida padrao:
> ./objeto < entrada.in > saida.in
## GDB
1) Chamar o gdb
> gdb objeto
2) Executar no gdb
> run
3) Acessar a pilha de chamadas
> bt
## ALGUNS ARQUIVOS INTERESSANTES
* ~/.bash_history - Lista de comandos executados
* ~/.vimrc - Configuracoes do VIM
* ~/.profile - Configuracoes do seu Usuario
## PRINCIPAIS COMANDOS NO VIM
* i - Abre o modo de insercao
* ESC - Fecha o modo de insercao
* :w - Salvar
* :q - Sair
* :q! - Forcar saida
* :wq! - Salvar e forcar a saida
* ? PALAVRA - Procurar as ocorrencias de PALAVRA
* :%s/STRING_OLD/STRING_NEW/gc - Substrituir a STRING_OLD pela STRING_NEW
* yy - Copiar linha
* NUMEROyy - Copiar NUMERO linhas
* dd - Excluir linha
* NUMEROdd - Excluir NUMERO linhas
* dw - Excluir palavra
* NUMEROdw - Excluir NUMERO palavras
* p - Colar
* :sp ARQUIVO - Abre o arquivo ARQUIVO
* ww - Alternar entre os arquivos abertos
* CTRL+V - Abre o modo de visualizacao
## ALGUNS COMANDOS PARA O MODO SHELL DO LINUX
* man
* exit
* cd
* ls
* ls -l -t -h
* rm
* cp
* mkdir
* clear
* grep
* grep "PALAVRA" ARQUIVO
* diff
* diff ARQUIVO1 ARQUIVO2
* ssh
* sftp
* wget
* chmod
* javac
* java
* tar -zcvf arquivo.tar.gz pasta
* tar -zxvf arquivo.tar.gz
## COMPILAR E EXECUTAR PROGRAMA JAVA EM LINHA DE COMANDO
1) Compilar:
> javac Programa.java
2) Executar:
> java Programa
3) Executar alterando entrada padrao:
> java Programa < entrada.in
4) Executar alterando saida padrao:
> java Programa > saida.in
5) Executar alterando entrada/saida padrao:
> java Programa < entrada.in > saida.in
## COMPILAR E EXECUTAR PROGRAMA C++ EM LINHA DE COMANDO
1) Compilar:
> g++ fonte.cc -o objeto
2) Executar:
> ./objeto
3) Executar alterando entrada padrao:
> ./objeto < entrada.in
4) Executar alterando saida padrao:
> ./objeto > saida.in
5) Executar alterando entrada/saida padrao:
> ./objeto < entrada.in > saida.in
## GDB
1) Chamar o gdb
> gdb objeto
2) Executar no gdb
> run
3) Acessar a pilha de chamadas
> bt

View File

@ -1,206 +1,206 @@
import java.io.*;
import java.util.Formatter;
import java.util.Scanner;
import java.io.File;
import java.nio.charset.*;
public class Arq
{
private static String nomeArquivo = "";
private static String charsetArquivo = "ISO-8859-1";
private static boolean write = false, read = false;
private static Formatter saida = null;
private static Scanner entrada = null;
public static boolean openWrite(String nomeArq, String charset) {
boolean resp = false;
close();
try{
saida = new Formatter(nomeArq, charset);
nomeArquivo = nomeArq;
resp = write = true;
} catch (Exception e) {}
return resp;
}
public static boolean openWrite(String nomeArq) {
return openWrite(nomeArq, charsetArquivo);
}
public static boolean openWriteClose(String nomeArq, String charset, String conteudo) {
boolean resp = openWrite(nomeArq, charset);
if(resp == true){
println(conteudo);
close();
}
return resp;
}
public static boolean openWriteClose(String nomeArq, String conteudo) {
return openWriteClose(nomeArq, charsetArquivo, conteudo);
}
public static boolean openRead(String nomeArq) {
return openRead(nomeArq, charsetArquivo);
}
public static boolean openRead(String nomeArq, String charset) {
boolean resp = false;
close();
try{
entrada = new Scanner(new File(nomeArq), charset);
nomeArquivo = nomeArq;
resp = read = true;
} catch (Exception e) {}
return resp;
}
public static String openReadClose(String nomeArq){
openRead(nomeArq);
String resp = readAll();
close();
return resp;
}
public static void close() {
if(write == true){
saida.close();
}
if(read == true){
entrada.close();
}
write = read = false;
nomeArquivo = "";
charsetArquivo = "ISO-8859-1";
}
public static long length(){
long resp = -1;
if(read != write){
File file = new File(nomeArquivo);
resp = file.length();
}
return resp;
}
public static void print(int x){
if(write == true){
saida.format( "%d", x);
}
}
public static void print(double x){
if(write == true){
saida.format( "%f", x);
}
}
public static void print(String x){
if(write == true){
saida.format( "%s", x);
}
}
public static void print(boolean x){
if(write == true){
saida.format( "%s", ((x) ? "true" : "false"));
}
}
public static void print(char x){
if(write == true){
saida.format( "%c", x);
}
}
public static void println(int x){
if(write == true){
saida.format( "%d\n", x);
}
}
public static void println(double x){
if(write == true){
saida.format( "%f\n", x);
}
}
public static void println(String x){
if(write == true){
saida.format( "%s\n", x);
}
}
public static void println(boolean x){
if(write == true){
saida.format( "%s\n", ((x) ? "true" : "false"));
}
}
public static void println(char x){
if(write == true){
saida.format( "%c\n", x);
}
}
public static int readInt(){
int resp = -1;
try{
resp = entrada.nextInt();
} catch (Exception e) {}
return resp;
}
public static char readChar(){
char resp = ' ';
try{
resp = (char)entrada.nextByte();
} catch (Exception e) {}
return resp;
}
public static double readDouble(){
double resp = -1;
try{
resp = Double.parseDouble(readString().replace(",","."));
} catch (Exception e) {}
return resp;
}
public static String readString(){
String resp = "";
try{
resp = entrada.next();
} catch (Exception e) { System.out.println(e.getMessage()); }
return resp;
}
public static boolean readBoolean(){
boolean resp = false;
try{
resp = (entrada.next().equals("true")) ? true : false;
} catch (Exception e) {}
return resp;
}
public static String readLine(){
String resp = "";
try{
resp = entrada.nextLine();
} catch (Exception e) { System.out.println(e.getMessage()); }
return resp;
}
public static boolean hasNext(){
return entrada.hasNext();
}
public static String readAll(){
String resp = "";
while(hasNext()){
resp += (readLine() + "\n");
}
return resp;
}
}
import java.io.*;
import java.util.Formatter;
import java.util.Scanner;
import java.io.File;
import java.nio.charset.*;
public class Arq
{
private static String nomeArquivo = "";
private static String charsetArquivo = "ISO-8859-1";
private static boolean write = false, read = false;
private static Formatter saida = null;
private static Scanner entrada = null;
public static boolean openWrite(String nomeArq, String charset) {
boolean resp = false;
close();
try{
saida = new Formatter(nomeArq, charset);
nomeArquivo = nomeArq;
resp = write = true;
} catch (Exception e) {}
return resp;
}
public static boolean openWrite(String nomeArq) {
return openWrite(nomeArq, charsetArquivo);
}
public static boolean openWriteClose(String nomeArq, String charset, String conteudo) {
boolean resp = openWrite(nomeArq, charset);
if(resp == true){
println(conteudo);
close();
}
return resp;
}
public static boolean openWriteClose(String nomeArq, String conteudo) {
return openWriteClose(nomeArq, charsetArquivo, conteudo);
}
public static boolean openRead(String nomeArq) {
return openRead(nomeArq, charsetArquivo);
}
public static boolean openRead(String nomeArq, String charset) {
boolean resp = false;
close();
try{
entrada = new Scanner(new File(nomeArq), charset);
nomeArquivo = nomeArq;
resp = read = true;
} catch (Exception e) {}
return resp;
}
public static String openReadClose(String nomeArq){
openRead(nomeArq);
String resp = readAll();
close();
return resp;
}
public static void close() {
if(write == true){
saida.close();
}
if(read == true){
entrada.close();
}
write = read = false;
nomeArquivo = "";
charsetArquivo = "ISO-8859-1";
}
public static long length(){
long resp = -1;
if(read != write){
File file = new File(nomeArquivo);
resp = file.length();
}
return resp;
}
public static void print(int x){
if(write == true){
saida.format( "%d", x);
}
}
public static void print(double x){
if(write == true){
saida.format( "%f", x);
}
}
public static void print(String x){
if(write == true){
saida.format( "%s", x);
}
}
public static void print(boolean x){
if(write == true){
saida.format( "%s", ((x) ? "true" : "false"));
}
}
public static void print(char x){
if(write == true){
saida.format( "%c", x);
}
}
public static void println(int x){
if(write == true){
saida.format( "%d\n", x);
}
}
public static void println(double x){
if(write == true){
saida.format( "%f\n", x);
}
}
public static void println(String x){
if(write == true){
saida.format( "%s\n", x);
}
}
public static void println(boolean x){
if(write == true){
saida.format( "%s\n", ((x) ? "true" : "false"));
}
}
public static void println(char x){
if(write == true){
saida.format( "%c\n", x);
}
}
public static int readInt(){
int resp = -1;
try{
resp = entrada.nextInt();
} catch (Exception e) {}
return resp;
}
public static char readChar(){
char resp = ' ';
try{
resp = (char)entrada.nextByte();
} catch (Exception e) {}
return resp;
}
public static double readDouble(){
double resp = -1;
try{
resp = Double.parseDouble(readString().replace(",","."));
} catch (Exception e) {}
return resp;
}
public static String readString(){
String resp = "";
try{
resp = entrada.next();
} catch (Exception e) { System.out.println(e.getMessage()); }
return resp;
}
public static boolean readBoolean(){
boolean resp = false;
try{
resp = (entrada.next().equals("true")) ? true : false;
} catch (Exception e) {}
return resp;
}
public static String readLine(){
String resp = "";
try{
resp = entrada.nextLine();
} catch (Exception e) { System.out.println(e.getMessage()); }
return resp;
}
public static boolean hasNext(){
return entrada.hasNext();
}
public static String readAll(){
String resp = "";
while(hasNext()){
resp += (readLine() + "\n");
}
return resp;
}
}

View File

@ -1,40 +1,40 @@
import java.io.*;
import java.net.*;
class ExemploURL {
public static String getHtml(String endereco){
URL url;
InputStream is = null;
BufferedReader br;
String resp = "", line;
try {
url = new URL(endereco);
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
resp += line + "\n";
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
is.close();
} catch (IOException ioe) {
// nothing to see here
}
return resp;
}
public static void main(String[] args) {
String endereco, html;
endereco = "http://maratona.crc.pucminas.br/series/Friends.html";
html = getHtml(endereco);
System.out.print(html);
}
}
import java.io.*;
import java.net.*;
class ExemploURL {
public static String getHtml(String endereco){
URL url;
InputStream is = null;
BufferedReader br;
String resp = "", line;
try {
url = new URL(endereco);
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
resp += line + "\n";
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
is.close();
} catch (IOException ioe) {
// nothing to see here
}
return resp;
}
public static void main(String[] args) {
String endereco, html;
endereco = "http://maratona.crc.pucminas.br/series/Friends.html";
html = getHtml(endereco);
System.out.print(html);
}
}

View File

@ -1,252 +1,252 @@
import java.io.*;
import java.nio.charset.*;
class MyIO {
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1")));
private static String charset = "ISO-8859-1";
public static void setCharset(String charset_){
charset = charset_;
in = new BufferedReader(new InputStreamReader(System.in, Charset.forName(charset)));
}
public static void print(){
}
public static void print(int x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void print(float x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void print(double x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void print(String x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void print(boolean x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void print(char x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void println(){
}
public static void println(int x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void println(float x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void println(double x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void println(String x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void println(boolean x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void println(char x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void printf(String formato, double x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.printf(formato, x);// "%.2f"
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static double readDouble(){
double d = -1;
try{
d = Double.parseDouble(readString().trim().replace(",","."));
}catch(Exception e){}
return d;
}
public static double readDouble(String str){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readDouble();
}
public static float readFloat(){
return (float) readDouble();
}
public static float readFloat(String str){
return (float) readDouble(str);
}
public static int readInt(){
int i = -1;
try{
i = Integer.parseInt(readString().trim());
}catch(Exception e){}
return i;
}
public static int readInt(String str){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readInt();
}
public static String readString(){
String s = "";
char tmp;
try{
do{
tmp = (char)in.read();
if(tmp != '\n' && tmp != ' ' && tmp != 13){
s += tmp;
}
}while(tmp != '\n' && tmp != ' ');
}catch(IOException ioe){
System.out.println("lerPalavra: " + ioe.getMessage());
}
return s;
}
public static String readString(String str){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readString();
}
public static String readLine(){
String s = "";
char tmp;
try{
do{
tmp = (char)in.read();
if(tmp != '\n' && tmp != 13){
s += tmp;
}
}while(tmp != '\n');
}catch(IOException ioe){
System.out.println("lerPalavra: " + ioe.getMessage());
}
return s;
}
public static String readLine(String str){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readLine();
}
public static char readChar(){
char resp = ' ';
try{
resp = (char)in.read();
}catch(Exception e){}
return resp;
}
public static char readChar(String str){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readChar();
}
public static boolean readBoolean(){
boolean resp = false;
String str = "";
try{
str = readString();
}catch(Exception e){}
if(str.equals("true") || str.equals("TRUE") || str.equals("t") || str.equals("1") ||
str.equals("verdadeiro") || str.equals("VERDADEIRO") || str.equals("V")){
resp = true;
}
return resp;
}
public static boolean readBoolean(String str){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readBoolean();
}
public static void pause(){
try{
in.read();
}catch(Exception e){}
}
public static void pause(String str){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
pause();
}
}
import java.io.*;
import java.nio.charset.*;
class MyIO {
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1")));
private static String charset = "ISO-8859-1";
public static void setCharset(String charset_){
charset = charset_;
in = new BufferedReader(new InputStreamReader(System.in, Charset.forName(charset)));
}
public static void print(){
}
public static void print(int x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void print(float x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void print(double x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void print(String x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void print(boolean x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void print(char x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void println(){
}
public static void println(int x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void println(float x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void println(double x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void println(String x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void println(boolean x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void println(char x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.println(x);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static void printf(String formato, double x){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.printf(formato, x);// "%.2f"
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
}
public static double readDouble(){
double d = -1;
try{
d = Double.parseDouble(readString().trim().replace(",","."));
}catch(Exception e){}
return d;
}
public static double readDouble(String str){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readDouble();
}
public static float readFloat(){
return (float) readDouble();
}
public static float readFloat(String str){
return (float) readDouble(str);
}
public static int readInt(){
int i = -1;
try{
i = Integer.parseInt(readString().trim());
}catch(Exception e){}
return i;
}
public static int readInt(String str){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readInt();
}
public static String readString(){
String s = "";
char tmp;
try{
do{
tmp = (char)in.read();
if(tmp != '\n' && tmp != ' ' && tmp != 13){
s += tmp;
}
}while(tmp != '\n' && tmp != ' ');
}catch(IOException ioe){
System.out.println("lerPalavra: " + ioe.getMessage());
}
return s;
}
public static String readString(String str){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readString();
}
public static String readLine(){
String s = "";
char tmp;
try{
do{
tmp = (char)in.read();
if(tmp != '\n' && tmp != 13){
s += tmp;
}
}while(tmp != '\n');
}catch(IOException ioe){
System.out.println("lerPalavra: " + ioe.getMessage());
}
return s;
}
public static String readLine(String str){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readLine();
}
public static char readChar(){
char resp = ' ';
try{
resp = (char)in.read();
}catch(Exception e){}
return resp;
}
public static char readChar(String str){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readChar();
}
public static boolean readBoolean(){
boolean resp = false;
String str = "";
try{
str = readString();
}catch(Exception e){}
if(str.equals("true") || str.equals("TRUE") || str.equals("t") || str.equals("1") ||
str.equals("verdadeiro") || str.equals("VERDADEIRO") || str.equals("V")){
resp = true;
}
return resp;
}
public static boolean readBoolean(String str){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
return readBoolean();
}
public static void pause(){
try{
in.read();
}catch(Exception e){}
}
public static void pause(String str){
try {
PrintStream out = new PrintStream(System.out, true, charset);
out.print(str);
}catch(UnsupportedEncodingException e){ System.out.println("Erro: charset invalido"); }
pause();
}
}

View File

@ -1,18 +1,18 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "r");
// testa se o arquivo foi aberto com sucesso
if (p != NULL) {
printf ("Arquivo foi aberto com sucesso.\n\n");
fclose(p);
} else {
printf ("Nao foi possivel abrir o arquivo.\n\n");
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "r");
// testa se o arquivo foi aberto com sucesso
if (p != NULL) {
printf ("Arquivo foi aberto com sucesso.\n\n");
fclose(p);
} else {
printf ("Nao foi possivel abrir o arquivo.\n\n");
}
return 0;
}

View File

@ -1,19 +1,19 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "r");
// testa se o arquivo foi aberto com sucesso
if (p != NULL) {
printf ("Arquivo foi aberto com sucesso.\n\n");
fclose(p);
} else {
printf ("Nao foi possivel abrir o arquivo.\n\n");
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "r");
// testa se o arquivo foi aberto com sucesso
if (p != NULL) {
printf ("Arquivo foi aberto com sucesso.\n\n");
fclose(p);
} else {
printf ("Nao foi possivel abrir o arquivo.\n\n");
}
return 0;
}

View File

@ -1,21 +1,21 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p = fopen (argv[1], "r");
int ch;
if (p != NULL) {
do {
ch = fgetc(p);
if(ch != EOF){
printf( "%i %c\n", ch, (char)ch);
//printf( "%c", (char)ch);
}
} while (ch != EOF);
fclose(p);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p = fopen (argv[1], "r");
int ch;
if (p != NULL) {
do {
ch = fgetc(p);
if(ch != EOF){
printf( "%i %c\n", ch, (char)ch);
//printf( "%c", (char)ch);
}
} while (ch != EOF);
fclose(p);
}
return 0;
}

View File

@ -1,23 +1,23 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "r");
char str[100+1];
char* resp;
int i = 0;
if (p != NULL) {
do {
resp = fgets(str, 100, p);
if(resp != NULL){
printf("(%d) %s", i, str);
i++;
}
} while (resp != NULL);
fclose(p);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "r");
char str[100+1];
char* resp;
int i = 0;
if (p != NULL) {
do {
resp = fgets(str, 100, p);
if(resp != NULL){
printf("(%d) %s", i, str);
i++;
}
} while (resp != NULL);
fclose(p);
}
return 0;
}

View File

@ -1,12 +1,12 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "w");
fputc('M', p);
fclose(p);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "w");
fputc('M', p);
fclose(p);
return 0;
}

View File

@ -1,11 +1,11 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "w");
fputs("Algoritmos e Estruturas de Dados II", p);
fclose(p);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p = fopen ("teste.txt", "w");
fputs("Algoritmos e Estruturas de Dados II", p);
fclose(p);
return 0;
}

View File

@ -1,19 +1,19 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *in = fopen ("teste.txt", "r"),
*out = fopen ("copia.txt", "w");
while ( !feof(in) ) {
char ch = getc(in);
if ( !feof(in)) {
putc(ch, out);
}
}
fclose(in);
fclose(out);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *in = fopen ("teste.txt", "r"),
*out = fopen ("copia.txt", "w");
while ( !feof(in) ) {
char ch = getc(in);
if ( !feof(in)) {
putc(ch, out);
}
}
fclose(in);
fclose(out);
return 0;
}

View File

@ -1,24 +1,24 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p;
double d = 12.23;
int i = 101;
long l = 123023L;
if ((p = fopen("teste.txt", "wb")) == NULL) {
printf ("arquivo nao pode ser aberto\n");
exit(1);
}
fwrite(&d, sizeof(double), 1, p);
fwrite(&i, sizeof(int), 1, p);
fwrite(&l, sizeof(long), 1, p);
fclose(p);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p;
double d = 12.23;
int i = 101;
long l = 123023L;
if ((p = fopen("teste.txt", "wb")) == NULL) {
printf ("arquivo nao pode ser aberto\n");
exit(1);
}
fwrite(&d, sizeof(double), 1, p);
fwrite(&i, sizeof(int), 1, p);
fwrite(&l, sizeof(long), 1, p);
fclose(p);
return 0;
}

View File

@ -1,25 +1,25 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p;
double d;
int i;
long l;
if ((p = fopen("teste.txt", "rb")) == NULL) {
printf ("arquivo nao pode ser aberto\n");
exit(1);
}
fread(&d, sizeof(double), 1, p);
fread (&i, sizeof(int), 1, p);
fread (&l, sizeof(long), 1, p);
printf("%f %d %ld", d, i, l);
fclose(p);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *p;
double d;
int i;
long l;
if ((p = fopen("teste.txt", "rb")) == NULL) {
printf ("arquivo nao pode ser aberto\n");
exit(1);
}
fread(&d, sizeof(double), 1, p);
fread (&i, sizeof(int), 1, p);
fread (&l, sizeof(long), 1, p);
printf("%f %d %ld", d, i, l);
fclose(p);
return 0;
}

View File

@ -1,35 +1,35 @@
#include <stdio.h>
#include <string.h>
typedef struct cliente {
char nome[100];
int codigo;
} cliente;
void escrever(char*);
void ler(char*);
void main(int argc, char** argv){
escrever("teste.txt");
ler("teste.txt");
}
void escrever(char* nomeArq){
cliente c1, c2;
strcat(c1.nome, "Ze da Silva"); c1.codigo = 1;
strcat(c2.nome, "Lele da Cuca"); c2.codigo = 11;
FILE *p = fopen(nomeArq, "ab");
fwrite(&c1, sizeof(cliente), 1, p);
fwrite(&c2, sizeof(cliente), 1, p);
fclose(p);
}
void ler(char* nomeArq){
cliente c1, c2;
FILE *p = fopen(nomeArq, "rb");
fread(&c1, sizeof(cliente), 1, p);
fread(&c2, sizeof(cliente), 1, p);
fclose(p);
printf("%s -- %d\n", c1.nome, c1.codigo);
printf("%s -- %d\n", c2.nome, c2.codigo);
}
#include <stdio.h>
#include <string.h>
typedef struct cliente {
char nome[100];
int codigo;
} cliente;
void escrever(char*);
void ler(char*);
void main(int argc, char** argv){
escrever("teste.txt");
ler("teste.txt");
}
void escrever(char* nomeArq){
cliente c1, c2;
strcat(c1.nome, "Ze da Silva"); c1.codigo = 1;
strcat(c2.nome, "Lele da Cuca"); c2.codigo = 11;
FILE *p = fopen(nomeArq, "ab");
fwrite(&c1, sizeof(cliente), 1, p);
fwrite(&c2, sizeof(cliente), 1, p);
fclose(p);
}
void ler(char* nomeArq){
cliente c1, c2;
FILE *p = fopen(nomeArq, "rb");
fread(&c1, sizeof(cliente), 1, p);
fread(&c2, sizeof(cliente), 1, p);
fclose(p);
printf("%s -- %d\n", c1.nome, c1.codigo);
printf("%s -- %d\n", c2.nome, c2.codigo);
}

View File

@ -1,23 +1,23 @@
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *p = fopen("teste.txt", "wb+");
double d = 12.23; int i = 101; long l = 123023L;
fwrite(&d, sizeof(double), 1, p);
fwrite(&i, sizeof(int), 1, p);
fwrite(&l, sizeof(long), 1, p);
rewind(p);
fread(&d, sizeof(double), 1, p);
fread (&i, sizeof(int), 1, p);
fread (&l, sizeof(long), 1, p);
printf("%f %d %ld", d, i, l);
fclose(p);
return 0;
}
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *p = fopen("teste.txt", "wb+");
double d = 12.23; int i = 101; long l = 123023L;
fwrite(&d, sizeof(double), 1, p);
fwrite(&i, sizeof(int), 1, p);
fwrite(&l, sizeof(long), 1, p);
rewind(p);
fread(&d, sizeof(double), 1, p);
fread (&i, sizeof(int), 1, p);
fread (&l, sizeof(long), 1, p);
printf("%f %d %ld", d, i, l);
fclose(p);
return 0;
}

View File

@ -1,22 +1,22 @@
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *p = fopen("teste.txt", "wb+");
int registro, valor, i;
for (i = valor = 0; i < 10; i++, valor = i * 10) fwrite(&valor, sizeof(int), 1, p);
int numRegistro = ftell(p) / sizeof (int);
do {
printf ("\nEscolha um numero entre zero e %i: ", numRegistro-1);
scanf("%d", &registro);
} while (registro < 0 || registro >= numRegistro);
fseek(p, registro * sizeof(int), SEEK_SET);
fread(&valor, sizeof(int), 1, p);
fclose(p);
printf ("\nValor: %d\n\n", valor);
return 0;
}
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *p = fopen("teste.txt", "wb+");
int registro, valor, i;
for (i = valor = 0; i < 10; i++, valor = i * 10) fwrite(&valor, sizeof(int), 1, p);
int numRegistro = ftell(p) / sizeof (int);
do {
printf ("\nEscolha um numero entre zero e %i: ", numRegistro-1);
scanf("%d", &registro);
} while (registro < 0 || registro >= numRegistro);
fseek(p, registro * sizeof(int), SEEK_SET);
fread(&valor, sizeof(int), 1, p);
fclose(p);
printf ("\nValor: %d\n\n", valor);
return 0;
}

View File

@ -1,117 +1,117 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//=============================================================================
void gravar_arquivo_texto(){
// ABRIR O ARQUIVO
FILE *arq = fopen("arquivo.txt", "w");
if(arq == NULL){
printf("Erro ao tentar abrir o arquivo!\n");
return;
}
// ESCREVER NO ARQUIVO
fprintf(arq, "%s\t", "Algoritmos");
fprintf(arq, "%d\t", 1);
fprintf(arq, "%f\t", 5.3);
fprintf(arq, "%c\t", 'X');
// FECHA O ARQUIVO
fclose(arq);
}
//=============================================================================
void ler_texto_texto(){
char texto[12], caracter;
int inteiro;
float real;
// ABRIR O ARQUIVO
FILE *arq = fopen("arquivo.txt", "r");
if(arq == NULL){
printf("Erro ao tentar abrir o arquivo!\n");
return;
}
// LE O ARQUIVO
fscanf(arq, "%99[^\t]\t", &texto); // LER STRING
fscanf(arq, "%d\t", &inteiro);
fscanf(arq, "%f\t", &real);
fscanf(arq, "%c\t", &caracter);
// FECHA O ARQUIVO
fclose(arq);
printf("texto: %s\n", texto);
printf("inteiro: %d\n", inteiro);
printf("real: %f\n", real);
printf("caracter: %c\n", caracter);
}
//=============================================================================
void gravar_arquivo_binario(){
char texto[12] = "Algoritmos", caracter = 'X';
int inteiro = 1;
float real = 5.3;
// ABRIR O ARQUIVO
FILE *arq = fopen("arquivo.bin", "wb");
if(arq == NULL){
printf("Erro ao tentar abrir o arquivo!\n");
return;
}
// ESCREVER NO ARQUIVO
fwrite(&texto, sizeof(char), 12, arq);
fwrite(&inteiro, sizeof(int), 1, arq);
fwrite(&real, sizeof(float), 1, arq);
fwrite(&caracter,sizeof(char), 1, arq);
// FECHA O ARQUIVO
fclose(arq);
}
//=============================================================================
void ler_texto_binario(){
char texto[12], caracter;
int inteiro;
float real;
// ABRIR O ARQUIVO
FILE *arq = fopen("arquivo.bin", "rb");
if(arq == NULL){
printf("Erro ao tentar abrir o arquivo!\n");
return;
}
// LE O ARQUIVO
fread(&texto, sizeof(char), 12, arq);
fread(&inteiro, sizeof(int), 1, arq);
fread(&real, sizeof(float), 1, arq);
fread(&caracter,sizeof(char), 1, arq);
// FECHA O ARQUIVO
fclose(arq);
printf("texto: %s\n", texto);
printf("inteiro: %d\n", inteiro);
printf("real: %f\n", real);
printf("caracter: %c\n", caracter);
}
//=============================================================================
int main(){
gravar_arquivo_texto();
ler_texto_texto();
gravar_arquivo_binario();
ler_texto_binario();
return 1;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//=============================================================================
void gravar_arquivo_texto(){
// ABRIR O ARQUIVO
FILE *arq = fopen("arquivo.txt", "w");
if(arq == NULL){
printf("Erro ao tentar abrir o arquivo!\n");
return;
}
// ESCREVER NO ARQUIVO
fprintf(arq, "%s\t", "Algoritmos");
fprintf(arq, "%d\t", 1);
fprintf(arq, "%f\t", 5.3);
fprintf(arq, "%c\t", 'X');
// FECHA O ARQUIVO
fclose(arq);
}
//=============================================================================
void ler_texto_texto(){
char texto[12], caracter;
int inteiro;
float real;
// ABRIR O ARQUIVO
FILE *arq = fopen("arquivo.txt", "r");
if(arq == NULL){
printf("Erro ao tentar abrir o arquivo!\n");
return;
}
// LE O ARQUIVO
fscanf(arq, "%99[^\t]\t", &texto); // LER STRING
fscanf(arq, "%d\t", &inteiro);
fscanf(arq, "%f\t", &real);
fscanf(arq, "%c\t", &caracter);
// FECHA O ARQUIVO
fclose(arq);
printf("texto: %s\n", texto);
printf("inteiro: %d\n", inteiro);
printf("real: %f\n", real);
printf("caracter: %c\n", caracter);
}
//=============================================================================
void gravar_arquivo_binario(){
char texto[12] = "Algoritmos", caracter = 'X';
int inteiro = 1;
float real = 5.3;
// ABRIR O ARQUIVO
FILE *arq = fopen("arquivo.bin", "wb");
if(arq == NULL){
printf("Erro ao tentar abrir o arquivo!\n");
return;
}
// ESCREVER NO ARQUIVO
fwrite(&texto, sizeof(char), 12, arq);
fwrite(&inteiro, sizeof(int), 1, arq);
fwrite(&real, sizeof(float), 1, arq);
fwrite(&caracter,sizeof(char), 1, arq);
// FECHA O ARQUIVO
fclose(arq);
}
//=============================================================================
void ler_texto_binario(){
char texto[12], caracter;
int inteiro;
float real;
// ABRIR O ARQUIVO
FILE *arq = fopen("arquivo.bin", "rb");
if(arq == NULL){
printf("Erro ao tentar abrir o arquivo!\n");
return;
}
// LE O ARQUIVO
fread(&texto, sizeof(char), 12, arq);
fread(&inteiro, sizeof(int), 1, arq);
fread(&real, sizeof(float), 1, arq);
fread(&caracter,sizeof(char), 1, arq);
// FECHA O ARQUIVO
fclose(arq);
printf("texto: %s\n", texto);
printf("inteiro: %d\n", inteiro);
printf("real: %f\n", real);
printf("caracter: %c\n", caracter);
}
//=============================================================================
int main(){
gravar_arquivo_texto();
ler_texto_texto();
gravar_arquivo_binario();
ler_texto_binario();
return 1;
}

View File

@ -1,14 +1,14 @@
#include <stdio.h>
#include <stdlib.h>
//=============================================================================
// EXEMPLO DE UTILIZAÇÃO DOS ARGUMENTOS PASSADOS PARA O MAIN
int main(int argc, char *argv[]){
int i;
for (i = 0; i < argc; i++)
printf("%d Parametro: %s\n", i, argv[i]);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
//=============================================================================
// EXEMPLO DE UTILIZAÇÃO DOS ARGUMENTOS PASSADOS PARA O MAIN
int main(int argc, char *argv[]){
int i;
for (i = 0; i < argc; i++)
printf("%d Parametro: %s\n", i, argv[i]);
return 0;
}
//=============================================================================

View File

@ -1,22 +1,22 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
char c;
char s[100];
int i;
double d;
printf("\nEntre com um caractere: ");
scanf("%c", &c);
printf("\nEntre com uma palavra: ");
scanf("%s", s);
printf("\nEntre com um inteiro e um real: ");
scanf("%i%lf", &i, &d);
printf("\ninteiro(%d) real(%f) char(%c) s(%s)", i, d, c, s);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
char c;
char s[100];
int i;
double d;
printf("\nEntre com um caractere: ");
scanf("%c", &c);
printf("\nEntre com uma palavra: ");
scanf("%s", s);
printf("\nEntre com um inteiro e um real: ");
scanf("%i%lf", &i, &d);
printf("\ninteiro(%d) real(%f) char(%c) s(%s)", i, d, c, s);
return 0;
}

View File

@ -1,6 +1,6 @@
#include <stdio.h>
#include <stdlib.h>
void helloWorld(void){
printf("Hello World!\n");
}
#include <stdio.h>
#include <stdlib.h>
void helloWorld(void){
printf("Hello World!\n");
}

View File

@ -1,6 +1,6 @@
#ifndef _H_TESTE
#define _H_TESTE
void helloWorld(void);
#endif
#ifndef _H_TESTE
#define _H_TESTE
void helloWorld(void);
#endif

View File

@ -1,8 +1,8 @@
#include <stdio.h>
#include <stdlib.h>
#include "helloworld.h"
int main(){
helloWorld();
return (0);
}
#include <stdio.h>
#include <stdlib.h>
#include "helloworld.h"
int main(){
helloWorld();
return (0);
}

View File

@ -1,15 +1,15 @@
# My first makefile
all: printy
printy: main.o helloworld.o
gcc -o printy main.o helloworld.o
main.o: main.c helloworld.h
gcc -o main.o main.c -c -W -Wall -ansi -pedantic
helloworld.o: helloworld.c helloworld.h
gcc -o helloworld.o helloworld.c -c -W -Wall -ansi -pedantic
clean:
rm -rf *.o *~ printy
# My first makefile
all: printy
printy: main.o helloworld.o
gcc -o printy main.o helloworld.o
main.o: main.c helloworld.h
gcc -o main.o main.c -c -W -Wall -ansi -pedantic
helloworld.o: helloworld.c helloworld.h
gcc -o helloworld.o helloworld.c -c -W -Wall -ansi -pedantic
clean:
rm -rf *.o *~ printy

View File

@ -1,6 +1,6 @@
#include <stdio.h>
int main(int argc, char *argv[]) {
printf ("Ola pessoal!!!\n\n");
return 0;
}
#include <stdio.h>
int main(int argc, char *argv[]) {
printf ("Ola pessoal!!!\n\n");
return 0;
}

View File

@ -1,13 +1,13 @@
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv){
int x = 10;
int * y = & x;
printf("\n%i", x);
printf("\n%p", &x);
printf("\n%p", y);
printf("\n%p", &y);
printf("\n%i", *y);
printf("\n");
}
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv){
int x = 10;
int * y = & x;
printf("\n%i", x);
printf("\n%p", &x);
printf("\n%p", y);
printf("\n%p", &y);
printf("\n%i", *y);
printf("\n");
}

View File

@ -1,19 +1,19 @@
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv){
int x1 = 11,
x2 = 22,
x3 = 33;
int *p;
p = &x1; //p <- o endereço de x1
x2 = *p; //x2 <- o cont. do addr apont. por p
*p = x3; //o cont. do addr apont. por p <- x3
p = &x3; //p <- o endereço de x3
*p = 0; //o cont. do addr apont. por p <- x3
printf("\ncont:%d %d %d %d", x1, x2, x3, *p);
printf("\naddr:%p %p %p %p", &x1, &x2, &x3, p);
printf("\n");
}
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv){
int x1 = 11,
x2 = 22,
x3 = 33;
int *p;
p = &x1; //p <- o endereço de x1
x2 = *p; //x2 <- o cont. do addr apont. por p
*p = x3; //o cont. do addr apont. por p <- x3
p = &x3; //p <- o endereço de x3
*p = 0; //o cont. do addr apont. por p <- x3
printf("\ncont:%d %d %d %d", x1, x2, x3, *p);
printf("\naddr:%p %p %p %p", &x1, &x2, &x3, p);
printf("\n");
}

View File

@ -1,27 +1,27 @@
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv){
int *x1;
int x2;
int *x3;
x1 = (int*) malloc (sizeof(int));
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
*x1 = 20;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
x2 = *x1;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
*x3 = x2 * *x1;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
x3 = &x2;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
x2 = 15;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
printf("\n");
}
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv){
int *x1;
int x2;
int *x3;
x1 = (int*) malloc (sizeof(int));
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
*x1 = 20;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
x2 = *x1;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
*x3 = x2 * *x1;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
x3 = &x2;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
x2 = 15;
printf("\nx1(%p)(%i)(%p) x2(%i)(%p) x3(%p)(%i)(%p)", x1, *x1, &x1, x2, &x2, x3, *x3, &x3);
printf("\n");
}

View File

@ -1,13 +1,13 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, char** argv){
double M [3][3];
double *p = M[0];
for (int i = 0; i < pow(3, 2); i++, p++){
*p=0.0;
}
}
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, char** argv){
double M [3][3];
double *p = M[0];
for (int i = 0; i < pow(3, 2); i++, p++){
*p=0.0;
}
}

View File

@ -1,26 +1,26 @@
#include <stdio.h>
#include <stdlib.h>
#define MAXTAM 10
typedef struct Cliente {
int codigo;
char nome[MAXTAM];
} Cliente;
int main (int argc, char** argv){
char* p1 = (char*) malloc (sizeof(char));
int* p2 = (int*) malloc (sizeof(int));
float* p3 = (float*) malloc (sizeof(float));
Cliente* p4 = (Cliente*) malloc (sizeof(Cliente));
int* p5 = (int*) malloc (MAXTAM * sizeof (int));
Cliente* p6 =(Cliente*) malloc (MAXTAM * sizeof (Cliente));
free(p1);
free(p2);
free(p3);
free(p4);
free(p5);
free(p6);
}
#include <stdio.h>
#include <stdlib.h>
#define MAXTAM 10
typedef struct Cliente {
int codigo;
char nome[MAXTAM];
} Cliente;
int main (int argc, char** argv){
char* p1 = (char*) malloc (sizeof(char));
int* p2 = (int*) malloc (sizeof(int));
float* p3 = (float*) malloc (sizeof(float));
Cliente* p4 = (Cliente*) malloc (sizeof(Cliente));
int* p5 = (int*) malloc (MAXTAM * sizeof (int));
Cliente* p6 =(Cliente*) malloc (MAXTAM * sizeof (Cliente));
free(p1);
free(p2);
free(p3);
free(p4);
free(p5);
free(p6);
}

View File

@ -1,26 +1,26 @@
#include <iostream>
using namespace std;
#define MAXTAM 10
typedef struct Cliente {
int codigo;
char nome[MAXTAM];
} Cliente;
int main (int argc, char** argv){
char* p1 = new char;
int* p2 = new int;
float* p3 = new float;
Cliente* p4 = new Cliente;
int* p5 = new int [MAXTAM];
Cliente* p6 = new Cliente[MAXTAM];
delete p1;
delete p2;
delete p3;
delete p4;
delete [] p5;
delete [] p6;
}
#include <iostream>
using namespace std;
#define MAXTAM 10
typedef struct Cliente {
int codigo;
char nome[MAXTAM];
} Cliente;
int main (int argc, char** argv){
char* p1 = new char;
int* p2 = new int;
float* p3 = new float;
Cliente* p4 = new Cliente;
int* p5 = new int [MAXTAM];
Cliente* p6 = new Cliente[MAXTAM];
delete p1;
delete p2;
delete p3;
delete p4;
delete [] p5;
delete [] p6;
}

View File

@ -1,24 +1,24 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXTAM 100
typedef struct Cliente {
int codigo;
char nome[MAXTAM];
} Cliente;
int main (int argc, char** argv){
Cliente registro;
Cliente* ponteiro = (Cliente*) malloc (sizeof(Cliente));
registro.codigo = 1;
strcpy(registro.nome, "AA");
printf("\nFuncionario (%i): %s", registro.codigo, registro.nome);
ponteiro->codigo = 2;
strcpy(ponteiro->nome, "BB");
printf("\nFuncionario (%i): %s", ponteiro->codigo, ponteiro->nome);
printf("\n");
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXTAM 100
typedef struct Cliente {
int codigo;
char nome[MAXTAM];
} Cliente;
int main (int argc, char** argv){
Cliente registro;
Cliente* ponteiro = (Cliente*) malloc (sizeof(Cliente));
registro.codigo = 1;
strcpy(registro.nome, "AA");
printf("\nFuncionario (%i): %s", registro.codigo, registro.nome);
ponteiro->codigo = 2;
strcpy(ponteiro->nome, "BB");
printf("\nFuncionario (%i): %s", ponteiro->codigo, ponteiro->nome);
printf("\n");
}

View File

@ -1,30 +1,30 @@
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv){
double a;
double *p, *q;
a = 3.14;
printf("%f\n", a);
p = &a;
*p = 2.718;
printf("%f\n", a);
a = 5;
printf("%f\n", *p);
p = NULL;
p = (double*) malloc(sizeof(double));
*p = 20;
q = p;
printf("%f\n", *p);
printf("%f\n", a);
free(p);
printf("%f\n", *q);
printf("\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv){
double a;
double *p, *q;
a = 3.14;
printf("%f\n", a);
p = &a;
*p = 2.718;
printf("%f\n", a);
a = 5;
printf("%f\n", *p);
p = NULL;
p = (double*) malloc(sizeof(double));
*p = 20;
q = p;
printf("%f\n", *p);
printf("%f\n", a);
free(p);
printf("%f\n", *q);
printf("\n");
return 0;
}

View File

@ -1,19 +1,19 @@
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv){
int a[10], *b;
b = a;
b[5] = 100;
printf("\n%d -- %d", a[5], b[5]);
b = (int*) malloc(10*sizeof(int));
b[7] = 100;
printf("\n%d -- %d", a[7], b[7]);
printf("\n");
//O comando a = b gera um erro de compilação
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv){
int a[10], *b;
b = a;
b[5] = 100;
printf("\n%d -- %d", a[5], b[5]);
b = (int*) malloc(10*sizeof(int));
b[7] = 100;
printf("\n%d -- %d", a[7], b[7]);
printf("\n");
//O comando a = b gera um erro de compilação
return 0;
}

View File

@ -1,40 +1,40 @@
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv){
int *x1;
int x2;
int *x3;
x1 = (int*) malloc(sizeof(int));
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
*x1 = 20;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = *x1;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
*x3 = x2 * *x1;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x3 = &x2;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 15;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 13 & 3;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 13 | 3;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 13 >> 1;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 13 << 1;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv){
int *x1;
int x2;
int *x3;
x1 = (int*) malloc(sizeof(int));
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
*x1 = 20;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = *x1;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
*x3 = x2 * *x1;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x3 = &x2;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 15;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 13 & 3;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 13 | 3;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 13 >> 1;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
x2 = 13 << 1;
printf("\nx1(%p)(%p)(%i) x2(%p)(%i) x3(%p)(%p)(%i)", &x1, x1, *x1, &x2, x2, &x3, x3, *x3);
return 0;
}

View File

@ -1,21 +1,21 @@
#include <stdio.h>
#include <stdlib.h>
#define MAXTAM 10
typedef struct Cliente {
int codigo;
char nome[MAXTAM];
} Cliente;
int main (int argc, char** argv){
Cliente c;
c.codigo = 5;
Cliente *p = NULL;
p = (Cliente*) malloc (sizeof(Cliente));
p->codigo = 6;
Cliente *p2 = &c;
p2->codigo = 7;
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define MAXTAM 10
typedef struct Cliente {
int codigo;
char nome[MAXTAM];
} Cliente;
int main (int argc, char** argv){
Cliente c;
c.codigo = 5;
Cliente *p = NULL;
p = (Cliente*) malloc (sizeof(Cliente));
p->codigo = 6;
Cliente *p2 = &c;
p2->codigo = 7;
return 0;
}

View File

@ -1,20 +1,20 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct Celula {
int elemento;
struct Celula *prox;
} Celula;
Celula *novaCelula(int elemento) {
Celula *nova = (Celula*) malloc(sizeof(Celula));
nova->elemento = elemento;
nova->prox = NULL;
return nova;
}
int main (int argc, char** argv){
Celula *tmp = novaCelula(3);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
typedef struct Celula {
int elemento;
struct Celula *prox;
} Celula;
Celula *novaCelula(int elemento) {
Celula *nova = (Celula*) malloc(sizeof(Celula));
nova->elemento = elemento;
nova->prox = NULL;
return nova;
}
int main (int argc, char** argv){
Celula *tmp = novaCelula(3);
return 0;
}

View File

@ -1,20 +1,20 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct Elemento {
int valor;
} Elemento;
int main (int argc, char** argv){
Elemento e1;
Elemento* e2 = (Elemento*) malloc (3 * sizeof (Elemento));
Elemento e3[3];
Elemento** e4 = (Elemento**) malloc(3 * sizeof(Elemento*));
e4[0] = (Elemento*) malloc(sizeof(Elemento*));
e4[2] = (Elemento*) malloc(sizeof(Elemento*));
e4[0]->valor = 7;
printf("\n%i -- %i\n", e4[0]->valor, e4[2]->valor);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
typedef struct Elemento {
int valor;
} Elemento;
int main (int argc, char** argv){
Elemento e1;
Elemento* e2 = (Elemento*) malloc (3 * sizeof (Elemento));
Elemento e3[3];
Elemento** e4 = (Elemento**) malloc(3 * sizeof(Elemento*));
e4[0] = (Elemento*) malloc(sizeof(Elemento*));
e4[2] = (Elemento*) malloc(sizeof(Elemento*));
e4[0]->valor = 7;
printf("\n%i -- %i\n", e4[0]->valor, e4[2]->valor);
return 0;
}

View File

@ -1,26 +1,26 @@
#include <stdio.h>
#include <stdlib.h>
void terceiro(){
printf("3o - inicio e fim\n");
}
void segundo(){
printf("2o - inicio\n");
terceiro();
printf("2o - fim\n");
}
void primeiro(){
printf("1o - inicio\n");
segundo();
printf("1o - fim\n");
}
int main(int argc, char *argv[]) {
printf("main - inicio\n");
primeiro();
printf("main - fim\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
void terceiro(){
printf("3o - inicio e fim\n");
}
void segundo(){
printf("2o - inicio\n");
terceiro();
printf("2o - fim\n");
}
void primeiro(){
printf("1o - inicio\n");
segundo();
printf("1o - fim\n");
}
int main(int argc, char *argv[]) {
printf("main - inicio\n");
primeiro();
printf("main - fim\n");
return 0;
}

View File

@ -1,45 +1,45 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define bool int
#define true 1
#define false 0
bool isUpper(char x){
return (x >= 'A' && x <= 'Z');
}
int contMaiusculo(char* s){
int cont = 0;
for(int i = 0; i < strlen(s); i++){
if(isUpper(s[i]) == true){
cont++;
}
}
return cont;
}
int contMaiusculoRec(char* s, int i){
int cont = 0;
if(i < strlen(s)){
if(isUpper(s[i]) == true){
cont++;
}
cont += contMaiusculoRec(s, i + 1);
}
return cont;
}
int contMaiusculoRecursivo(char* s){
return contMaiusculoRec(s, 0);
}
int main(int argc, char *argv[]) {
printf("\nAlGoritmos e Estrutudas de Dados: %i", contMaiusculo("AlGoritmos e Estruturas de Dados"));
printf("\nAlGoritmos e Estruturas de Dados: %i", contMaiusculoRecursivo("AlGoritmos e Estruturas de Dados"));
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define bool int
#define true 1
#define false 0
bool isUpper(char x){
return (x >= 'A' && x <= 'Z');
}
int contMaiusculo(char* s){
int cont = 0;
for(int i = 0; i < strlen(s); i++){
if(isUpper(s[i]) == true){
cont++;
}
}
return cont;
}
int contMaiusculoRec(char* s, int i){
int cont = 0;
if(i < strlen(s)){
if(isUpper(s[i]) == true){
cont++;
}
cont += contMaiusculoRec(s, i + 1);
}
return cont;
}
int contMaiusculoRecursivo(char* s){
return contMaiusculoRec(s, 0);
}
int main(int argc, char *argv[]) {
printf("\nAlGoritmos e Estrutudas de Dados: %i", contMaiusculo("AlGoritmos e Estruturas de Dados"));
printf("\nAlGoritmos e Estruturas de Dados: %i", contMaiusculoRecursivo("AlGoritmos e Estruturas de Dados"));
return 0;
}

View File

@ -1,18 +1,18 @@
#include <stdio.h>
#include <stdlib.h>
int fatorial(int n){
int resp;
printf("\nfat (%i)", n);
resp = (n == 1) ? 1 : n * fatorial(n-1);
printf("\nfat n(%i): %i", n, resp);
return resp;
}
int main(int argc, char *argv[]) {
int n = 5;
printf("\nFATORIAL RECURSIVO(%i): %i", n, fatorial(n));
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int fatorial(int n){
int resp;
printf("\nfat (%i)", n);
resp = (n == 1) ? 1 : n * fatorial(n-1);
printf("\nfat n(%i): %i", n, resp);
return resp;
}
int main(int argc, char *argv[]) {
int n = 5;
printf("\nFATORIAL RECURSIVO(%i): %i", n, fatorial(n));
return 0;
}

View File

@ -1,18 +1,18 @@
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int n){
int resp;
printf("\nfib (%i)", n);
resp = (n == 0 || n == 1) ? 1 : fibonacci(n-1) + fibonacci(n-2);
printf("\nfib n(%i): %i", n, resp);
return resp;
}
int main(int argc, char *argv[]) {
int n = 5;
printf("\nFIBONACCI RECURSIVO(%i): %i", n, fibonacci(n));
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int n){
int resp;
printf("\nfib (%i)", n);
resp = (n == 0 || n == 1) ? 1 : fibonacci(n-1) + fibonacci(n-2);
printf("\nfib n(%i): %i", n, resp);
return resp;
}
int main(int argc, char *argv[]) {
int n = 5;
printf("\nFIBONACCI RECURSIVO(%i): %i", n, fibonacci(n));
return 0;
}

View File

@ -1,34 +1,34 @@
#include <stdio.h>
#include <stdlib.h>
int multiplicacaoRec(int a, int b, int i){
int resp = 0;
if(i < b){
resp = a + multiplicacaoRec(a, b, i+1);
}
return resp;
}
int multiplicacao(int a, int b){
return multiplicacaoRec(a, b, 0);
}
int multiplicacaoIt(int a, int b){
int resp = 0;
for(int i = 0; i < b; i++){
resp = a + resp;
}
return resp;
}
int main(int argc, char *argv[]) {
int mult = multiplicacaoIt(4, 3);
printf("\nRESPOSTA IT: %i", mult);
mult = multiplicacao(4, 3);
printf("\nRESPOSTA REC: %i", mult);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int multiplicacaoRec(int a, int b, int i){
int resp = 0;
if(i < b){
resp = a + multiplicacaoRec(a, b, i+1);
}
return resp;
}
int multiplicacao(int a, int b){
return multiplicacaoRec(a, b, 0);
}
int multiplicacaoIt(int a, int b){
int resp = 0;
for(int i = 0; i < b; i++){
resp = a + resp;
}
return resp;
}
int main(int argc, char *argv[]) {
int mult = multiplicacaoIt(4, 3);
printf("\nRESPOSTA IT: %i", mult);
mult = multiplicacao(4, 3);
printf("\nRESPOSTA REC: %i", mult);
return 0;
}

View File

@ -1,17 +1,17 @@
#include <stdio.h>
#include <stdlib.h>
void printRecursivo(int i){
printf("\nvalor de i: %i", i);
if(i > 0){
printRecursivo(i-1);
}
printf("\nvalor de i: %i", i);
}
int main(int argc, char *argv[]) {
int n = 3;
printRecursivo(n);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
void printRecursivo(int i){
printf("\nvalor de i: %i", i);
if(i > 0){
printRecursivo(i-1);
}
printf("\nvalor de i: %i", i);
}
int main(int argc, char *argv[]) {
int n = 3;
printRecursivo(n);
return 0;
}

View File

@ -1,24 +1,24 @@
#include <stdio.h>
#define MAXTAM 100
struct Funcionario {
int matricula;
char nome[MAXTAM];
};
void main (){
struct Funcionario f;
printf("\nEntre com a matricula: ");
scanf("%d", &f.matricula);
printf("\nEntre com o nome: ");
scanf("%s", f.nome);
printf("\nMatricula: %d", f.matricula);
printf("\nNome: %s", f.nome);
printf("\n\n");
}
#include <stdio.h>
#define MAXTAM 100
struct Funcionario {
int matricula;
char nome[MAXTAM];
};
void main (){
struct Funcionario f;
printf("\nEntre com a matricula: ");
scanf("%d", &f.matricula);
printf("\nEntre com o nome: ");
scanf("%s", f.nome);
printf("\nMatricula: %d", f.matricula);
printf("\nNome: %s", f.nome);
printf("\n\n");
}

View File

@ -1,24 +1,24 @@
#include <stdio.h>
#define MAXTAM 100
struct Funcionario {
int matricula;
char nome[MAXTAM];
};
typedef struct Funcionario Funcionario;
void main (){
Funcionario f;
printf("\nEntre com a matricula: ");
scanf("%d", &f.matricula);
printf("\nEntre com o nome: ");
scanf("%s", f.nome);
printf("\nMatricula: %d", f.matricula);
printf("\nNome: %s", f.nome);
printf("\n\n");
}
#include <stdio.h>
#define MAXTAM 100
struct Funcionario {
int matricula;
char nome[MAXTAM];
};
typedef struct Funcionario Funcionario;
void main (){
Funcionario f;
printf("\nEntre com a matricula: ");
scanf("%d", &f.matricula);
printf("\nEntre com o nome: ");
scanf("%s", f.nome);
printf("\nMatricula: %d", f.matricula);
printf("\nNome: %s", f.nome);
printf("\n\n");
}

View File

@ -1,22 +1,22 @@
#include <stdio.h>
#define MAXTAM 100
typedef struct Funcionario {
int matricula;
char nome[MAXTAM];
} Funcionario;
void main (){
Funcionario f;
printf("\nEntre com a matricula: ");
scanf("%d", &f.matricula);
printf("\nEntre com o nome: ");
scanf("%s", f.nome);
printf("\nMatricula: %d", f.matricula);
printf("\nNome: %s", f.nome);
printf("\n\n");
}
#include <stdio.h>
#define MAXTAM 100
typedef struct Funcionario {
int matricula;
char nome[MAXTAM];
} Funcionario;
void main (){
Funcionario f;
printf("\nEntre com a matricula: ");
scanf("%d", &f.matricula);
printf("\nEntre com o nome: ");
scanf("%s", f.nome);
printf("\nMatricula: %d", f.matricula);
printf("\nNome: %s", f.nome);
printf("\n\n");
}

View File

@ -1,29 +1,29 @@
#include <stdio.h>
#define MAXTAM 100
struct Funcionario {
int matricula;
char nome[MAXTAM];
};
typedef struct Funcionario Funcionario;
void main (){
Funcionario vet[MAXTAM];
int n = 3;
for(int i = 0; i < n; i++){
printf("\nEntre com a matricula do funcionario %d: ", (i+1));
scanf("%d", &vet[i].matricula);
printf("\nEntre com o nome do funcionario %d: ", (i+1));
scanf("%s", vet[i].nome);
}
for(int i = 0; i < n; i++){
printf("\nMatricula do funcionario %d: %d", (i+1), vet[i].matricula);
printf("\nNome do funcionario %d: %s\n", (i+1), vet[i].nome);
}
printf("\n\n");
}
#include <stdio.h>
#define MAXTAM 100
struct Funcionario {
int matricula;
char nome[MAXTAM];
};
typedef struct Funcionario Funcionario;
void main (){
Funcionario vet[MAXTAM];
int n = 3;
for(int i = 0; i < n; i++){
printf("\nEntre com a matricula do funcionario %d: ", (i+1));
scanf("%d", &vet[i].matricula);
printf("\nEntre com o nome do funcionario %d: ", (i+1));
scanf("%s", vet[i].nome);
}
for(int i = 0; i < n; i++){
printf("\nMatricula do funcionario %d: %d", (i+1), vet[i].matricula);
printf("\nNome do funcionario %d: %s\n", (i+1), vet[i].nome);
}
printf("\n\n");
}

View File

@ -1,14 +1,14 @@
#include <stdio.h>
int main(int argc, char *argv[]) {
int a = sizeof(char),
b = sizeof(int),
c = sizeof(double),
d = sizeof(float);
printf ("Tamanho do char: %i\n", a);
printf ("Tamanho do int: %i\n", b);
printf ("Tamanho do double: %i\n", c);
printf ("Tamanho do float: %i\n", d);
return 0;
}
#include <stdio.h>
int main(int argc, char *argv[]) {
int a = sizeof(char),
b = sizeof(int),
c = sizeof(double),
d = sizeof(float);
printf ("Tamanho do char: %i\n", a);
printf ("Tamanho do int: %i\n", b);
printf ("Tamanho do double: %i\n", c);
printf ("Tamanho do float: %i\n", d);
return 0;
}

View File

@ -1,33 +1,33 @@
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
char s1[80], s2[80];
strcpy(s1, "Algoritmos");
strcpy(s2, " e Estruturas de Dados II");
printf("\nTamanho s1(%i)", (int)strlen(s1));
printf("\nTamanho s2(%i)", (int)strlen(s2));
if(!strcmp(s1, s2)) printf("\nIguais!!!");
else printf("\nDiferentes!!!");
strcat(s1, s2);
printf("\nNova s1 (%s)", s1);
strcpy(s2, s1);
printf("\nNova s2 (%s)", s2);
if(!strcmp(s1, s2)) printf("\nIguais!!!");
else printf("\nDiferentes!!!");
s1[10] = s2[10] = '\0'; s1[11] = 'a'; s2[11] = 'b';
printf("\nNova s1 (%s)", s1);
printf("\nNova s2 (%s)", s2);
if(!strcmp(s1, s2)) printf("\nIguais!!!");
else printf("\nDiferentes!!!");
return 0;
}
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
char s1[80], s2[80];
strcpy(s1, "Algoritmos");
strcpy(s2, " e Estruturas de Dados II");
printf("\nTamanho s1(%i)", (int)strlen(s1));
printf("\nTamanho s2(%i)", (int)strlen(s2));
if(!strcmp(s1, s2)) printf("\nIguais!!!");
else printf("\nDiferentes!!!");
strcat(s1, s2);
printf("\nNova s1 (%s)", s1);
strcpy(s2, s1);
printf("\nNova s2 (%s)", s2);
if(!strcmp(s1, s2)) printf("\nIguais!!!");
else printf("\nDiferentes!!!");
s1[10] = s2[10] = '\0'; s1[11] = 'a'; s2[11] = 'b';
printf("\nNova s1 (%s)", s1);
printf("\nNova s2 (%s)", s2);
if(!strcmp(s1, s2)) printf("\nIguais!!!");
else printf("\nDiferentes!!!");
return 0;
}

View File

@ -1,6 +1,6 @@
class ArgumentoMain {
public static void main (String[] args){
System.out.println("Primeiro parametro: " + args[0]);
System.out.println("Numero de parametros: " + args.length);
}
}
class ArgumentoMain {
public static void main (String[] args){
System.out.println("Primeiro parametro: " + args[0]);
System.out.println("Numero de parametros: " + args.length);
}
}

View File

@ -1,21 +1,21 @@
class ExemploArq01Escrita
{
public static void main(String[] args)
{
//Abrir o arquivo texto
Arq.openWrite("exemplo.txt");
//Escrever no arquivo texto
Arq.println(1);
Arq.println(5.3);
Arq.println('X');
Arq.println(true);
Arq.println("Algoritmos");
//Fechar o arquivo texto
Arq.close();
} // Fim main()
} // Fim class
class ExemploArq01Escrita
{
public static void main(String[] args)
{
//Abrir o arquivo texto
Arq.openWrite("exemplo.txt");
//Escrever no arquivo texto
Arq.println(1);
Arq.println(5.3);
Arq.println('X');
Arq.println(true);
Arq.println("Algoritmos");
//Fechar o arquivo texto
Arq.close();
} // Fim main()
} // Fim class

View File

@ -1,28 +1,28 @@
class ExemploArq02Leitura
{
public static void main(String[] args)
{
//Abrir o arquivo texto
Arq.openRead("exemplo.txt");
//Ler o arquivo texto
int inteiro = Arq.readInt();
double real = Arq.readDouble();
char caractere = Arq.readChar();
boolean boleano = Arq.readBoolean();
String str = Arq.readString();
//Fechar o arquivo texto
Arq.close();
//Mostrar os valores lidos na tela
MyIO.println("inteiro: " + inteiro);
MyIO.println("real: " + real);
MyIO.println("caractere: " + caractere);
MyIO.println("boleano: " + boleano);
MyIO.println("str: " + str);
} // Fim main()
} // Fim class
class ExemploArq02Leitura
{
public static void main(String[] args)
{
//Abrir o arquivo texto
Arq.openRead("exemplo.txt");
//Ler o arquivo texto
int inteiro = Arq.readInt();
double real = Arq.readDouble();
char caractere = Arq.readChar();
boolean boleano = Arq.readBoolean();
String str = Arq.readString();
//Fechar o arquivo texto
Arq.close();
//Mostrar os valores lidos na tela
MyIO.println("inteiro: " + inteiro);
MyIO.println("real: " + real);
MyIO.println("caractere: " + caractere);
MyIO.println("boleano: " + boleano);
MyIO.println("str: " + str);
} // Fim main()
} // Fim class

View File

@ -1,28 +1,28 @@
class ExemploArq02bLeitura
{
public static void main(String[] args)
{
//Abrir o arquivo texto
Arq.openRead("exemplo.txt");
//Ler o arquivo texto
int inteiro = Integer.parseInt(Arq.readLine());
double real = Double.parseDouble(Arq.readLine().replace(",","."));
char caractere = Arq.readLine().charAt(0);
boolean boleano = Boolean.parseBoolean(Arq.readLine());
String str = Arq.readLine();
//Fechar o arquivo texto
Arq.close();
//Mostrar os valores lidos na tela
MyIO.println("inteiro: " + inteiro);
MyIO.println("real: " + real);
MyIO.println("caractere: " + caractere);
MyIO.println("boleano: " + boleano);
MyIO.println("str: " + str);
} // Fim main()
} // Fim class
class ExemploArq02bLeitura
{
public static void main(String[] args)
{
//Abrir o arquivo texto
Arq.openRead("exemplo.txt");
//Ler o arquivo texto
int inteiro = Integer.parseInt(Arq.readLine());
double real = Double.parseDouble(Arq.readLine().replace(",","."));
char caractere = Arq.readLine().charAt(0);
boolean boleano = Boolean.parseBoolean(Arq.readLine());
String str = Arq.readLine();
//Fechar o arquivo texto
Arq.close();
//Mostrar os valores lidos na tela
MyIO.println("inteiro: " + inteiro);
MyIO.println("real: " + real);
MyIO.println("caractere: " + caractere);
MyIO.println("boleano: " + boleano);
MyIO.println("str: " + str);
} // Fim main()
} // Fim class

View File

@ -1,16 +1,16 @@
class ExemploArq03Exercicio {
public static void main (String[] args){
Arq.openRead("exemplo.txt");
String str = "";
while (Arq.hasNext() == true){
str += Arq.readChar();
}
Arq.close();
Arq.openWrite("copia.txt");
Arq.print(str);
Arq.close();
}
}
class ExemploArq03Exercicio {
public static void main (String[] args){
Arq.openRead("exemplo.txt");
String str = "";
while (Arq.hasNext() == true){
str += Arq.readChar();
}
Arq.close();
Arq.openWrite("copia.txt");
Arq.print(str);
Arq.close();
}
}

View File

@ -1,16 +1,16 @@
import java.io.*;
public class ExemploRAF01Escrita {
public static void main(String args[]) throws Exception {
RandomAccessFile raf = new RandomAccessFile("exemplo.txt","rw");
raf.writeInt(1);
raf.writeDouble(5.3);
raf.writeChar('X');
raf.writeBoolean(true);
raf.writeBytes("Algoritmos");
raf.close();
}
}
import java.io.*;
public class ExemploRAF01Escrita {
public static void main(String args[]) throws Exception {
RandomAccessFile raf = new RandomAccessFile("exemplo.txt","rw");
raf.writeInt(1);
raf.writeDouble(5.3);
raf.writeChar('X');
raf.writeBoolean(true);
raf.writeBytes("Algoritmos");
raf.close();
}
}

View File

@ -1,22 +1,22 @@
import java.io.*;
class ExemploRAF02Leitura {
public static void main (String[] args) throws Exception{
RandomAccessFile raf = new RandomAccessFile("exemplo.txt", "rw");
int inteiro = raf.readInt();
double real = raf.readDouble();
char caractere = raf.readChar();
boolean boleano = raf.readBoolean();
String str = raf.readLine();
raf.close();
System.out.println("inteiro: " + inteiro);
System.out.println("real: " + real);
System.out.println("caractere: " + caractere);
System.out.println("boleano: " + boleano);
System.out.println("str: " + str);
}
}
import java.io.*;
class ExemploRAF02Leitura {
public static void main (String[] args) throws Exception{
RandomAccessFile raf = new RandomAccessFile("exemplo.txt", "rw");
int inteiro = raf.readInt();
double real = raf.readDouble();
char caractere = raf.readChar();
boolean boleano = raf.readBoolean();
String str = raf.readLine();
raf.close();
System.out.println("inteiro: " + inteiro);
System.out.println("real: " + real);
System.out.println("caractere: " + caractere);
System.out.println("boleano: " + boleano);
System.out.println("str: " + str);
}
}

View File

@ -1,29 +1,29 @@
import java.io.*;
public class ExemploRAF03Cabecote {
public static void main(String args[]) throws Exception {
RandomAccessFile raf = new RandomAccessFile("exemplo.txt","rw");
raf.writeInt(1);
raf.writeDouble(5.3);
raf.writeChar('X');
raf.writeBoolean(true);
raf.writeBytes("Algoritmos");
raf.seek(0); //Retornando o cabecote para a posicao 0
System.out.println(raf.readInt()); //imprimindo o inteiro
raf.seek(12); //Setando o cabecote na posicao 12 (do caractere,
//12 = 4 do int + 8 do double)
System.out.println(raf.readChar());
raf.seek(12); //Setando o cabecote novamente na posicao 12
raf.writeChar('@'); //Substituindo o caractere
raf.seek(12);
System.out.println(raf.readChar());
raf.close();
}
}
import java.io.*;
public class ExemploRAF03Cabecote {
public static void main(String args[]) throws Exception {
RandomAccessFile raf = new RandomAccessFile("exemplo.txt","rw");
raf.writeInt(1);
raf.writeDouble(5.3);
raf.writeChar('X');
raf.writeBoolean(true);
raf.writeBytes("Algoritmos");
raf.seek(0); //Retornando o cabecote para a posicao 0
System.out.println(raf.readInt()); //imprimindo o inteiro
raf.seek(12); //Setando o cabecote na posicao 12 (do caractere,
//12 = 4 do int + 8 do double)
System.out.println(raf.readChar());
raf.seek(12); //Setando o cabecote novamente na posicao 12
raf.writeChar('@'); //Substituindo o caractere
raf.seek(12);
System.out.println(raf.readChar());
raf.close();
}
}

View File

@ -1,44 +1,44 @@
/**
* Introducao a programacao orientada por objetos
* @author Max do Val Machado
* @version 2 01/2015
*/
class Principal
{
public static void main(String[] args)
{
Retangulo r1 = new Retangulo();
Retangulo r2 = new Retangulo();
r1.lerTudo();
r1.escreverTudo();
r2.lerTudo();
r2.escreverTudo();
if (r1.comparar(r2.getB(), r2.getH()) == true){
System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao iguais!");
}else{
System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao diferentes!");
}
if (r1.comparar(r2) == true){
System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao iguais!");
}else{
System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao diferentes!");
}
if (r1.comparar(r1) == true){
System.out.println("Os retangulos " + r1.getNome() + " e " + r1.getNome() + "sao iguais!");
}else{
System.out.println("Os retangulos " + r1.getNome() + " e " + r1.getNome() + "sao diferentes!");
}
if (r2.comparar(r1) == true){
System.out.println("Os retangulos " + r2.getNome() + " e " + r1.getNome() + "sao iguais!");
}else{
System.out.println("Os retangulos " + r2.getNome() + " e " + r1.getNome() + "sao diferentes!");
}
}
}
/**
* Introducao a programacao orientada por objetos
* @author Max do Val Machado
* @version 2 01/2015
*/
class Principal
{
public static void main(String[] args)
{
Retangulo r1 = new Retangulo();
Retangulo r2 = new Retangulo();
r1.lerTudo();
r1.escreverTudo();
r2.lerTudo();
r2.escreverTudo();
if (r1.comparar(r2.getB(), r2.getH()) == true){
System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao iguais!");
}else{
System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao diferentes!");
}
if (r1.comparar(r2) == true){
System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao iguais!");
}else{
System.out.println("Os retangulos " + r1.getNome() + " e " + r2.getNome() + "sao diferentes!");
}
if (r1.comparar(r1) == true){
System.out.println("Os retangulos " + r1.getNome() + " e " + r1.getNome() + "sao iguais!");
}else{
System.out.println("Os retangulos " + r1.getNome() + " e " + r1.getNome() + "sao diferentes!");
}
if (r2.comparar(r1) == true){
System.out.println("Os retangulos " + r2.getNome() + " e " + r1.getNome() + "sao iguais!");
}else{
System.out.println("Os retangulos " + r2.getNome() + " e " + r1.getNome() + "sao diferentes!");
}
}
}

View File

@ -1,102 +1,102 @@
/**
* Introducao a programacao orientada por objetos
* @author Max do Val Machado
* @version 2 01/2015
*/
class Retangulo{
//Declaracao de variaveis
private double b, h;
private String nome;
//Construtor vazio
public Retangulo(){
this.b = this.h = 0;
this.nome = "";
}
//Construtor que recebe parametros
public Retangulo(double b, double h, String nome){
this.b = b;
this.h = h;
this.nome = nome;
}
public double getB(){
return this.b;
}
public void setB(double b){
this.b = b;
}
public double getH(){
return this.h;
}
public void setH(double h){
this.h = h;
}
public String getNome(){
return this.nome;
}
public void setNome(String nome){
this.nome = nome;
}
public void lerTudo(){
b = MyIO.readDouble("Entre com a base: ");
h = MyIO.readDouble("Entre com a altura: ");
nome = MyIO.readString("Entre com o nome: ");
}
public void escreverTudo(){
System.out.println("NOME: " + nome);
System.out.println("Base: " + b);
System.out.println("Altura: " + h);
System.out.println("Area: " + getArea());
System.out.println("Diagonal: " + getDiagonal());
System.out.println("Perimetro: " + getPerimetro());
}
//Retornar a area
public double getArea(){
return (b * h);
}
//Retornar o perimetro
public double getPerimetro(){
return ((b + h) * 2);
}
//Retornar a diagonal
public double getDiagonal(){
return Math.sqrt(b * b + h * h);
}
//Comparar
public boolean comparar(double outraB, double outraH){
boolean resp;
if (this.b == outraB && this.h == outraH){
resp = true;
}else{
resp = false;
}
return resp;
}
//Comparar
//public boolean comparar(double outraB, double outraH){
// return (this.b == outraB && this.h == outraH);
//}
//Comparar
public boolean comparar(Retangulo x){
return (this.b == x.b && this.h == x.h);
}
}
/**
* Introducao a programacao orientada por objetos
* @author Max do Val Machado
* @version 2 01/2015
*/
class Retangulo{
//Declaracao de variaveis
private double b, h;
private String nome;
//Construtor vazio
public Retangulo(){
this.b = this.h = 0;
this.nome = "";
}
//Construtor que recebe parametros
public Retangulo(double b, double h, String nome){
this.b = b;
this.h = h;
this.nome = nome;
}
public double getB(){
return this.b;
}
public void setB(double b){
this.b = b;
}
public double getH(){
return this.h;
}
public void setH(double h){
this.h = h;
}
public String getNome(){
return this.nome;
}
public void setNome(String nome){
this.nome = nome;
}
public void lerTudo(){
b = MyIO.readDouble("Entre com a base: ");
h = MyIO.readDouble("Entre com a altura: ");
nome = MyIO.readString("Entre com o nome: ");
}
public void escreverTudo(){
System.out.println("NOME: " + nome);
System.out.println("Base: " + b);
System.out.println("Altura: " + h);
System.out.println("Area: " + getArea());
System.out.println("Diagonal: " + getDiagonal());
System.out.println("Perimetro: " + getPerimetro());
}
//Retornar a area
public double getArea(){
return (b * h);
}
//Retornar o perimetro
public double getPerimetro(){
return ((b + h) * 2);
}
//Retornar a diagonal
public double getDiagonal(){
return Math.sqrt(b * b + h * h);
}
//Comparar
public boolean comparar(double outraB, double outraH){
boolean resp;
if (this.b == outraB && this.h == outraH){
resp = true;
}else{
resp = false;
}
return resp;
}
//Comparar
//public boolean comparar(double outraB, double outraH){
// return (this.b == outraB && this.h == outraH);
//}
//Comparar
public boolean comparar(Retangulo x){
return (this.b == x.b && this.h == x.h);
}
}

View File

@ -1,43 +1,43 @@
import java.io.*;
import java.nio.charset.*;
class ExemploBufferedReader {
//Declaracao da classe BufferedReader
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1")));
public static String readString(){
String s = "";
char tmp;
try{
do{
tmp = (char)in.read();
if(tmp != '\n' && tmp != ' ' && tmp != 13){
s += tmp;
}
}while(tmp != '\n' && tmp != ' ');
}catch(IOException ioe){}
return s;
}
public static void main(String [] args) throws Exception {
System.out.printf("Entre com uma palavra: ");
String str = readString();
System.out.printf("Entre com um numero inteiro: ");
int inteiro = Integer.parseInt(readString().trim());
System.out.printf("Entre com um numero real: ");
double real = Double.parseDouble(readString().trim().replace(",","."));
System.out.printf("Entre com um caractere: ");
char caractere = (char)in.read();
System.out.println("Sua str: " + str);
System.out.println("Seu inteiro: " + inteiro);
System.out.println("Seu real: " + real);
System.out.println("Seu caractere: " + caractere);
} // fim main ()
} // fim class
import java.io.*;
import java.nio.charset.*;
class ExemploBufferedReader {
//Declaracao da classe BufferedReader
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1")));
public static String readString(){
String s = "";
char tmp;
try{
do{
tmp = (char)in.read();
if(tmp != '\n' && tmp != ' ' && tmp != 13){
s += tmp;
}
}while(tmp != '\n' && tmp != ' ');
}catch(IOException ioe){}
return s;
}
public static void main(String [] args) throws Exception {
System.out.printf("Entre com uma palavra: ");
String str = readString();
System.out.printf("Entre com um numero inteiro: ");
int inteiro = Integer.parseInt(readString().trim());
System.out.printf("Entre com um numero real: ");
double real = Double.parseDouble(readString().trim().replace(",","."));
System.out.printf("Entre com um caractere: ");
char caractere = (char)in.read();
System.out.println("Sua str: " + str);
System.out.println("Seu inteiro: " + inteiro);
System.out.println("Seu real: " + real);
System.out.println("Seu caractere: " + caractere);
} // fim main ()
} // fim class

View File

@ -1,13 +1,13 @@
class ExemploMyIO {
public static void main (String[] args){
String str = MyIO.readString("Entre com uma palavra: ");
int inteiro = MyIO.readInt("Entre com um inteiro: ");
double real = MyIO.readDouble("Entre com um real: ");
char caractere = MyIO.readChar("Entre com um caractere: ");
MyIO.println("Sua string: " + str);
MyIO.println("Seu inteiro: " + inteiro);
MyIO.println("Seu real: " + real);
MyIO.println("Seu caractere: " + caractere);
}
}
class ExemploMyIO {
public static void main (String[] args){
String str = MyIO.readString("Entre com uma palavra: ");
int inteiro = MyIO.readInt("Entre com um inteiro: ");
double real = MyIO.readDouble("Entre com um real: ");
char caractere = MyIO.readChar("Entre com um caractere: ");
MyIO.println("Sua string: " + str);
MyIO.println("Seu inteiro: " + inteiro);
MyIO.println("Seu real: " + real);
MyIO.println("Seu caractere: " + caractere);
}
}

View File

@ -1,28 +1,28 @@
import java.util.*;
class ExemploScanner {
public static void main(String [] args){
//Declaracao da classe scanner
Scanner scanner = new Scanner (System.in);
System.out.printf("Entre com uma palavra: ");
String str = scanner.nextLine();
System.out.printf("Entre com um caractere: ");
char caractere = scanner.nextLine().charAt(0);
System.out.printf("Entre com um numero inteiro: ");
int inteiro = scanner.nextInt();
System.out.printf("Entre com um numero real: ");
double real = scanner.nextDouble();
System.out.println("Sua str: " + str);
System.out.println("Seu inteiro: " + inteiro);
System.out.println("Seu real: " + real);
System.out.println("Seu caractere: " + caractere);
} // fim main ()
} // fim class
import java.util.*;
class ExemploScanner {
public static void main(String [] args){
//Declaracao da classe scanner
Scanner scanner = new Scanner (System.in);
System.out.printf("Entre com uma palavra: ");
String str = scanner.nextLine();
System.out.printf("Entre com um caractere: ");
char caractere = scanner.nextLine().charAt(0);
System.out.printf("Entre com um numero inteiro: ");
int inteiro = scanner.nextInt();
System.out.printf("Entre com um numero real: ");
double real = scanner.nextDouble();
System.out.println("Sua str: " + str);
System.out.println("Seu inteiro: " + inteiro);
System.out.println("Seu real: " + real);
System.out.println("Seu caractere: " + caractere);
} // fim main ()
} // fim class

View File

@ -1,5 +1,5 @@
hoje
3000000
12.3
a
hoje
3000000
12.3
a

View File

@ -1,14 +1,14 @@
/**
* Ponteiro
* @author Max do Val Machado
* @version 2 01/2015
*/
class Ponteiro01Array {
public static void main (String[] args) {
int[] vet = new int [10];
System.out.println(vet);
vet = new int [10];
System.out.println(vet);
}
}
/**
* Ponteiro
* @author Max do Val Machado
* @version 2 01/2015
*/
class Ponteiro01Array {
public static void main (String[] args) {
int[] vet = new int [10];
System.out.println(vet);
vet = new int [10];
System.out.println(vet);
}
}

View File

@ -1,19 +1,19 @@
/**
* Ponteiro
* @author Max do Val Machado
* @version 2 01/2015
*/
class Ponteiro02PassagemTipoPrimitivo {
public static void passagemDeTipoPrimitivo(int a){
System.out.println("a: " + a);
a = 10;
System.out.println("a: " + a);
}
public static void main(String[] args) {
int x = 5;
System.out.println("x: " + x);
passagemDeTipoPrimitivo(x);
System.out.println("x: " + x);
}
}
/**
* Ponteiro
* @author Max do Val Machado
* @version 2 01/2015
*/
class Ponteiro02PassagemTipoPrimitivo {
public static void passagemDeTipoPrimitivo(int a){
System.out.println("a: " + a);
a = 10;
System.out.println("a: " + a);
}
public static void main(String[] args) {
int x = 5;
System.out.println("x: " + x);
passagemDeTipoPrimitivo(x);
System.out.println("x: " + x);
}
}

View File

@ -1,31 +1,31 @@
/**
* Ponteiro
* @author Max do Val Machado
* @version 2 01/2015
*/
class Ponteiro03PassagemArray {
public static void passangemDeArray(int[] b){
for(int i = 0; i < 5; i++){
b[i] *= 5;
System.out.println("b[" + i + "]: " + b[i]);
}
b = new int[5];
for(int i = 0; i < 5; i++){
b[i] = i;
System.out.println("b[" + i + "]: " + b[i]);
}
}
public static void main(String[] args) {
int[] y = new int [5];
for(int i = 0; i < 5; i++){
y[i] = i;
System.out.println("y[" + i + "]: " + y[i]);
}
passangemDeArray(y);
for(int i = 0; i < 5; i++){
System.out.println("y[" + i + "]: " + y[i]);
}
}
}
/**
* Ponteiro
* @author Max do Val Machado
* @version 2 01/2015
*/
class Ponteiro03PassagemArray {
public static void passangemDeArray(int[] b){
for(int i = 0; i < 5; i++){
b[i] *= 5;
System.out.println("b[" + i + "]: " + b[i]);
}
b = new int[5];
for(int i = 0; i < 5; i++){
b[i] = i;
System.out.println("b[" + i + "]: " + b[i]);
}
}
public static void main(String[] args) {
int[] y = new int [5];
for(int i = 0; i < 5; i++){
y[i] = i;
System.out.println("y[" + i + "]: " + y[i]);
}
passangemDeArray(y);
for(int i = 0; i < 5; i++){
System.out.println("y[" + i + "]: " + y[i]);
}
}
}

View File

@ -1,55 +1,55 @@
/**
* Ponteiro
* @author Max do Val Machado
* @version 3 01/2016
*/
class Cliente{
private int codigo;
private String nome;
public Cliente(){
this(0, "");
}
public Cliente(int codigo){
this(codigo, "");
}
public Cliente(int codigo, String nome){
this.codigo = codigo;
this.nome = nome;
}
public int getCodigo(){
return codigo;
}
public void setCodigo(int codigo){
this.codigo = codigo;
}
public String getNome(){
return nome;
}
public void setNome(String nome){
this.nome = nome;
}
}
class Ponteiro04Objeto {
public static void main (String[] args){
//Declarando tres ponteiros
Cliente c1 = null, c2 = null, c3 = null;
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
//Alocando areas de memoria (ou inicializando objetos) e apontando os ponteiros para tais areas
c1 = new Cliente(1, "aa");
c2 = c1;
c3 = new Cliente(2, "bb");
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
//Setando o codigo apontado por c1 e c2
c2.setCodigo(3);
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
}
}
/**
* Ponteiro
* @author Max do Val Machado
* @version 3 01/2016
*/
class Cliente{
private int codigo;
private String nome;
public Cliente(){
this(0, "");
}
public Cliente(int codigo){
this(codigo, "");
}
public Cliente(int codigo, String nome){
this.codigo = codigo;
this.nome = nome;
}
public int getCodigo(){
return codigo;
}
public void setCodigo(int codigo){
this.codigo = codigo;
}
public String getNome(){
return nome;
}
public void setNome(String nome){
this.nome = nome;
}
}
class Ponteiro04Objeto {
public static void main (String[] args){
//Declarando tres ponteiros
Cliente c1 = null, c2 = null, c3 = null;
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
//Alocando areas de memoria (ou inicializando objetos) e apontando os ponteiros para tais areas
c1 = new Cliente(1, "aa");
c2 = c1;
c3 = new Cliente(2, "bb");
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
//Setando o codigo apontado por c1 e c2
c2.setCodigo(3);
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
}
}

View File

@ -1,96 +1,96 @@
/**
* Ponteiro
* @author Max do Val Machado
* @version 3 01/2016
*/
class Cliente{
private int codigo;
private String nome;
public Cliente(){
this(0, "");
}
public Cliente(int codigo){
this(codigo, "");
}
public Cliente(int codigo, String nome){
this.codigo = codigo;
this.nome = nome;
}
public int getCodigo(){
return codigo;
}
public void setCodigo(int codigo){
this.codigo = codigo;
}
public String getNome(){
return nome;
}
public void setNome(String nome){
this.nome = nome;
}
}
class Ponteiro05PassagemObjeto {
/**
* Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o
* conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal).
* Depois, o metodo retorna o conteudo do nosso ponteiro (endereco recebido como parametro).
*/
public static Cliente setar2(Cliente y){
y.setCodigo(6);
y.setNome("ff");
System.out.println("ADDRs: y(" + y + ")");
System.out.println("ATRIBUTOs: y(" + y.getCodigo() + " / " + y.getNome()+")");
return y;
}
/**
* Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o
* conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal).
* Depois, o metodo faz com que o ponteiro corrente aponte para outro objeto (veja que c1 do metodo
* princial continua apontando para o primeiro objeto). No final, a coleta de lixo do java libera a
* area de memoria que continha o ponteiro e o objeto criados neste metodo.
*/
public static void setar1(Cliente x){
x.setCodigo(4);
x.setNome("dd");
System.out.println("ADDRs: x(" + x + ")");
System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")");
x = new Cliente (5, "ee");
System.out.println("ADDRs: x(" + x + ")");
System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")");
}
public static void main (String[] args){
//Declarando tres ponteiros
Cliente c1 = new Cliente(1, "aa");
Cliente c2 = c1;
Cliente c3 = new Cliente(2, "bb");
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
//Chamando o metodo setar1 e passando POR VALOR O ADDR de c1
setar1(c1);
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
//Chamando o metodo setar2, passando POR VALOR O ADDR DE c2 e retornando um novo endereco para C3
c3 = setar2(c2);
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
}
}
/**
* Ponteiro
* @author Max do Val Machado
* @version 3 01/2016
*/
class Cliente{
private int codigo;
private String nome;
public Cliente(){
this(0, "");
}
public Cliente(int codigo){
this(codigo, "");
}
public Cliente(int codigo, String nome){
this.codigo = codigo;
this.nome = nome;
}
public int getCodigo(){
return codigo;
}
public void setCodigo(int codigo){
this.codigo = codigo;
}
public String getNome(){
return nome;
}
public void setNome(String nome){
this.nome = nome;
}
}
class Ponteiro05PassagemObjeto {
/**
* Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o
* conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal).
* Depois, o metodo retorna o conteudo do nosso ponteiro (endereco recebido como parametro).
*/
public static Cliente setar2(Cliente y){
y.setCodigo(6);
y.setNome("ff");
System.out.println("ADDRs: y(" + y + ")");
System.out.println("ATRIBUTOs: y(" + y.getCodigo() + " / " + y.getNome()+")");
return y;
}
/**
* Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o
* conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal).
* Depois, o metodo faz com que o ponteiro corrente aponte para outro objeto (veja que c1 do metodo
* princial continua apontando para o primeiro objeto). No final, a coleta de lixo do java libera a
* area de memoria que continha o ponteiro e o objeto criados neste metodo.
*/
public static void setar1(Cliente x){
x.setCodigo(4);
x.setNome("dd");
System.out.println("ADDRs: x(" + x + ")");
System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")");
x = new Cliente (5, "ee");
System.out.println("ADDRs: x(" + x + ")");
System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")");
}
public static void main (String[] args){
//Declarando tres ponteiros
Cliente c1 = new Cliente(1, "aa");
Cliente c2 = c1;
Cliente c3 = new Cliente(2, "bb");
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
//Chamando o metodo setar1 e passando POR VALOR O ADDR de c1
setar1(c1);
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
//Chamando o metodo setar2, passando POR VALOR O ADDR DE c2 e retornando um novo endereco para C3
c3 = setar2(c2);
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
}
}

View File

@ -1,99 +1,99 @@
/**
* Ponteiro
* @author Max do Val Machado
* @version 3 01/2016
*/
class Cliente{
private int codigo;
private String nome;
public Cliente(){
this(0, "");
}
public Cliente(int codigo){
this(codigo, "");
}
public Cliente(int codigo, String nome){
this.codigo = codigo;
this.nome = nome;
}
public int getCodigo(){
return codigo;
}
public void setCodigo(int codigo){
this.codigo = codigo;
}
public String getNome(){
return nome;
}
public void setNome(String nome){
this.nome = nome;
}
public Cliente clone(){
return new Cliente(this.codigo, this.nome);
}
}
class Ponteiro06PassagemObjetoClone {
/**
* Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o
* conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal).
* Depois, o metodo retorna o conteudo do nosso ponteiro (endereco recebido como parametro).
*/
public static Cliente setar2(Cliente y){
y.setCodigo(6);
y.setNome("ff");
System.out.println("ADDRs: y(" + y + ")");
System.out.println("ATRIBUTOs: y(" + y.getCodigo() + " / " + y.getNome()+")");
return y;
}
/**
* Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o
* conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal).
* Depois, o metodo faz com que o ponteiro corrente aponte para outro objeto (veja que c1 do metodo
* princial continua apontando para o primeiro objeto). No final, a coleta de lixo do java libera a
* area de memoria que continha o ponteiro e o objeto criados neste metodo.
*/
public static void setar1(Cliente x){
x.setCodigo(4);
x.setNome("dd");
System.out.println("ADDRs: x(" + x + ")");
System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")");
x = new Cliente (5, "ee");
System.out.println("ADDRs: x(" + x + ")");
System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")");
}
public static void main (String[] args){
//Declarando tres ponteiros
Cliente c1 = new Cliente(1, "aa");
Cliente c2 = c1.clone();
Cliente c3 = new Cliente(2, "bb");
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
//Chamando o metodo setar1 e passando POR VALOR O ADDR de c1
setar1(c1);
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
//Chamando o metodo setar2, passando POR VALOR O ADDR DE c2 e retornando um novo endereco para C3
c3 = setar2(c2);
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
}
}
/**
* Ponteiro
* @author Max do Val Machado
* @version 3 01/2016
*/
class Cliente{
private int codigo;
private String nome;
public Cliente(){
this(0, "");
}
public Cliente(int codigo){
this(codigo, "");
}
public Cliente(int codigo, String nome){
this.codigo = codigo;
this.nome = nome;
}
public int getCodigo(){
return codigo;
}
public void setCodigo(int codigo){
this.codigo = codigo;
}
public String getNome(){
return nome;
}
public void setNome(String nome){
this.nome = nome;
}
public Cliente clone(){
return new Cliente(this.codigo, this.nome);
}
}
class Ponteiro06PassagemObjetoClone {
/**
* Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o
* conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal).
* Depois, o metodo retorna o conteudo do nosso ponteiro (endereco recebido como parametro).
*/
public static Cliente setar2(Cliente y){
y.setCodigo(6);
y.setNome("ff");
System.out.println("ADDRs: y(" + y + ")");
System.out.println("ATRIBUTOs: y(" + y.getCodigo() + " / " + y.getNome()+")");
return y;
}
/**
* Metodo que recebe um ponteiro contendo o endereco de um objeto. Em seguida, o metodo altera o
* conteudo do objeto apontado pelo ponteiro (o mesmo objeto apontado por c1 no metodo principal).
* Depois, o metodo faz com que o ponteiro corrente aponte para outro objeto (veja que c1 do metodo
* princial continua apontando para o primeiro objeto). No final, a coleta de lixo do java libera a
* area de memoria que continha o ponteiro e o objeto criados neste metodo.
*/
public static void setar1(Cliente x){
x.setCodigo(4);
x.setNome("dd");
System.out.println("ADDRs: x(" + x + ")");
System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")");
x = new Cliente (5, "ee");
System.out.println("ADDRs: x(" + x + ")");
System.out.println("ATRIBUTOs: x(" + x.getCodigo() + " / " + x.getNome()+")");
}
public static void main (String[] args){
//Declarando tres ponteiros
Cliente c1 = new Cliente(1, "aa");
Cliente c2 = c1.clone();
Cliente c3 = new Cliente(2, "bb");
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
//Chamando o metodo setar1 e passando POR VALOR O ADDR de c1
setar1(c1);
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
//Chamando o metodo setar2, passando POR VALOR O ADDR DE c2 e retornando um novo endereco para C3
c3 = setar2(c2);
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
}
}

View File

@ -1,58 +1,58 @@
/**
* Ponteiro
* @author Max do Val Machado
* @version 3 01/2016
*/
class Cliente{
private int codigo;
private String nome;
public Cliente(){
this(0, "");
}
public Cliente(int codigo){
this(codigo, "");
}
public Cliente(int codigo, String nome){
this.codigo = codigo;
this.nome = nome;
}
public int getCodigo(){
return codigo;
}
public void setCodigo(int codigo){
this.codigo = codigo;
}
public String getNome(){
return nome;
}
public void setNome(String nome){
this.nome = nome;
}
public Cliente clone(){
return new Cliente(this.codigo, this.nome);
}
}
class Ponteiro07ObjetoClone {
public static void main (String[] args){
//Declarando tres ponteiros
Cliente c1 = null, c2 = null, c3 = null;
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
//Alocando areas de memoria (ou inicializando objetos) e apontando os ponteiros para tais areas
c1 = new Cliente(1, "aa");
c2 = c1;
c3 = new Cliente(2, "bb");
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
//Setando o codigo apontado por c1 e c2
c2.setCodigo(3);
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
}
}
/**
* Ponteiro
* @author Max do Val Machado
* @version 3 01/2016
*/
class Cliente{
private int codigo;
private String nome;
public Cliente(){
this(0, "");
}
public Cliente(int codigo){
this(codigo, "");
}
public Cliente(int codigo, String nome){
this.codigo = codigo;
this.nome = nome;
}
public int getCodigo(){
return codigo;
}
public void setCodigo(int codigo){
this.codigo = codigo;
}
public String getNome(){
return nome;
}
public void setNome(String nome){
this.nome = nome;
}
public Cliente clone(){
return new Cliente(this.codigo, this.nome);
}
}
class Ponteiro07ObjetoClone {
public static void main (String[] args){
//Declarando tres ponteiros
Cliente c1 = null, c2 = null, c3 = null;
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
//Alocando areas de memoria (ou inicializando objetos) e apontando os ponteiros para tais areas
c1 = new Cliente(1, "aa");
c2 = c1;
c3 = new Cliente(2, "bb");
System.out.println("ADDRs: c1(" + c1 + ")\tc2(" + c2 + ")\tc3(" + c3 + ")");
//Setando o codigo apontado por c1 e c2
c2.setCodigo(3);
System.out.println("ATRIBUTOs:");
System.out.println("c1(" + c1.getCodigo() + " / " + c1.getNome()+")");
System.out.println("c2(" + c2.getCodigo() + " / " + c2.getNome()+")");
System.out.println("c3(" + c3.getCodigo() + " / " + c3.getNome()+")");
}
}

View File

@ -1,20 +1,20 @@
class ChamandoMetodo {
public static void primeiro(){
System.out.println("1o - inicio");
segundo();
System.out.println("1o - fim");
}
public static void segundo(){
System.out.println("2o - inicio");
terceiro();
System.out.println("2o - fim");
}
public static void terceiro(){
System.out.println("3o - inicio e fim");
}
public static void main (String[] args){
System.out.println("main - inicio");
primeiro();
System.out.println("main - fim");
}
}
class ChamandoMetodo {
public static void primeiro(){
System.out.println("1o - inicio");
segundo();
System.out.println("1o - fim");
}
public static void segundo(){
System.out.println("2o - inicio");
terceiro();
System.out.println("2o - fim");
}
public static void terceiro(){
System.out.println("3o - inicio e fim");
}
public static void main (String[] args){
System.out.println("main - inicio");
primeiro();
System.out.println("main - fim");
}
}

View File

@ -1,40 +1,40 @@
/**
* Recursividade
* @author Max do Val Machado
* @version 2 01/2015
*/
class ContarMaiuscula {
public static boolean isUpper(char x){
return (x >= 'A' && x <= 'Z');
}
public static int contMaiusculo(String s){
int cont = 0;
for(int i = 0; i < s.length(); i++){
if(isUpper(s.charAt(i)) == true){
cont++;
}
}
return cont;
}
public static int contMaiusculo2(String s){
return contMaiusculo2(s, 0);
}
public static int contMaiusculo2(String s, int i){
int cont = 0;
if(i < s.length()){
if(isUpper(s.charAt(i)) == true){
cont++;
}
cont += contMaiusculo2(s, i + 1);
}
return cont;
}
public static void main (String[] args){
System.out.println("AlGoritmos e Estruturas de Dados: " + contMaiusculo("AlGoritmos e Estruturas de Dados"));
System.out.println("AlGoritmos e Estruturas de Dados: " + contMaiusculo2("AlGoritmos e Estruturas de Dados"));
}
}
/**
* Recursividade
* @author Max do Val Machado
* @version 2 01/2015
*/
class ContarMaiuscula {
public static boolean isUpper(char x){
return (x >= 'A' && x <= 'Z');
}
public static int contMaiusculo(String s){
int cont = 0;
for(int i = 0; i < s.length(); i++){
if(isUpper(s.charAt(i)) == true){
cont++;
}
}
return cont;
}
public static int contMaiusculo2(String s){
return contMaiusculo2(s, 0);
}
public static int contMaiusculo2(String s, int i){
int cont = 0;
if(i < s.length()){
if(isUpper(s.charAt(i)) == true){
cont++;
}
cont += contMaiusculo2(s, i + 1);
}
return cont;
}
public static void main (String[] args){
System.out.println("AlGoritmos e Estruturas de Dados: " + contMaiusculo("AlGoritmos e Estruturas de Dados"));
System.out.println("AlGoritmos e Estruturas de Dados: " + contMaiusculo2("AlGoritmos e Estruturas de Dados"));
}
}

View File

@ -1,20 +1,20 @@
/**
* Recursividade
* @author Max do Val Machado
* @version 2 01/2015
*/
class FatorialRecursivo{
public static int fatorial(int n){
int resp;
System.out.println("fat (" + n + ")");
resp = (n == 1) ? 1 : n * fatorial(n-1);
System.out.println("fat n(" + n + "): " + resp);
return resp;
}
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
System.out.println("FATORIAL RECURSIVO(" + n + "): " + fatorial(n));
}
}
/**
* Recursividade
* @author Max do Val Machado
* @version 2 01/2015
*/
class FatorialRecursivo{
public static int fatorial(int n){
int resp;
System.out.println("fat (" + n + ")");
resp = (n == 1) ? 1 : n * fatorial(n-1);
System.out.println("fat n(" + n + "): " + resp);
return resp;
}
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
System.out.println("FATORIAL RECURSIVO(" + n + "): " + fatorial(n));
}
}

View File

@ -1,18 +1,18 @@
/**
* Recursividade
* @author Max do Val Machado
* @version 2 01/2015
*/
class FibonacciRecursivo {
public static int fibRec (int n){
int resp;
System.out.println("fib (" + n + ")");
resp = (n == 0 || n == 1) ? 1 : fibRec(n-1) + fibRec(n-2);
System.out.println("fib (" + n + "): " + resp);
return resp;
}
public static void main (String[] args){
int n = Integer.parseInt(args[0]);
System.out.println("FIBONACCI RECURSIVO(" + n + "): " + fibRec(n));
}
}
/**
* Recursividade
* @author Max do Val Machado
* @version 2 01/2015
*/
class FibonacciRecursivo {
public static int fibRec (int n){
int resp;
System.out.println("fib (" + n + ")");
resp = (n == 0 || n == 1) ? 1 : fibRec(n-1) + fibRec(n-2);
System.out.println("fib (" + n + "): " + resp);
return resp;
}
public static void main (String[] args){
int n = Integer.parseInt(args[0]);
System.out.println("FIBONACCI RECURSIVO(" + n + "): " + fibRec(n));
}
}

View File

@ -1,31 +1,31 @@
class Multiplicacao {
public static int multiplicacao(int a, int b){
return multiplicacao(a, b, 0);
}
public static int multiplicacao(int a, int b, int i){
int resp = 0;
if(i < b){
resp = a + multiplicacao(a, b, i+1);
}
return resp;
}
public static int multiplicacaoInt(int a, int b){
int resp = 0;
for(int i = 0; i < b; i++){
resp = a + resp;
}
return resp;
}
public static void main (String[] args){
int mult = multiplicacaoInt(4, 3);
System.out.println("RESPOSTA INT: " + mult);
mult = multiplicacao(4, 3);
System.out.println("RESPOSTA REC: " + mult);
}
}
class Multiplicacao {
public static int multiplicacao(int a, int b){
return multiplicacao(a, b, 0);
}
public static int multiplicacao(int a, int b, int i){
int resp = 0;
if(i < b){
resp = a + multiplicacao(a, b, i+1);
}
return resp;
}
public static int multiplicacaoInt(int a, int b){
int resp = 0;
for(int i = 0; i < b; i++){
resp = a + resp;
}
return resp;
}
public static void main (String[] args){
int mult = multiplicacaoInt(4, 3);
System.out.println("RESPOSTA INT: " + mult);
mult = multiplicacao(4, 3);
System.out.println("RESPOSTA REC: " + mult);
}
}

View File

@ -1,18 +1,18 @@
/**
* Recursividade
* @author Max do Val Machado
* @version 2 01/2015
*/
class PrintRecursivo{
public static void printRecursivo(int i){
System.out.println("valor de i: " + i);
if(i > 0){
printRecursivo(i-1);
}
System.out.println("valor de i: " + i);
}
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
printRecursivo(n);
}
}
/**
* Recursividade
* @author Max do Val Machado
* @version 2 01/2015
*/
class PrintRecursivo{
public static void printRecursivo(int i){
System.out.println("valor de i: " + i);
if(i > 0){
printRecursivo(i-1);
}
System.out.println("valor de i: " + i);
}
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
printRecursivo(n);
}
}

View File

@ -1,12 +1,12 @@
/**
* Tratamento de excecao
* @author Max do Val Machado
* @version 2 01/2015
*/
public class TratamentoExcecao01 {
public static void main(String[] args) {
Integer i = new Integer(args[0]);
MyIO.println("A variavel i vale " + i);
MyIO.println("FIM DE PROGRAMA!!!");
}
}
/**
* Tratamento de excecao
* @author Max do Val Machado
* @version 2 01/2015
*/
public class TratamentoExcecao01 {
public static void main(String[] args) {
Integer i = new Integer(args[0]);
MyIO.println("A variavel i vale " + i);
MyIO.println("FIM DE PROGRAMA!!!");
}
}

View File

@ -1,19 +1,19 @@
/**
* Tratamento de excecao
* @author Max do Val Machado
* @version 2 01/2015
*/
public class TratamentoExcecao02 {
public static void main(String[] args) {
try {
Integer i = new Integer(args[0]);
MyIO.println("A variavel i vale " + i);
} catch (ArrayIndexOutOfBoundsException e){
MyIO.println("Erro na passagem de parametros!!!");
} finally {
MyIO.println("FIM DE PROGRAMA!!!");
}
}
}
/**
* Tratamento de excecao
* @author Max do Val Machado
* @version 2 01/2015
*/
public class TratamentoExcecao02 {
public static void main(String[] args) {
try {
Integer i = new Integer(args[0]);
MyIO.println("A variavel i vale " + i);
} catch (ArrayIndexOutOfBoundsException e){
MyIO.println("Erro na passagem de parametros!!!");
} finally {
MyIO.println("FIM DE PROGRAMA!!!");
}
}
}

View File

@ -1,22 +1,22 @@
/**
* Tratamento de excecao
* @author Max do Val Machado
* @version 2 01/2015
*/
public class TratamentoExcecao03 {
public static void main(String[] args) {
try {
Integer i = new Integer(args[0]);
MyIO.println("A variavel i vale " + i);
} catch (NumberFormatException e) {
MyIO.println("Erro de formatacao!!!");
} catch (ArrayIndexOutOfBoundsException e){
MyIO.println("Erro na passagem de parametros!!!");
} finally {
MyIO.println("FIM DE PROGRAMA!!!");
}
}
}
/**
* Tratamento de excecao
* @author Max do Val Machado
* @version 2 01/2015
*/
public class TratamentoExcecao03 {
public static void main(String[] args) {
try {
Integer i = new Integer(args[0]);
MyIO.println("A variavel i vale " + i);
} catch (NumberFormatException e) {
MyIO.println("Erro de formatacao!!!");
} catch (ArrayIndexOutOfBoundsException e){
MyIO.println("Erro na passagem de parametros!!!");
} finally {
MyIO.println("FIM DE PROGRAMA!!!");
}
}
}

View File

@ -1,37 +1,37 @@
/**
* Tratamento de excecao
* @author Max do Val Machado
* @version 2 01/2015
*/
public class TratamentoExcecao04 {
public static void metodo1(String s) throws NumberFormatException, ArrayIndexOutOfBoundsException {
Integer i = new Integer(s);
MyIO.println("A variavel i vale " + i);
}
public static void metodo2(String s) throws NumberFormatException {
Integer i = new Integer(s);
MyIO.println("A variavel i vale " + i);
}
public static void main(String[] args) {
try {
metodo1(args[0]);
} catch (NumberFormatException e) {
MyIO.println("Erro!!!");
} catch (ArrayIndexOutOfBoundsException e){
MyIO.println("Erro!!!");
}
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
try {
metodo2(args[0]);
} catch (NumberFormatException e) {
MyIO.println("Erro!!!");
}
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
}
}
/**
* Tratamento de excecao
* @author Max do Val Machado
* @version 2 01/2015
*/
public class TratamentoExcecao04 {
public static void metodo1(String s) throws NumberFormatException, ArrayIndexOutOfBoundsException {
Integer i = new Integer(s);
MyIO.println("A variavel i vale " + i);
}
public static void metodo2(String s) throws NumberFormatException {
Integer i = new Integer(s);
MyIO.println("A variavel i vale " + i);
}
public static void main(String[] args) {
try {
metodo1(args[0]);
} catch (NumberFormatException e) {
MyIO.println("Erro!!!");
} catch (ArrayIndexOutOfBoundsException e){
MyIO.println("Erro!!!");
}
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
try {
metodo2(args[0]);
} catch (NumberFormatException e) {
MyIO.println("Erro!!!");
}
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
}
}

View File

@ -1,22 +1,22 @@
/**
* Tratamento de excecao
* @author Max do Val Machado
* @version 2 01/2015
*/
public class TratamentoExcecao05 {
public static void metodo(int i) throws Exception {
if(i % 2 == 1){
throw new Exception ("Valor impar");
}
}
public static void main(String[] args) throws Exception {
int i = 2;
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
metodo(i);
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
metodo(++i);
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
}
}
/**
* Tratamento de excecao
* @author Max do Val Machado
* @version 2 01/2015
*/
public class TratamentoExcecao05 {
public static void metodo(int i) throws Exception {
if(i % 2 == 1){
throw new Exception ("Valor impar");
}
}
public static void main(String[] args) throws Exception {
int i = 2;
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
metodo(i);
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
metodo(++i);
MyIO.println("-------------->>>>>>>> <<<<<<<<--------------");
}
}

View File

@ -1,2 +1,2 @@
# U1 - Introdução
Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II
# U1 - Introdução
Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II

View File

@ -1,19 +1,19 @@
class AND_OR {
public static boolean m1(){
System.out.println("m1");
return true;
}
public static boolean m2(){
System.out.println("m2");
return false;
}
public static void main (String[] args) {
System.out.println("=====================");
boolean or = m1() || m2();
System.out.println("OR: " + or);
System.out.println("=====================");
boolean and = m2() && m1();
System.out.println("AND: " + and);
System.out.println("=====================");
}
}
class AND_OR {
public static boolean m1(){
System.out.println("m1");
return true;
}
public static boolean m2(){
System.out.println("m2");
return false;
}
public static void main (String[] args) {
System.out.println("=====================");
boolean or = m1() || m2();
System.out.println("OR: " + or);
System.out.println("=====================");
boolean and = m2() && m1();
System.out.println("AND: " + and);
System.out.println("=====================");
}
}

View File

@ -1,17 +1,17 @@
class Log {
public static void main (String[] args) {
int[] n = {4,5,6,7,8,9,10,11,12,13,14,15,16,17,31,32,33,63,64,65};
int cont;
for(int k = 0; k < n.length; k++){
System.out.print("\n[n = " + n[k] + "] => ");
cont = 0;
for(int i = n[k]; i > 0; i /= 2){
System.out.print(" " + i);
cont++;
}
System.out.print(" (" + cont + " vezes)");
}
System.out.print("\n");
}
}
class Log {
public static void main (String[] args) {
int[] n = {4,5,6,7,8,9,10,11,12,13,14,15,16,17,31,32,33,63,64,65};
int cont;
for(int k = 0; k < n.length; k++){
System.out.print("\n[n = " + n[k] + "] => ");
cont = 0;
for(int i = n[k]; i > 0; i /= 2){
System.out.print(" " + i);
cont++;
}
System.out.print(" (" + cont + " vezes)");
}
System.out.print("\n");
}
}

View File

@ -1,61 +1,61 @@
class Pesquisa {
public static boolean pesqSeq(int[] vet, int x){
boolean resp = false;
int n = vet.length;
for(int i = 0; i < n; i++){
if(vet[i] == x){
resp = true;
i = n;
}
}
return resp;
}
public static boolean pesqBin(int[] vet, int x){
boolean resp = false;
int dir = (vet.length - 1), esq = 0, meio;
while (esq <= dir){
meio = (esq + dir) / 2;
if(x == vet[meio]){
resp = true;
esq = dir + 1;
} else if (x > vet[meio]) {
esq = meio + 1;
} else {
dir = meio - 1;
}
}
return resp;
}
public static boolean pesqBinRec(int[] vet, int x){
return pesqBinRec(vet, x, 0, (vet.length - 1));
}
public static boolean pesqBinRec(int[] vet, int x, int esq, int dir){
boolean resp;
int meio = (esq + dir) / 2;
if(esq > dir) {
resp = false;
} else if(x == vet[meio]){
resp = true;
} else if (x > vet[meio]) {
resp = pesqBinRec(vet, x, meio + 1, dir);
} else {
resp = pesqBinRec(vet, x, esq, meio - 1);
}
return resp;
}
public static void main (String[] args){
int[] vet = {2, 3, 5, 7, 9, 11, 15, 17, 20, 21, 30, 43, 49, 70, 71, 82};
int x = 35;
System.out.println("Pesquisa Sequencial: " + pesqSeq(vet, x));
System.out.println("Pesquisa Binária: " + pesqBin(vet, x));
System.out.println("Pesquisa Binária Recursiva: " + pesqBinRec(vet, x));
}
}
class Pesquisa {
public static boolean pesqSeq(int[] vet, int x){
boolean resp = false;
int n = vet.length;
for(int i = 0; i < n; i++){
if(vet[i] == x){
resp = true;
i = n;
}
}
return resp;
}
public static boolean pesqBin(int[] vet, int x){
boolean resp = false;
int dir = (vet.length - 1), esq = 0, meio;
while (esq <= dir){
meio = (esq + dir) / 2;
if(x == vet[meio]){
resp = true;
esq = dir + 1;
} else if (x > vet[meio]) {
esq = meio + 1;
} else {
dir = meio - 1;
}
}
return resp;
}
public static boolean pesqBinRec(int[] vet, int x){
return pesqBinRec(vet, x, 0, (vet.length - 1));
}
public static boolean pesqBinRec(int[] vet, int x, int esq, int dir){
boolean resp;
int meio = (esq + dir) / 2;
if(esq > dir) {
resp = false;
} else if(x == vet[meio]){
resp = true;
} else if (x > vet[meio]) {
resp = pesqBinRec(vet, x, meio + 1, dir);
} else {
resp = pesqBinRec(vet, x, esq, meio - 1);
}
return resp;
}
public static void main (String[] args){
int[] vet = {2, 3, 5, 7, 9, 11, 15, 17, 20, 21, 30, 43, 49, 70, 71, 82};
int x = 35;
System.out.println("Pesquisa Sequencial: " + pesqSeq(vet, x));
System.out.println("Pesquisa Binária: " + pesqBin(vet, x));
System.out.println("Pesquisa Binária Recursiva: " + pesqBinRec(vet, x));
}
}

View File

@ -1,2 +1,2 @@
# U2 - Somatórios
Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II
# U2 - Somatórios
Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II

View File

@ -1,2 +1,2 @@
# U3 - Fundamentos de análise de algoritmos
Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II
# U3 - Fundamentos de análise de algoritmos
Repositório de códigos da disciplina de Algoritmos e Estrutura de Dados II

View File

@ -1,14 +1,14 @@
# U4 - Ordenação em memória principal
## Exemplo de como compilar o código
```
gcc -I. bolha_teste.c -o bolha_teste
```
## Exemplo de como executar o código
```
.\bolha_teste.exe 10
```
# U4 - Ordenação em memória principal
## Exemplo de como compilar o código
```
gcc -I. bolha_teste.c -o bolha_teste
```
## Exemplo de como executar o código
```
.\bolha_teste.exe 10
```

View File

@ -1,14 +1,14 @@
#include "geracao.h"
#include "bolha.h"
//=============================================================================
void bolha(int *array, int n){
int i, j;
for (i = (n - 1); i > 0; i--) {
for (j = 0; j < i; j++) {
if (array[j] > array[j + 1]) {
swap(&array[j], &array[j + 1]);
}
}
}
}
//=============================================================================
#include "geracao.h"
#include "bolha.h"
//=============================================================================
void bolha(int *array, int n){
int i, j;
for (i = (n - 1); i > 0; i--) {
for (j = 0; j < i; j++) {
if (array[j] > array[j + 1]) {
swap(&array[j], &array[j + 1]);
}
}
}
}
//=============================================================================

View File

@ -1,6 +1,6 @@
#ifndef BOLHA_H
#define BOLHA_H
//=============================================================================
void bolha(int *array, int n);
//=============================================================================
#endif
#ifndef BOLHA_H
#define BOLHA_H
//=============================================================================
void bolha(int *array, int n);
//=============================================================================
#endif

View File

@ -1,36 +1,36 @@
#include "geracao.h"
#include "countingsort.h"
//=============================================================================
int getMaior(int *array, int n) {
int maior = array[0];
for (int i = 0; i < n; i++) {
if(maior < array[i]){
maior = array[i];
}
}
return maior;
}
//=============================================================================
void countingsort(int *array, int n) {
//Array para contar o numero de ocorrencias de cada elemento
int tamCount = getMaior(array, n) + 1;
int count[tamCount];
int ordenado[n];
//Inicializar cada posicao do array de contagem
for (int i = 0; i < tamCount; count[i] = 0, i++);
//Agora, o count[i] contem o numero de elemento iguais a i
for (int i = 0; i < n; count[array[i]]++, i++);
//Agora, o count[i] contem o numero de elemento menores ou iguais a i
for(int i = 1; i < tamCount; count[i] += count[i-1], i++);
//Ordenando
for(int i = n-1; i >= 0; ordenado[count[array[i]]-1] = array[i], count[array[i]]--, i--);
//Copiando para o array original
for(int i = 0; i < n; array[i] = ordenado[i], i++);
}
//=============================================================================
#include "geracao.h"
#include "countingsort.h"
//=============================================================================
int getMaior(int *array, int n) {
int maior = array[0];
for (int i = 0; i < n; i++) {
if(maior < array[i]){
maior = array[i];
}
}
return maior;
}
//=============================================================================
void countingsort(int *array, int n) {
//Array para contar o numero de ocorrencias de cada elemento
int tamCount = getMaior(array, n) + 1;
int count[tamCount];
int ordenado[n];
//Inicializar cada posicao do array de contagem
for (int i = 0; i < tamCount; count[i] = 0, i++);
//Agora, o count[i] contem o numero de elemento iguais a i
for (int i = 0; i < n; count[array[i]]++, i++);
//Agora, o count[i] contem o numero de elemento menores ou iguais a i
for(int i = 1; i < tamCount; count[i] += count[i-1], i++);
//Ordenando
for(int i = n-1; i >= 0; ordenado[count[array[i]]-1] = array[i], count[array[i]]--, i--);
//Copiando para o array original
for(int i = 0; i < n; array[i] = ordenado[i], i++);
}
//=============================================================================

View File

@ -1,8 +1,8 @@
#ifndef COUNTINGSORT_H
#define COUNTINGSORT_H
//=============================================================================
int getMaior(int *array, int n);
//=============================================================================
void countingsort(int *array, int n);
//=============================================================================
#endif
#ifndef COUNTINGSORT_H
#define COUNTINGSORT_H
//=============================================================================
int getMaior(int *array, int n);
//=============================================================================
void countingsort(int *array, int n);
//=============================================================================
#endif

View File

@ -1,70 +1,70 @@
#include "geracao.h"
//=============================================================================
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
//=============================================================================
// PROCEDIMENTO PARA TROCAR DOIS ELEMENTOS DO VETOR
void swap(int *i, int *j) {
int temp = *i;
*i = *j;
*j = temp;
}
//=============================================================================
// PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS EM ORDEM CRESCENTE
void crescente(int *array, int n) {
for (int i = 0; i < n; i++) {
array[i] = i;
}
}
//=============================================================================
// PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS EM ORDEM DECRESCENTE
void decrescente(int *array, int n) {
for (int i = 0; i < n; i++) {
array[i] = n - 1 - i;
}
}
//=============================================================================
// PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS EM ORDEM ALEATORIA
void aleatorio(int *array, int n) {
crescente(array, n);
srand(time(NULL));
for (int i = 0; i < n; i++) {
swap(&array[i], &array[rand() % n]);
}
}
//=============================================================================
// PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS DA ENTRADA PADRAO
int entradaPadrao(int *array) {
int n;
scanf("%i", &n);
array = (int*) malloc(n*sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%i", &array[i]);
}
return n;
}
//=============================================================================
// PROCEDIMENTO PARA EXIBIR OS DADOS PRESENTES NO ARRANJO
void mostrar(int *array, int n) {
printf("[ ");
for (int i = 0; i < n; i++) {
printf("%d ", array[i]);
}
printf("] \n");
}
//=============================================================================
// PROCEDIMENTO PARA VERIFICAR SE O ARRANJO ESTA ORDENADO
bool isOrdenado(int *array, int n){
bool resp = true;
for(int i = 1; i < n; i++){
if(array[i-1] > array[i]){
i = n;
resp = false;
}
}
return resp;
}
//=============================================================================
#include "geracao.h"
//=============================================================================
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
//=============================================================================
// PROCEDIMENTO PARA TROCAR DOIS ELEMENTOS DO VETOR
void swap(int *i, int *j) {
int temp = *i;
*i = *j;
*j = temp;
}
//=============================================================================
// PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS EM ORDEM CRESCENTE
void crescente(int *array, int n) {
for (int i = 0; i < n; i++) {
array[i] = i;
}
}
//=============================================================================
// PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS EM ORDEM DECRESCENTE
void decrescente(int *array, int n) {
for (int i = 0; i < n; i++) {
array[i] = n - 1 - i;
}
}
//=============================================================================
// PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS EM ORDEM ALEATORIA
void aleatorio(int *array, int n) {
crescente(array, n);
srand(time(NULL));
for (int i = 0; i < n; i++) {
swap(&array[i], &array[rand() % n]);
}
}
//=============================================================================
// PROCEDIMENTO PARA PREENCHER UM ARRANJO COM ELEMENTOS DA ENTRADA PADRAO
int entradaPadrao(int *array) {
int n;
scanf("%i", &n);
array = (int*) malloc(n*sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%i", &array[i]);
}
return n;
}
//=============================================================================
// PROCEDIMENTO PARA EXIBIR OS DADOS PRESENTES NO ARRANJO
void mostrar(int *array, int n) {
printf("[ ");
for (int i = 0; i < n; i++) {
printf("%d ", array[i]);
}
printf("] \n");
}
//=============================================================================
// PROCEDIMENTO PARA VERIFICAR SE O ARRANJO ESTA ORDENADO
bool isOrdenado(int *array, int n){
bool resp = true;
for(int i = 1; i < n; i++){
if(array[i-1] > array[i]){
i = n;
resp = false;
}
}
return resp;
}
//=============================================================================

View File

@ -1,18 +1,18 @@
#ifndef GERACAO_H
#define GERACAO_H
//=============================================================================
#include <stdbool.h>
//=============================================================================
void swap(int *i, int *j);
//=============================================================================
void crescente(int *array, int n);
//=============================================================================
void decrescente(int *array, int n);
//=============================================================================
void aleatorio(int *array, int n);
//=============================================================================
void mostrar(int *array, int n);
//=============================================================================
bool isOrdenado(int *array, int n);
//=============================================================================
#endif
#ifndef GERACAO_H
#define GERACAO_H
//=============================================================================
#include <stdbool.h>
//=============================================================================
void swap(int *i, int *j);
//=============================================================================
void crescente(int *array, int n);
//=============================================================================
void decrescente(int *array, int n);
//=============================================================================
void aleatorio(int *array, int n);
//=============================================================================
void mostrar(int *array, int n);
//=============================================================================
bool isOrdenado(int *array, int n);
//=============================================================================
#endif

View File

@ -1,56 +1,56 @@
#include "heapsort.h"
//=============================================================================
void construir(int *array, int tamHeap){
for(int i = tamHeap; i > 1 && array[i] > array[i/2]; i /= 2){
swap(array + i, array + i/2);
}
}
//=============================================================================
int getMaiorFilho(int *array, int i, int tamHeap){
int filho;
if (2*i == tamHeap || array[2*i] > array[2*i+1]){
filho = 2*i;
} else {
filho = 2*i + 1;
}
return filho;
}
//=============================================================================
void reconstruir(int *array, int tamHeap){
int i = 1;
while(i <= (tamHeap/2)){
int filho = getMaiorFilho(array, i, tamHeap);
if(array[i] < array[filho]){
swap(array + i, array + filho);
i = filho;
}else{
i = tamHeap;
}
}
}
//=============================================================================
void heapsort(int *array, int n) {
//Alterar o vetor ignorando a posicao zero
int arrayTmp[n+1];
for(int i = 0; i < n; i++){
arrayTmp[i+1] = array[i];
}
//Contrucao do heap
for(int tamHeap = 2; tamHeap <= n; tamHeap++){
construir(arrayTmp, tamHeap);
}
//Ordenacao propriamente dita
int tamHeap = n;
while(tamHeap > 1){
swap(arrayTmp + 1, arrayTmp + tamHeap--);
reconstruir(arrayTmp, tamHeap);
}
//Alterar o vetor para voltar a posicao zero
for(int i = 0; i < n; i++){
array[i] = arrayTmp[i+1];
}
}
//=============================================================================
#include "heapsort.h"
//=============================================================================
void construir(int *array, int tamHeap){
for(int i = tamHeap; i > 1 && array[i] > array[i/2]; i /= 2){
swap(array + i, array + i/2);
}
}
//=============================================================================
int getMaiorFilho(int *array, int i, int tamHeap){
int filho;
if (2*i == tamHeap || array[2*i] > array[2*i+1]){
filho = 2*i;
} else {
filho = 2*i + 1;
}
return filho;
}
//=============================================================================
void reconstruir(int *array, int tamHeap){
int i = 1;
while(i <= (tamHeap/2)){
int filho = getMaiorFilho(array, i, tamHeap);
if(array[i] < array[filho]){
swap(array + i, array + filho);
i = filho;
}else{
i = tamHeap;
}
}
}
//=============================================================================
void heapsort(int *array, int n) {
//Alterar o vetor ignorando a posicao zero
int arrayTmp[n+1];
for(int i = 0; i < n; i++){
arrayTmp[i+1] = array[i];
}
//Contrucao do heap
for(int tamHeap = 2; tamHeap <= n; tamHeap++){
construir(arrayTmp, tamHeap);
}
//Ordenacao propriamente dita
int tamHeap = n;
while(tamHeap > 1){
swap(arrayTmp + 1, arrayTmp + tamHeap--);
reconstruir(arrayTmp, tamHeap);
}
//Alterar o vetor para voltar a posicao zero
for(int i = 0; i < n; i++){
array[i] = arrayTmp[i+1];
}
}
//=============================================================================

View File

@ -1,14 +1,14 @@
#ifndef HEAPSORT_H
#define HEAPSORT_H
//=============================================================================
#include "geracao.h"
//=============================================================================
void construir(int *array, int tamHeap);
//=============================================================================
int getMaiorFilho(int *array, int i, int tamHeap);
//=============================================================================
void reconstruir(int *array, int tamHeap);
//=============================================================================
void heapsort(int *array, int n);
//=============================================================================
#endif
#ifndef HEAPSORT_H
#define HEAPSORT_H
//=============================================================================
#include "geracao.h"
//=============================================================================
void construir(int *array, int tamHeap);
//=============================================================================
int getMaiorFilho(int *array, int i, int tamHeap);
//=============================================================================
void reconstruir(int *array, int tamHeap);
//=============================================================================
void heapsort(int *array, int n);
//=============================================================================
#endif

View File

@ -1,15 +1,15 @@
#include "insercao.h"
//=============================================================================
void insercao(int *array, int n){
for (int i = 1; i < n; i++) {
int tmp = array[i];
int j = i - 1;
while ((j >= 0) && (array[j] > tmp)) {
array[j + 1] = array[j];
j--;
}
array[j+1] = tmp;
}
}
//=============================================================================
#include "insercao.h"
//=============================================================================
void insercao(int *array, int n){
for (int i = 1; i < n; i++) {
int tmp = array[i];
int j = i - 1;
while ((j >= 0) && (array[j] > tmp)) {
array[j + 1] = array[j];
j--;
}
array[j+1] = tmp;
}
}
//=============================================================================

View File

@ -1,8 +1,8 @@
#ifndef INSERCAO_H
#define INSERCAO_H
//=============================================================================
#include "geracao.h"
//=============================================================================
void insercao(int *array, int n);
//=============================================================================
#endif
#ifndef INSERCAO_H
#define INSERCAO_H
//=============================================================================
#include "geracao.h"
//=============================================================================
void insercao(int *array, int n);
//=============================================================================
#endif

Some files were not shown because too many files have changed in this diff Show More